mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 13:55:58 +00:00
Merge upstream PC input and dual-screen updates
This commit is contained in:
commit
68b0396dfe
819 files changed
+43953
-6186
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,366 @@
|
||||
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
|
||||
var outputSize = 0 to 0
|
||||
private set
|
||||
private var attachedSurface: Surface? = null
|
||||
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
|
||||
|
||||
fun outputSizeFor(width: Int, height: Int, fullResolution: Boolean = false): Pair<Int, Int> =
|
||||
desktopOutputSize(width, height, fullResolution, TARGET_SHORT_SIDE)
|
||||
|
||||
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
|
||||
attachedSurface = surface
|
||||
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 resize(surface: Surface, width: Int, height: Int) {
|
||||
if (surface !== attachedSurface || width <= 0 || height <= 0 || outputSize == (width to height)) return
|
||||
outputSize = width to height
|
||||
pendingAttach?.data?.apply {
|
||||
putInt(Comp.KEY_WIDTH, width)
|
||||
putInt(Comp.KEY_HEIGHT, height)
|
||||
}
|
||||
service?.let { send(it, Message.obtain(null, Comp.MSG_RESIZE, width, height)) }
|
||||
}
|
||||
|
||||
fun detach(surface: Surface? = null) {
|
||||
if (surface != null && attachedSurface != null && surface !== attachedSurface) return
|
||||
attachedSurface = null
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun desktopOutputSize(width: Int, height: Int, fullResolution: Boolean, targetShortSide: Float): Pair<Int, Int> {
|
||||
if (width <= 0 || height <= 0) return 0 to 0
|
||||
val scale = if (fullResolution) 1f else maxOf(1f, Math.round(minOf(width, height) / targetShortSide * 2f) / 2f)
|
||||
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Notification
|
||||
import android.content.Context
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
|
||||
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
|
||||
|
||||
object BottomNotifications {
|
||||
val items = mutableStateListOf<BottomNotification>()
|
||||
|
||||
fun granted(context: Context): Boolean =
|
||||
context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
|
||||
|
||||
internal fun keep(own: String, pkg: String, ongoing: Boolean, groupSummary: Boolean, title: String, text: String): Boolean =
|
||||
pkg != own && !ongoing && !groupSummary && (title.isNotBlank() || text.isNotBlank())
|
||||
|
||||
internal fun add(list: MutableList<BottomNotification>, item: BottomNotification) {
|
||||
list.removeAll { it.key == item.key }
|
||||
list.add(0, item)
|
||||
while (list.size > MAX_ITEMS) list.removeAt(list.lastIndex)
|
||||
}
|
||||
|
||||
fun clear() = items.clear()
|
||||
|
||||
internal fun post(context: Context, sbn: StatusBarNotification) {
|
||||
val n = sbn.notification ?: return
|
||||
val extras = n.extras
|
||||
val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = (extras?.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras?.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
|
||||
if (!keep(context.packageName, sbn.packageName, sbn.isOngoing, (n.flags and Notification.FLAG_GROUP_SUMMARY) != 0, title, text)) return
|
||||
val app = runCatching {
|
||||
val pm = context.packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
|
||||
}.getOrDefault(sbn.packageName)
|
||||
add(items, BottomNotification(sbn.key, app, title, text, sbn.postTime))
|
||||
}
|
||||
|
||||
internal fun remove(key: String) {
|
||||
items.removeAll { it.key == key }
|
||||
}
|
||||
|
||||
private const val MAX_ITEMS = 30
|
||||
}
|
||||
|
||||
class BottomNotificationListener : NotificationListenerService() {
|
||||
override fun onListenerConnected() {
|
||||
BottomNotifications.clear()
|
||||
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
|
||||
|
||||
override fun onListenerDisconnected() = BottomNotifications.clear()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
|
||||
val model: Any get() = uri ?: file!!
|
||||
}
|
||||
|
||||
object BottomScreenshots {
|
||||
private const val FOLDER = "DroidDeck"
|
||||
private const val QUALITY = 95
|
||||
private const val LIMIT = 120
|
||||
|
||||
internal fun fileName(at: Long): String =
|
||||
"DroidDeck_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(at)) + ".jpg"
|
||||
|
||||
fun save(context: Context, bitmap: Bitmap, at: Long = System.currentTimeMillis()): Boolean = runCatching {
|
||||
val name = fileName(at)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = context.contentResolver
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Images.Media.DISPLAY_NAME, name)
|
||||
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
|
||||
put(MediaStore.Images.Media.DATE_TAKEN, at)
|
||||
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$FOLDER")
|
||||
put(MediaStore.Images.Media.IS_PENDING, 1)
|
||||
}
|
||||
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false
|
||||
val written = runCatching {
|
||||
resolver.openOutputStream(uri)?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } == true
|
||||
}.getOrDefault(false)
|
||||
if (!written) {
|
||||
resolver.delete(uri, null, null)
|
||||
return false
|
||||
}
|
||||
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
|
||||
true
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
|
||||
if (!dir.isDirectory && !dir.mkdirs()) return false
|
||||
val file = File(dir, name)
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) }
|
||||
android.media.MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf("image/jpeg"), null)
|
||||
true
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun list(context: Context, runtimeRoot: File): List<BottomShot> =
|
||||
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
|
||||
|
||||
private fun own(context: Context): List<BottomShot> = runCatching {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
|
||||
return dir.listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty()
|
||||
.map { BottomShot(null, it, it.lastModified(), steam = false) }
|
||||
}
|
||||
val shots = ArrayList<BottomShot>()
|
||||
context.contentResolver.query(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_ADDED),
|
||||
"${MediaStore.Images.Media.RELATIVE_PATH} = ?", arrayOf("${Environment.DIRECTORY_PICTURES}/$FOLDER/"),
|
||||
"${MediaStore.Images.Media.DATE_ADDED} DESC",
|
||||
)?.use { c ->
|
||||
while (c.moveToNext() && shots.size < LIMIT) {
|
||||
val taken = c.getLong(1).takeIf { it > 0L } ?: (c.getLong(2) * 1000L)
|
||||
shots += BottomShot(android.content.ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getLong(0)),
|
||||
null, taken, steam = false)
|
||||
}
|
||||
}
|
||||
shots
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
internal fun steam(runtimeRoot: File): List<BottomShot> =
|
||||
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
|
||||
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
|
||||
File(account, "760/remote").listFiles { f -> f.isDirectory }.orEmpty().flatMap { app ->
|
||||
File(app, "screenshots").listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
}.map { BottomShot(null, it, it.lastModified(), steam = true) }
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.core.GameEnvironment
|
||||
import com.droiddeck.launcher.gpu.AppVulkan
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.github.luben.zstd.ZstdInputStream
|
||||
@@ -34,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)
|
||||
@@ -639,29 +639,31 @@ object ComponentsManager {
|
||||
}
|
||||
|
||||
|
||||
fun swap(context: Context, protonId: String, file: String): String = synchronized(lock) {
|
||||
fun swap(context: Context, protonId: String, file: String, auto: Boolean = false): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
val info = packageInfo(context, wcp)
|
||||
val state = loadState(context)
|
||||
if (inUse(context, p)) {
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version))
|
||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
||||
.apply { if (auto) put("auto", true) })
|
||||
saveState(context, state)
|
||||
return context.getString(R.string.cmgr_swap_queued, LABEL[info.comp], info.version, p.name)
|
||||
}
|
||||
applyPackage(context, p, info, wcp, state)
|
||||
applyPackage(context, p, info, wcp, state, auto)
|
||||
state.sub("queued").optJSONObject(p.id)?.remove(info.comp)
|
||||
saveState(context, state)
|
||||
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
||||
}
|
||||
|
||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject) {
|
||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
||||
ensureOriginal(context, p, info.comp, state)
|
||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||
.put("file", wcp.name).put("label", info.version).put("protonVersion", p.version)
|
||||
.put("files", JSONObject(hashes.filterKeys { owned(info.comp, it) } as Map<*, *>))
|
||||
.put("at", System.currentTimeMillis() / 1000))
|
||||
.put("at", System.currentTimeMillis() / 1000)
|
||||
.apply { if (auto) put("auto", true) })
|
||||
Log.i(TAG, "swapped ${info.comp} ${info.version} into ${p.name} ${p.version}")
|
||||
}
|
||||
|
||||
@@ -709,7 +711,7 @@ object ComponentsManager {
|
||||
applyOriginal(context, p, comp, v, File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp"), state)
|
||||
} else {
|
||||
val wcp = File(packagesDir(context), q.optString("file"))
|
||||
applyPackage(context, p, packageInfo(context, wcp), wcp, state)
|
||||
applyPackage(context, p, packageInfo(context, wcp), wcp, state, q.optBoolean("auto"))
|
||||
}
|
||||
done += "${LABEL[comp]} ${q.optString("label")} → ${p.name}"
|
||||
}.onFailure { Log.w(TAG, "queued $comp for ${p.name}", it) }
|
||||
@@ -976,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 ->
|
||||
@@ -1015,15 +1014,76 @@ object ComponentsManager {
|
||||
internal fun forcedPackageWanted(activeFile: String?, protonVersionMatches: Boolean): Boolean =
|
||||
activeFile.isNullOrEmpty() || !protonVersionMatches
|
||||
|
||||
internal fun bridgeDxvk(vk: AppVulkan?): ForcedPackage? = when {
|
||||
vk == null -> null
|
||||
!vk.atLeast(1, 1) -> null
|
||||
!vk.atLeast(1, 3) -> ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_1, "Dxvk-Linux")
|
||||
vk.shaderInt64 == false || (vk.maxPushConstants ?: 256) < 256 ->
|
||||
ForcedPackage(emptySet(), "dxvk", DXVK_FOR_VULKAN_1_3_NO_INT64, "Dxvk-Linux")
|
||||
else -> null
|
||||
}
|
||||
|
||||
internal const val DXVK_FOR_VULKAN_1_1 = "dxvk-1.10.3-linux.wcp"
|
||||
internal const val DXVK_FOR_VULKAN_1_3_NO_INT64 = "dxvk-2.6.2-linux.wcp"
|
||||
|
||||
internal fun autoDxvkUndoWanted(bridgeSession: Boolean, keepProtonDxvk: Boolean, vulkan: AppVulkan?, bridgeRule: ForcedPackage?): Boolean =
|
||||
!bridgeSession || keepProtonDxvk || (vulkan != null && bridgeRule == null)
|
||||
|
||||
private fun dropQueuedAuto(context: Context, installed: List<Proton>) = synchronized(lock) {
|
||||
val state = loadState(context)
|
||||
var changed = false
|
||||
for (p in installed) {
|
||||
val q = state.optJSONObject("queued")?.optJSONObject(p.id) ?: continue
|
||||
if (q.optJSONObject("dxvk")?.optBoolean("auto") == true) { q.remove("dxvk"); changed = true }
|
||||
}
|
||||
if (changed) saveState(context, state)
|
||||
}
|
||||
|
||||
internal fun autoChoiceStale(entry: JSONObject?, wantedFile: String?): Boolean =
|
||||
entry != null && entry.optBoolean("auto") && entry.optString("file") != wantedFile
|
||||
|
||||
internal fun catalogMatch(items: List<CatalogItem>, file: String, release: String): CatalogItem? =
|
||||
items.firstOrNull { it.file == file && it.release == release }
|
||||
|
||||
fun ensureForcedPackages(context: Context): String? = ensureForcedPackages(
|
||||
private val forcedLock = Any()
|
||||
|
||||
fun ensureForcedPackages(context: Context): String? = synchronized(forcedLock) { ensureForcedPackages(
|
||||
context, GpuInfo.detect(),
|
||||
{ file, release -> catalogItem(context, file, release) },
|
||||
{ download(context, it) {} },
|
||||
{ id, file -> swap(context, id, file) },
|
||||
)
|
||||
vulkan = AppVulkan.detect(context),
|
||||
bridgeSession = com.droiddeck.launcher.core.DeviceSupport.vkBridge(context),
|
||||
applyAuto = { id, file -> swap(context, id, file, auto = true) },
|
||||
undoAuto = { id, comp -> undoAutoChoice(context, id, comp) },
|
||||
keepProtonDxvk = SessionPrefs.bridgeProtonDxvk(context),
|
||||
autoPossible = !com.droiddeck.launcher.core.DeviceSupport.adreno(),
|
||||
) }
|
||||
|
||||
fun settleAutoDxvk(context: Context) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
runCatching { ensureForcedPackages(app) }
|
||||
.onSuccess { if (it != null) Log.i(TAG, it) }
|
||||
.onFailure { Log.w(TAG, "automatic DXVK", it) }
|
||||
}, "auto-dxvk").start()
|
||||
}
|
||||
|
||||
internal fun undoAutoChoice(context: Context, protonId: String, comp: String): String = synchronized(lock) {
|
||||
val p = proton(context, protonId)
|
||||
val state = loadState(context)
|
||||
val entry = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
|
||||
val sameProton = entry?.optString("protonVersion") == p.version
|
||||
if (sameProton && originalFile(context, p, comp).isFile)
|
||||
return restore(context, protonId, comp, safeName(p.version))
|
||||
if (sameProton) {
|
||||
Log.w(TAG, "${p.name}: its own ${LABEL[comp]} copy is gone; keeping ${entry?.optString("label")}")
|
||||
return "${LABEL[comp]}: ${p.name} keeps ${entry?.optString("label")} (its own copy is gone)"
|
||||
}
|
||||
state.sub("active").optJSONObject(p.id)?.remove(comp)
|
||||
saveState(context, state)
|
||||
"${LABEL[comp]}: ${p.name} keeps its own copy"
|
||||
}
|
||||
|
||||
internal fun ensureForcedPackages(
|
||||
context: Context,
|
||||
@@ -1031,16 +1091,35 @@ object ComponentsManager {
|
||||
lookup: (file: String, release: String) -> CatalogItem?,
|
||||
fetch: (CatalogItem) -> Unit,
|
||||
apply: (protonId: String, file: String) -> String,
|
||||
vulkan: AppVulkan? = null,
|
||||
bridgeSession: Boolean = false,
|
||||
applyAuto: (protonId: String, file: String) -> String = apply,
|
||||
undoAuto: (protonId: String, comp: String) -> String = { _, _ -> "" },
|
||||
keepProtonDxvk: Boolean = false,
|
||||
autoPossible: Boolean = true,
|
||||
): String? {
|
||||
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }
|
||||
if (rules.isEmpty()) return null
|
||||
val chooseDxvk = bridgeSession && !keepProtonDxvk
|
||||
val bridgeRule = if (chooseDxvk) bridgeDxvk(vulkan) else null
|
||||
val rules = FORCED_PACKAGES.filter { it.matches(gpu) }.map { it to false } + listOfNotNull(bridgeRule?.let { it to true })
|
||||
if (rules.isEmpty() && !autoPossible) return null
|
||||
val installed = protons(context)
|
||||
val lines = mutableListOf<String>()
|
||||
for (rule in rules) {
|
||||
fun each(p: Proton, what: () -> String): String =
|
||||
runCatching(what).getOrElse { e -> Log.w(TAG, "${p.name}: ${e.message}", e); "${p.name}: ${e.message ?: e.javaClass.simpleName}" }
|
||||
if (autoPossible && autoDxvkUndoWanted(bridgeSession, keepProtonDxvk, vulkan, bridgeRule)) {
|
||||
dropQueuedAuto(context, installed)
|
||||
val state = loadState(context)
|
||||
for (p in installed) {
|
||||
val entry = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject("dxvk")
|
||||
if (autoChoiceStale(entry, null)) lines.add(each(p) { undoAuto(p.id, "dxvk") })
|
||||
}
|
||||
}
|
||||
for ((rule, auto) in rules) {
|
||||
val state = loadState(context)
|
||||
val targets = installed.filter { p ->
|
||||
val active = state.optJSONObject("active")?.optJSONObject(p.id)?.optJSONObject(rule.comp)
|
||||
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version)
|
||||
forcedPackageWanted(active?.optString("file"), active?.optString("protonVersion") == p.version) ||
|
||||
(auto && autoChoiceStale(active, rule.file))
|
||||
}
|
||||
if (targets.isEmpty()) continue
|
||||
val missing = missingPackage(context, rule, lookup, fetch)
|
||||
@@ -1048,9 +1127,10 @@ object ComponentsManager {
|
||||
lines.add(missing)
|
||||
continue
|
||||
}
|
||||
lines.add(targets.joinToString("; ") { apply(it.id, rule.file) })
|
||||
if (auto) lines.add("${vulkan?.label}: DXVK ${rule.file}")
|
||||
lines.add(targets.joinToString("; ") { p -> if (auto) each(p) { applyAuto(p.id, rule.file) } else apply(p.id, rule.file) })
|
||||
}
|
||||
return lines.joinToString("; ").ifEmpty { null }
|
||||
return lines.filter { it.isNotEmpty() }.joinToString("; ").ifEmpty { null }
|
||||
}
|
||||
|
||||
private fun missingPackage(
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
object DesktopLocale {
|
||||
const val DEFAULT = "C.UTF-8"
|
||||
|
||||
private val regions = mapOf(
|
||||
"en" to "US", "id" to "ID", "ms" to "MY", "cs" to "CZ", "da" to "DK", "de" to "DE",
|
||||
"es" to "ES", "fr" to "FR", "it" to "IT", "hu" to "HU", "nl" to "NL", "nb" to "NO",
|
||||
"pl" to "PL", "pt" to "PT", "ro" to "RO", "fi" to "FI", "sv" to "SE", "vi" to "VN",
|
||||
"tr" to "TR", "el" to "GR", "bg" to "BG", "ru" to "RU", "uk" to "UA", "ar" to "EG",
|
||||
"hi" to "IN", "th" to "TH", "ja" to "JP", "ko" to "KR", "zh" to "CN",
|
||||
)
|
||||
|
||||
private val systemRegions = mapOf(
|
||||
"en" to setOf("US", "GB", "AU", "CA", "IN", "NZ", "IE", "ZA", "SG"),
|
||||
"fr" to setOf("FR", "CA", "BE", "CH", "LU"),
|
||||
"de" to setOf("DE", "AT", "CH", "LU"),
|
||||
"it" to setOf("IT", "CH"),
|
||||
"nl" to setOf("NL", "BE"),
|
||||
"pt" to setOf("PT", "BR"),
|
||||
"sv" to setOf("SE", "FI"),
|
||||
"ar" to setOf("EG", "SA", "AE", "MA", "DZ", "TN", "JO", "KW", "IQ"),
|
||||
)
|
||||
|
||||
private val traditionalRegions = setOf("TW", "HK", "MO")
|
||||
|
||||
fun lang(locale: Locale): String {
|
||||
val language = when (locale.language) {
|
||||
"in" -> "id"
|
||||
"no", "nn" -> "nb"
|
||||
else -> locale.language
|
||||
}
|
||||
val region = when {
|
||||
language == "es" && SteamLanguage.forLocale(locale) == "latam" ->
|
||||
locale.country.takeIf { it.length == 2 && it != "US" } ?: "MX"
|
||||
language == "zh" -> chineseRegion(locale)
|
||||
locale.country in systemRegions[language].orEmpty() -> locale.country
|
||||
else -> regions[language] ?: return DEFAULT
|
||||
}
|
||||
return "${language}_$region.UTF-8"
|
||||
}
|
||||
|
||||
private fun chineseRegion(locale: Locale): String = when {
|
||||
locale.script == "Hans" -> "CN"
|
||||
locale.script == "Hant" -> if (locale.country == "HK") "HK" else "TW"
|
||||
locale.country == "HK" -> "HK"
|
||||
locale.country in traditionalRegions -> "TW"
|
||||
else -> "CN"
|
||||
}
|
||||
|
||||
fun language(locale: Locale): String? {
|
||||
val lang = lang(locale)
|
||||
if (lang == DEFAULT) return null
|
||||
val full = lang.removeSuffix(".UTF-8")
|
||||
val short = full.substringBefore('_')
|
||||
return when {
|
||||
short == "en" -> full
|
||||
full == "zh_HK" -> "zh_HK:zh_TW:zh"
|
||||
else -> "$full:$short"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
data class Telemetry(
|
||||
val source: String,
|
||||
val speedKmh: Float? = null,
|
||||
val rpm: Float? = null,
|
||||
val maxRpm: Float? = null,
|
||||
val gear: String? = null,
|
||||
val throttle: Float? = null,
|
||||
val brake: Float? = null,
|
||||
val lap: Int? = null,
|
||||
val laps: Int? = null,
|
||||
val position: Int? = null,
|
||||
val fuel: Float? = null,
|
||||
val currentLapS: Float? = null,
|
||||
val lastLapS: Float? = null,
|
||||
val bestLapS: Float? = null,
|
||||
val gLat: Float? = null,
|
||||
val gLon: Float? = null,
|
||||
val steer: Float? = null,
|
||||
val tireTempsC: List<Float>? = null,
|
||||
val turboBar: Float? = null,
|
||||
val engineTempC: Float? = null,
|
||||
val oilTempC: Float? = null,
|
||||
val lights: Int? = null,
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
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 {
|
||||
val buf = ByteBuffer.wrap(data, 0, length).order(ByteOrder.LITTLE_ENDIAN)
|
||||
when (port) {
|
||||
CODEMASTERS_PORT -> codemasters(buf, length)
|
||||
FORZA_PORT -> forza(buf, length)
|
||||
OUTGAUGE_PORT -> outGauge(buf, length)
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
private const val MPS_TO_KMH = 3.6f
|
||||
private const val GRAVITY = 9.81f
|
||||
|
||||
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
|
||||
|
||||
private const val CM_LAP_TIME = 1
|
||||
private const val CM_SPEED = 7
|
||||
private const val CM_THROTTLE = 29
|
||||
private const val CM_STEER = 30
|
||||
private const val CM_BRAKE = 31
|
||||
private const val CM_GEAR = 33
|
||||
private const val CM_G_LAT = 34
|
||||
private const val CM_G_LON = 35
|
||||
private const val CM_LAP = 36
|
||||
private const val CM_RPM = 37
|
||||
private const val CM_POSITION = 39
|
||||
private const val CM_FUEL = 45
|
||||
private const val CM_FUEL_CAPACITY = 46
|
||||
private const val CM_LAPS = 60
|
||||
private const val CM_LAST_LAP = 62
|
||||
private const val CM_MAX_RPM = 63
|
||||
private const val CM_MIN_FLOATS = 38
|
||||
|
||||
internal fun codemasters(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < CM_MIN_FLOATS * 4) return null
|
||||
val floats = length / 4
|
||||
fun f(i: Int) = if (i < floats) buf.getFloat(i * 4) else 0f
|
||||
val gear = f(CM_GEAR).toInt()
|
||||
val capacity = f(CM_FUEL_CAPACITY)
|
||||
return Telemetry(
|
||||
source = "Codemasters",
|
||||
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
|
||||
rpm = f(CM_RPM) * 10f,
|
||||
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
|
||||
gear = when {
|
||||
gear == 0 -> "N"
|
||||
gear < 0 || gear == 10 -> "R"
|
||||
else -> gear.toString()
|
||||
},
|
||||
throttle = f(CM_THROTTLE).coerceIn(0f, 1f),
|
||||
brake = f(CM_BRAKE).coerceIn(0f, 1f),
|
||||
lap = f(CM_LAP).toInt() + 1,
|
||||
laps = f(CM_LAPS).toInt().takeIf { it > 0 },
|
||||
position = f(CM_POSITION).toInt().takeIf { it > 0 },
|
||||
fuel = if (capacity > 0f) (f(CM_FUEL) / capacity).coerceIn(0f, 1f) else null,
|
||||
currentLapS = f(CM_LAP_TIME).takeIf { it > 0f },
|
||||
lastLapS = f(CM_LAST_LAP).takeIf { it > 0f },
|
||||
gLat = f(CM_G_LAT),
|
||||
gLon = f(CM_G_LON),
|
||||
steer = f(CM_STEER).coerceIn(-1f, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
private const val FORZA_SLED = 232
|
||||
private const val FORZA_FM7 = 311
|
||||
private const val FORZA_HORIZON = 324
|
||||
private const val FORZA_FM2023 = 331
|
||||
private const val HORIZON_SHIFT = 12
|
||||
|
||||
internal fun forza(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < FORZA_SLED) return null
|
||||
val racing = buf.getInt(0) != 0
|
||||
val maxRpm = buf.getFloat(8)
|
||||
val rpm = buf.getFloat(16)
|
||||
val dash = when (length) {
|
||||
FORZA_FM7, FORZA_FM2023 -> FORZA_SLED
|
||||
FORZA_HORIZON -> FORZA_SLED + HORIZON_SHIFT
|
||||
else -> -1
|
||||
}
|
||||
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
|
||||
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
|
||||
return Telemetry(
|
||||
source = "Forza",
|
||||
speedKmh = buf.getFloat(dash + 12) * MPS_TO_KMH,
|
||||
rpm = rpm,
|
||||
maxRpm = maxRpm.takeIf { it > 0f },
|
||||
gear = if (gear == 0) "R" else gear.toString(),
|
||||
throttle = (buf.get(dash + 71).toInt() and 0xFF) / 255f,
|
||||
brake = (buf.get(dash + 72).toInt() and 0xFF) / 255f,
|
||||
lap = (buf.getShort(dash + 68).toInt() and 0xFFFF) + 1,
|
||||
position = (buf.get(dash + 70).toInt() and 0xFF).takeIf { it > 0 },
|
||||
fuel = buf.getFloat(dash + 44).coerceIn(0f, 1f),
|
||||
currentLapS = buf.getFloat(dash + 60).takeIf { it > 0f },
|
||||
lastLapS = buf.getFloat(dash + 56).takeIf { it > 0f },
|
||||
bestLapS = buf.getFloat(dash + 52).takeIf { it > 0f },
|
||||
gLat = buf.getFloat(20) / GRAVITY,
|
||||
gLon = buf.getFloat(28) / GRAVITY,
|
||||
steer = (buf.get(dash + 76).toFloat() / 127f).coerceIn(-1f, 1f),
|
||||
tireTempsC = tiresF.takeIf { f -> f.any { it > 0f } }?.map { (it - 32f) * 5f / 9f },
|
||||
)
|
||||
}
|
||||
|
||||
private const val OUTGAUGE_SIZE = 92
|
||||
|
||||
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < OUTGAUGE_SIZE) return null
|
||||
val gear = buf.get(10).toInt() and 0xFF
|
||||
return Telemetry(
|
||||
source = "OutGauge",
|
||||
speedKmh = buf.getFloat(12) * MPS_TO_KMH,
|
||||
rpm = buf.getFloat(16),
|
||||
gear = when (gear) {
|
||||
0 -> "R"
|
||||
1 -> "N"
|
||||
else -> (gear - 1).toString()
|
||||
},
|
||||
throttle = buf.getFloat(48).coerceIn(0f, 1f),
|
||||
brake = buf.getFloat(52).coerceIn(0f, 1f),
|
||||
fuel = buf.getFloat(28).coerceIn(0f, 1f),
|
||||
turboBar = buf.getFloat(20).takeIf { it != 0f },
|
||||
engineTempC = buf.getFloat(24).takeIf { it != 0f },
|
||||
oilTempC = buf.getFloat(36).takeIf { it != 0f },
|
||||
lights = buf.getInt(44).takeIf { buf.getInt(40) != 0 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
internal fun warThunder(json: String): List<Pair<String, String>> {
|
||||
val state = org.json.JSONObject(json)
|
||||
if (!state.optBoolean("valid", false)) return emptyList()
|
||||
return state.keys().asSequence().filter { it != "valid" }.mapNotNull { key ->
|
||||
val value = state.opt(key) as? Number ?: return@mapNotNull null
|
||||
key to if (value.toDouble() % 1.0 == 0.0) value.toLong().toString() else "%.1f".format(java.util.Locale.US, value.toDouble())
|
||||
}.toList()
|
||||
}
|
||||
|
||||
fun eliteStatusFile(runtimeRoot: java.io.File, mounts: Map<String, java.io.File>): java.io.File? {
|
||||
val libraries = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { it.parentFile } +
|
||||
SteamDownloadMonitor.STEAM_HOMES.map { java.io.File(runtimeRoot, "$it/steamapps") }
|
||||
return libraries.distinct().map { java.io.File(it, "compatdata/$ELITE_APP/$ELITE_STATUS") }.firstOrNull { it.isFile }
|
||||
}
|
||||
|
||||
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List<Int>?, val legal: String?, val balance: Long?)
|
||||
|
||||
internal fun elite(json: String): Elite? {
|
||||
val s = org.json.JSONObject(json)
|
||||
val fuel = s.optJSONObject("Fuel")
|
||||
val pips = s.optJSONArray("Pips")?.let { a -> (0 until a.length()).map { a.optInt(it) } }
|
||||
if (fuel == null && pips == null && !s.has("Cargo") && !s.has("Balance")) return null
|
||||
return Elite(
|
||||
fuelMain = fuel?.optDouble("FuelMain")?.takeIf { !it.isNaN() },
|
||||
fuelReserve = fuel?.optDouble("FuelReservoir")?.takeIf { !it.isNaN() },
|
||||
cargo = s.optDouble("Cargo").takeIf { !it.isNaN() },
|
||||
pips = pips,
|
||||
legal = s.optString("LegalState").takeIf { it.isNotEmpty() },
|
||||
balance = if (s.has("Balance")) s.optLong("Balance") else null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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.FusionHudHost.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,13 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
|
||||
}
|
||||
|
||||
fun prepare(): Boolean {
|
||||
sources = ""
|
||||
KgslBusy.status = "not tried"
|
||||
KgslClock.status = "not tried"
|
||||
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 +44,19 @@ 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")
|
||||
})
|
||||
createMissing(feeds.map { it.file })
|
||||
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 +76,217 @@ 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
|
||||
KgslBusy.status += ", but the stamps never moved"
|
||||
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 ->
|
||||
if (memstore?.mode == KgslBusy.MODE_CONTEXTS) "kgsl memstore per-context timestamps (all GPU work)"
|
||||
else "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 +294,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 +340,34 @@ 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 = ""
|
||||
|
||||
/** Why the no-root GPU readers work or not, for the HUD diagnostics export; empty where they were not needed. */
|
||||
fun readerStatus(): String =
|
||||
if (KgslBusy.status == "not tried" && KgslClock.status == "not tried") ""
|
||||
else "kgsl memstore ${KgslBusy.status}; GPU cycle counter ${KgslClock.status}"
|
||||
|
||||
private const val STALE_MS = 30_000L
|
||||
|
||||
fun guestLoadDir(root: File) = File(root, GUEST_LOAD_DIR.removePrefix("/"))
|
||||
|
||||
// A feed with no value yet (the HUD hidden at start) still needs its file, or binds() leaves its node out for
|
||||
// the whole session.
|
||||
internal fun createMissing(files: List<File>) = files.forEach { runCatching { it.createNewFile() } }
|
||||
|
||||
/** 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,67 @@
|
||||
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 nativeMode(handle: Long): Int
|
||||
@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)
|
||||
}
|
||||
|
||||
/** Which memstore entries are watched: [MODE_RINGBUFFER] or [MODE_CONTEXTS] (hardware-scheduled kernels). */
|
||||
val mode: Int = if (handle != 0L) runCatching { nativeMode(handle) }.getOrDefault(0) else 0
|
||||
|
||||
/** Running totals: busy samples, samples, samples in which a ringbuffer or context 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
|
||||
}
|
||||
}
|
||||
|
||||
const val MODE_RINGBUFFER = 1
|
||||
const val MODE_CONTEXTS = 2
|
||||
|
||||
/** What the last [open] found, for the HUD diagnostics export. */
|
||||
@Volatile var status = "not tried"
|
||||
|
||||
fun open(): Reader? {
|
||||
if (!loaded) {
|
||||
status = "gpuclock library did not load"
|
||||
return null
|
||||
}
|
||||
val error = IntArray(1)
|
||||
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
|
||||
if (handle == 0L) {
|
||||
status = "open failed: ${KgslErrors.describe(error[0])}"
|
||||
Log.i(TAG, "hud: no GPU load from the kgsl memstore (open error ${error[0]})")
|
||||
return null
|
||||
}
|
||||
val reader = Reader(handle)
|
||||
status = if (reader.mode == MODE_CONTEXTS) "per-context stamps (hardware-scheduled kernel)" else "ringbuffer stamps"
|
||||
Log.i(TAG, "hud: kgsl memstore reader uses $status")
|
||||
return reader
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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? = sample().takeIf { it > 0 }
|
||||
|
||||
/** MHz, or a negative native code: -errno from kgsl or [RANGE_CHECK_FAILED]. */
|
||||
@Synchronized fun sample(): Int = if (handle == 0L) CLOSED else nativeSample(handle)
|
||||
|
||||
@Synchronized override fun close() {
|
||||
if (handle != 0L) nativeClose(handle)
|
||||
handle = 0L
|
||||
}
|
||||
}
|
||||
|
||||
/** -EBADF, what the native side also returns for a closed handle. */
|
||||
private const val CLOSED = -9
|
||||
|
||||
/** The native sample code for a reading that failed its range checks (kgsl_clock.c sampler_mhz). */
|
||||
const val RANGE_CHECK_FAILED = -1000
|
||||
|
||||
/** What the last [open] found, for the HUD diagnostics export. */
|
||||
@Volatile var status = "not tried"
|
||||
|
||||
/** A sampler that already produced one good reading, or null (the reason goes to the log and [status]). */
|
||||
fun open(): Sampler? {
|
||||
if (!loaded) {
|
||||
status = "gpuclock library did not load"
|
||||
return null
|
||||
}
|
||||
val error = IntArray(1)
|
||||
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
|
||||
if (handle == 0L) {
|
||||
status = "open failed: ${KgslErrors.describe(error[0])}"
|
||||
Log.i(TAG, "hud: no GPU clock from the cycle counter (open error ${error[0]})")
|
||||
return null
|
||||
}
|
||||
val sampler = Sampler(handle)
|
||||
var code = 0
|
||||
val first = (0 until 3).firstNotNullOfOrNull {
|
||||
code = sampler.sample()
|
||||
code.takeIf { it > 0 }
|
||||
}
|
||||
if (first == null) {
|
||||
status = "no usable reading: ${KgslErrors.describe(code)}"
|
||||
Log.i(TAG, "hud: GPU cycle counter gave no usable reading ($code)")
|
||||
sampler.close()
|
||||
return null
|
||||
}
|
||||
status = "working ($first MHz at start)"
|
||||
Log.i(TAG, "hud: GPU clock from the cycle counter ($first MHz now)")
|
||||
return sampler
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** Readable text for the negative errno codes the gpuclock library returns. */
|
||||
internal object KgslErrors {
|
||||
fun describe(code: Int): String {
|
||||
if (code == 0) return "no error code"
|
||||
if (code == KgslClock.RANGE_CHECK_FAILED) return "sample out of range"
|
||||
val name = runCatching { android.system.OsConstants.errnoName(-code) }.getOrNull()
|
||||
return if (name != null) "$name ($code)" else "error $code"
|
||||
}
|
||||
}
|
||||
@@ -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++
|
||||
|
||||
@@ -4,7 +4,7 @@ import java.io.File
|
||||
|
||||
object OverlayShown {
|
||||
fun check(root: File): Boolean {
|
||||
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") }
|
||||
val config = File(root, "tmp").listFiles { f -> f.name.startsWith("mangohud.") || f.name == "droiddeck-mangohud.conf" }
|
||||
?.maxByOrNull { it.lastModified() } ?: return false
|
||||
return runCatching { !config.readText().contains("no_display") }.getOrDefault(false)
|
||||
}
|
||||
|
||||
@@ -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,17 +160,25 @@ 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",
|
||||
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"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",
|
||||
) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
|
||||
) + 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)
|
||||
}
|
||||
@@ -275,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()
|
||||
@@ -290,21 +297,15 @@ object SessionFiles {
|
||||
"stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " +
|
||||
"staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}",
|
||||
)
|
||||
if (startsSession) disableIdleSleep(home)
|
||||
if (!done) allDone = false
|
||||
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 {
|
||||
@@ -383,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) {
|
||||
@@ -400,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) {
|
||||
@@ -413,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
|
||||
@@ -424,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? {
|
||||
@@ -436,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(
|
||||
@@ -446,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
|
||||
@@ -459,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"
|
||||
@@ -486,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) {
|
||||
@@ -528,7 +517,38 @@ object SessionFiles {
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */
|
||||
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
|
||||
|
||||
internal fun disableIdleSleep(steamHome: File): Boolean {
|
||||
val config = File(steamHome, "config/config.vdf")
|
||||
val text = runCatching { config.readText() }.getOrNull() ?: return false
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val steam = findSteamBlock(text) ?: return false
|
||||
val system = findObject(text, "system", steam.open + 1, steam.close)
|
||||
val updated = if (system != null) {
|
||||
val block = text.substring(system.keyStart, system.close + 1)
|
||||
text.replaceRange(system.keyStart, system.close + 1, IDLE_SLEEP_TIMERS.fold(block) { acc, key -> setScalar(acc, key, "0", newline) })
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val section = (listOf(indent + "\"system\"", indent + "{") +
|
||||
IDLE_SLEEP_TIMERS.map { "$indent\t\"$it\"\t\t\"0\"" } + (indent + "}")).joinToString(newline) + newline
|
||||
text.substring(0, lineStart) + section + text.substring(lineStart)
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
return try {
|
||||
if (updated != text) {
|
||||
staged.writeText(updated)
|
||||
if (!staged.renameTo(config)) { staged.delete(); return false }
|
||||
}
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not disable Steam's idle sleep", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
@@ -598,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
|
||||
|
||||
|
||||
@@ -86,12 +86,26 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("animations", on).apply()
|
||||
}
|
||||
|
||||
fun dualScreenMode(context: Context): String =
|
||||
prefs(context).getString("dualScreenMode", null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
|
||||
?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
|
||||
private fun savedDualScreenMode(context: Context, key: String): String? =
|
||||
prefs(context).getString(key, null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
|
||||
|
||||
private fun legacyDualScreenMode(context: Context): String =
|
||||
if (!prefs(context).getBoolean("dualScreenLauncher", true)) com.droiddeck.launcher.input.DualScreen.MODE_OFF
|
||||
else savedDualScreenMode(context, "dualScreenMode") ?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
|
||||
|
||||
fun dualScreenMode(context: Context): String = legacyDualScreenMode(context)
|
||||
|
||||
fun setDualScreenMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("dualScreenMode", mode).apply()
|
||||
val sessions = dualScreenSessionMode(context)
|
||||
prefs(context).edit().remove("dualScreenLauncher").putString("dualScreenMode", mode).putString("dualScreenSessionMode", sessions).apply()
|
||||
}
|
||||
|
||||
fun dualScreenSessionMode(context: Context): String =
|
||||
savedDualScreenMode(context, "dualScreenSessionMode") ?: legacyDualScreenMode(context)
|
||||
|
||||
fun setDualScreenSessionMode(context: Context, mode: String) {
|
||||
val launcher = dualScreenMode(context)
|
||||
prefs(context).edit().remove("dualScreenLauncher").putString("dualScreenMode", launcher).putString("dualScreenSessionMode", mode).apply()
|
||||
}
|
||||
|
||||
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
|
||||
@@ -100,10 +114,66 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("secondScreenPanel", mode).apply()
|
||||
}
|
||||
|
||||
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
|
||||
/** 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 setDualScreenLauncher(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("dualScreenLauncher", on).apply()
|
||||
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) {
|
||||
prefs(context).edit().putString("statsSpeedUnit", id).apply()
|
||||
}
|
||||
|
||||
fun statsDash(context: Context): String? = prefs(context).getString("statsDash", null)
|
||||
|
||||
fun setStatsDash(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsDash", id).apply()
|
||||
}
|
||||
|
||||
fun telemetryAuto(context: Context): Boolean = prefs(context).getBoolean("telemetryAuto", true)
|
||||
|
||||
fun setTelemetryAuto(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
|
||||
}
|
||||
|
||||
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
|
||||
|
||||
fun setTelemetryOff(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
|
||||
}
|
||||
|
||||
fun dualScreenSessionControls(context: Context): Boolean = prefs(context).getBoolean("dualScreenSessionControls", true)
|
||||
@@ -124,13 +194,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)
|
||||
@@ -147,10 +210,10 @@ object SessionPrefs {
|
||||
}
|
||||
|
||||
fun storesView(context: Context): String =
|
||||
prefs(context).getString("storesView", null)?.takeIf { it in STORES_VIEWS } ?: STORES_VIEWS.first()
|
||||
prefs(context).getString("storesView", null)?.takeIf { it in STORES_VIEWS } ?: DEFAULT_STORES_VIEW
|
||||
|
||||
fun setStoresView(context: Context, view: String) {
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply()
|
||||
prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else DEFAULT_STORES_VIEW).apply()
|
||||
}
|
||||
|
||||
fun libraryCardLevel(context: Context): Int = prefs(context).getInt("libraryCardLevel", 2)
|
||||
@@ -199,6 +262,7 @@ object SessionPrefs {
|
||||
|
||||
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
||||
val STORES_VIEWS = listOf("cards", "capsules", "list")
|
||||
const val DEFAULT_STORES_VIEW = "capsules"
|
||||
|
||||
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
|
||||
|
||||
@@ -206,7 +270,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) {
|
||||
@@ -285,18 +348,44 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null)
|
||||
const val PC_KEYBOARD_SIZE_DEFAULT = 47
|
||||
val PC_KEYBOARD_SIZE_RANGE = 25..70
|
||||
const val PC_KEYBOARD_OPACITY_DEFAULT = 100
|
||||
val PC_KEYBOARD_OPACITY_RANGE = 30..100
|
||||
|
||||
fun setFusionHudConfig(context: Context, config: String) {
|
||||
prefs(context).edit().putString("fusionHud", config).apply()
|
||||
fun pcKeyboardSize(context: Context): Int =
|
||||
prefs(context).getInt("pcKeyboardSize", PC_KEYBOARD_SIZE_DEFAULT).takeIf { it in PC_KEYBOARD_SIZE_RANGE } ?: PC_KEYBOARD_SIZE_DEFAULT
|
||||
|
||||
fun setPcKeyboardSize(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("pcKeyboardSize", percent.coerceIn(PC_KEYBOARD_SIZE_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun fusionHudPosition(context: Context): Pair<Float, Float>? =
|
||||
prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
fun pcKeyboardOpacity(context: Context): Int =
|
||||
prefs(context).getInt("pcKeyboardOpacity", PC_KEYBOARD_OPACITY_DEFAULT).takeIf { it in PC_KEYBOARD_OPACITY_RANGE } ?: PC_KEYBOARD_OPACITY_DEFAULT
|
||||
|
||||
fun setPcKeyboardOpacity(context: Context, percent: Int) {
|
||||
prefs(context).edit().putInt("pcKeyboardOpacity", percent.coerceIn(PC_KEYBOARD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun pcKeyboardHiddenKeys(context: Context): Set<String> =
|
||||
idList(prefs(context).getString("pcKeyboardHiddenKeys", null)).toSet()
|
||||
|
||||
fun setPcKeyboardHiddenKeys(context: Context, hidden: Set<String>) {
|
||||
prefs(context).edit().putString("pcKeyboardHiddenKeys", hidden.joinToString(",")).apply()
|
||||
}
|
||||
|
||||
fun droidDeckHudConfig(context: Context): String? = prefs(context).getString("__KEEP_droidDeckHud__", null)
|
||||
|
||||
fun setDroidDeckHudConfig(context: Context, config: String) {
|
||||
prefs(context).edit().putString("__KEEP_droidDeckHud__", config).apply()
|
||||
}
|
||||
|
||||
fun droidDeckHudPosition(context: Context): Pair<Float, Float>? =
|
||||
prefs(context).getString("__KEEP_droidDeckHudPos__", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
?.takeIf { it.size == 2 }?.let { it[0] to it[1] }
|
||||
|
||||
fun setFusionHudPosition(context: Context, x: Float, y: Float) {
|
||||
prefs(context).edit().putString("fusionHudPos", "$x,$y").apply()
|
||||
fun setDroidDeckHudPosition(context: Context, x: Float, y: Float) {
|
||||
prefs(context).edit().putString("__KEEP_droidDeckHudPos__", "$x,$y").apply()
|
||||
}
|
||||
|
||||
const val HUD_COLOR_MINT = "mint"
|
||||
@@ -327,6 +416,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) {
|
||||
@@ -426,10 +521,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) {
|
||||
@@ -439,13 +530,12 @@ 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.
|
||||
*/
|
||||
fun pendingShaderPrecache(context: Context): Boolean? {
|
||||
val prefs = prefs(context)
|
||||
if (!prefs.contains("shaderPrecache")) return null
|
||||
if (!prefs.contains("shaderPrecache")) {
|
||||
if (steamConfig(context).exists()) return null
|
||||
prefs.edit().putBoolean("shaderPrecache", false).apply()
|
||||
}
|
||||
val on = prefs.getBoolean("shaderPrecache", true)
|
||||
val applied = shaderPrecacheApplied(context)
|
||||
val written = runCatching { applied.readText().trim() }.getOrNull() ?: return on
|
||||
@@ -460,9 +550,12 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("shaderPrecache", on).apply()
|
||||
}
|
||||
|
||||
private fun steamConfig(context: Context) =
|
||||
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf")
|
||||
|
||||
fun shaderPrecache(context: Context): Boolean = pendingShaderPrecache(context)
|
||||
?: runCatching { com.droiddeck.launcher.storage.SteamStorage.shaderPrecache(
|
||||
java.io.File(steamRoot(context, steamClientArch(context)), "config/config.vdf").readText()) }.getOrDefault(true)
|
||||
steamConfig(context).readText()) }.getOrDefault(true)
|
||||
|
||||
fun stretch16x9(context: Context): Boolean = prefs(context).getBoolean("stretch16x9", false)
|
||||
|
||||
@@ -607,7 +700,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)
|
||||
@@ -622,18 +714,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/<package>/files/droiddeck-stock-proot
|
||||
*/
|
||||
@JvmStatic
|
||||
fun allowStockProot(context: Context): Boolean =
|
||||
context.getExternalFilesDir(null)?.let { File(it, "droiddeck-stock-proot").isFile } == true
|
||||
@@ -686,6 +772,29 @@ object SessionPrefs {
|
||||
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
|
||||
@JvmStatic
|
||||
fun vkBridge(context: Context): Boolean = prefs(context).getBoolean("vkBridge", com.droiddeck.launcher.core.DeviceSupport.mali())
|
||||
|
||||
fun setVkBridge(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vkBridge", on).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun bridgeProtonDxvk(context: Context): Boolean = prefs(context).getBoolean("bridgeProtonDxvk", false)
|
||||
|
||||
fun setBridgeProtonDxvk(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("bridgeProtonDxvk", on).apply()
|
||||
}
|
||||
|
||||
fun vkBridgeSafe(context: Context): Boolean = prefs(context).getBoolean("vkBridgeSafe", true)
|
||||
|
||||
fun setVkBridgeSafe(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("vkBridgeSafe", on).apply()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun vkBridgeMode(context: Context): String = if (vkBridgeSafe(context)) "safe" else "performance"
|
||||
|
||||
fun setZinkLazy(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zinkLazy", on).apply()
|
||||
}
|
||||
@@ -719,7 +828,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)
|
||||
|
||||
@@ -782,6 +890,9 @@ object SessionPrefs {
|
||||
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
|
||||
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
|
||||
|
||||
fun battleNetFolder(context: Context, code: String): String? = prefs(context).getString("battleNetFolder:$code", null)
|
||||
fun setBattleNetFolder(context: Context, code: String, path: String) { prefs(context).edit().putString("battleNetFolder:$code", path).apply() }
|
||||
|
||||
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
|
||||
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
|
||||
|
||||
@@ -828,7 +939,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}" }
|
||||
}
|
||||
@@ -841,7 +952,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}"
|
||||
@@ -873,7 +984,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)
|
||||
|
||||
@@ -891,13 +1001,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)
|
||||
@@ -905,10 +1012,17 @@ object SessionPrefs {
|
||||
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
|
||||
}
|
||||
|
||||
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
|
||||
const val STARTUP_OFF = ""
|
||||
const val STARTUP_STEAM = "steam"
|
||||
const val STARTUP_DESKTOP = "desktop"
|
||||
|
||||
fun setRunSteamAtStartup(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("runSteamAtStartup", on).apply()
|
||||
fun startupSession(context: Context): String {
|
||||
val p = prefs(context)
|
||||
return p.getString("startupSession", null) ?: if (p.getBoolean("runSteamAtStartup", false)) STARTUP_STEAM else STARTUP_OFF
|
||||
}
|
||||
|
||||
fun setStartupSession(context: Context, id: String) {
|
||||
prefs(context).edit().putString("startupSession", id).remove("runSteamAtStartup").apply()
|
||||
}
|
||||
|
||||
fun addedGamesDirs(context: Context): List<String> {
|
||||
@@ -1015,21 +1129,34 @@ object SessionPrefs {
|
||||
if (previous != null && !p.contains("addedAppId:$folderPath")) {
|
||||
val moved = movedAddedGame(p.all, previous, folderPath)
|
||||
moved.keys.forEach { edit.remove(it) }
|
||||
moved.values.forEach { (name, value) ->
|
||||
when (value) {
|
||||
is String -> edit.putString(name, value)
|
||||
is Long -> edit.putLong(name, value)
|
||||
is Int -> edit.putInt(name, value)
|
||||
is Boolean -> edit.putBoolean(name, value)
|
||||
is Float -> edit.putFloat(name, value)
|
||||
}
|
||||
}
|
||||
moved.values.forEach { (name, value) -> edit.putValue(name, value) }
|
||||
val removed = removedAddedGames(context)
|
||||
if (previous in removed) edit.putString("removedAddedGames", removed.map { if (it == previous) folderPath else it }.joinToString("\n"))
|
||||
}
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
fun inheritAddedGame(context: Context, from: String, to: String) = synchronized(addedGameLock) {
|
||||
val p = prefs(context)
|
||||
val all = p.all
|
||||
val edit = p.edit()
|
||||
all.filterKeys { it.startsWith("added") && it.endsWith(":$from") }.forEach { (name, value) ->
|
||||
val key = name.removeSuffix(from) + to
|
||||
if (key !in all) edit.putValue(key, value)
|
||||
}
|
||||
edit.apply()
|
||||
}
|
||||
|
||||
private fun android.content.SharedPreferences.Editor.putValue(name: String, value: Any?) {
|
||||
when (value) {
|
||||
is String -> putString(name, value)
|
||||
is Long -> putLong(name, value)
|
||||
is Int -> putInt(name, value)
|
||||
is Boolean -> putBoolean(name, value)
|
||||
is Float -> putFloat(name, value)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun movedAddedGame(all: Map<String, *>, from: String, to: String): Map<String, Pair<String, Any?>> =
|
||||
all.filterKeys { it.startsWith("added") && it.endsWith(":$from") }.mapValues { (name, value) ->
|
||||
val moved = if (value is String && (value == from || value.startsWith("$from/"))) to + value.removePrefix(from) else value
|
||||
@@ -1048,13 +1175,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)
|
||||
|
||||
@@ -1084,32 +1209,21 @@ 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 = 120
|
||||
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.
|
||||
*/
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0): Int = when {
|
||||
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
|
||||
mirrorRefreshLimit <= 0 -> sessionLimit
|
||||
sessionLimit <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(mirrorRefreshLimit, sessionLimit)
|
||||
}
|
||||
const val PIP_FPS = 30
|
||||
|
||||
private const val STEAM_UI_FPS = 60f
|
||||
|
||||
fun steamUiPacing(context: Context): Boolean = prefs(context).getBoolean("steamUiPacing", true)
|
||||
|
||||
fun steamUiFpsLimit(refreshHz: Float): Int {
|
||||
val steps = ((refreshHz + 0.5f) / STEAM_UI_FPS).toInt()
|
||||
return if (steps < 2) 0 else (refreshHz / steps + 0.01f).toInt()
|
||||
fun compositorFpsLimit(mirrorRefreshLimit: Int, sessionLimit: Int = 0, pip: Boolean = false): Int {
|
||||
val limit = when {
|
||||
mirrorRefreshLimit <= 0 && sessionLimit <= 0 -> FPS_UNPACED
|
||||
mirrorRefreshLimit <= 0 -> sessionLimit
|
||||
sessionLimit <= 0 -> mirrorRefreshLimit
|
||||
else -> minOf(mirrorRefreshLimit, sessionLimit)
|
||||
}
|
||||
return if (pip && mirrorRefreshLimit <= 0 && (limit <= 0 || limit > PIP_FPS)) PIP_FPS else limit
|
||||
}
|
||||
|
||||
val upscalerChoices = listOf(
|
||||
@@ -1400,4 +1514,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()
|
||||
}
|
||||
}
|
||||
@@ -70,10 +70,13 @@ class SessionService : Service() {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private var suspendController: SessionSuspendController? = null
|
||||
private val steamDownloadMonitor = SteamDownloadMonitor()
|
||||
private val downloadMonitorExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "steam-download-monitor").apply { isDaemon = true } }
|
||||
private var downloadMonitorTask: Runnable? = null
|
||||
private var downloadActive = false
|
||||
private var clientInstallActive = false
|
||||
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
|
||||
private var steamLibraryMounts: Map<String, File>
|
||||
get() = SessionState.steamLibraryMounts
|
||||
set(value) { SessionState.steamLibraryMounts = value }
|
||||
private var suspendDownloadNow = false
|
||||
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
|
||||
private var steamDownloadsInBackground = false
|
||||
@@ -105,7 +108,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()
|
||||
@@ -345,7 +347,7 @@ class SessionService : Service() {
|
||||
screenOn = readScreenOn()
|
||||
manualPauseRequested = false
|
||||
suspendDownloadNow = false
|
||||
steamDownloadMonitor.reset()
|
||||
runOnDownloadMonitor { steamDownloadMonitor.reset() }
|
||||
downloadActive = false
|
||||
clientInstallActive = false
|
||||
steamSleepToken = null
|
||||
@@ -370,9 +372,10 @@ class SessionService : Service() {
|
||||
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
|
||||
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
|
||||
synchronized(stopLock) {
|
||||
val gen = synchronized(stopLock) {
|
||||
SessionState.steamClientArch = null
|
||||
SessionState.running = true
|
||||
++sessionGen
|
||||
}
|
||||
if (SessionState.stopRequested) {
|
||||
stopSession(0)
|
||||
@@ -383,7 +386,6 @@ class SessionService : Service() {
|
||||
SessionState.guestPid = -1
|
||||
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
|
||||
com.droiddeck.launcher.wayland.CompositorHost.newSession()
|
||||
val gen = ++sessionGen
|
||||
SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF }
|
||||
?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) }
|
||||
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
|
||||
@@ -439,7 +441,7 @@ class SessionService : Service() {
|
||||
LinuxRuntime.writeAccounts(this)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not write the guest's passwd/group", e)
|
||||
stopSession(-1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -466,8 +468,8 @@ class SessionService : Service() {
|
||||
} else {
|
||||
val message = getString(R.string.session_proot_missing)
|
||||
Log.e(TAG, "$message (pack ready=$prootPack)")
|
||||
SessionEvents.fail("PROOT_MISSING", message, -1)
|
||||
stopSession(-1)
|
||||
failSession(gen, "PROOT_MISSING", message, -1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -475,7 +477,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)
|
||||
@@ -488,7 +489,7 @@ class SessionService : Service() {
|
||||
GameEnvironmentStore.publish(this)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "could not publish the game environment", e)
|
||||
stopSession(-1)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
val sessionLog = File(sessionDir, "session.log")
|
||||
@@ -522,6 +523,7 @@ class SessionService : Service() {
|
||||
components.add(encoder)
|
||||
guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath)
|
||||
}
|
||||
startVkBridge(guest, sessionDir)
|
||||
|
||||
guest.add("BL_WIDTH=" + size.first)
|
||||
guest.add("BL_HEIGHT=" + size.second)
|
||||
@@ -533,7 +535,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))
|
||||
@@ -543,7 +544,6 @@ class SessionService : Service() {
|
||||
val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() }
|
||||
val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()
|
||||
SessionState.deckPad = false
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
deckBinds = emptyList()
|
||||
inputSysfs = null
|
||||
if (controllersOn) {
|
||||
@@ -576,6 +576,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 {
|
||||
@@ -587,7 +588,7 @@ class SessionService : Service() {
|
||||
val program = SessionState.program
|
||||
if (program.isNullOrEmpty()) {
|
||||
Log.e(TAG, "run mode without a program")
|
||||
stopSession(65)
|
||||
stopSession(65, gen)
|
||||
return
|
||||
}
|
||||
guest.add(program)
|
||||
@@ -642,9 +643,17 @@ 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)
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
runCatching { com.droiddeck.launcher.runtime.DesktopLanguage.ensure(this, com.droiddeck.launcher.core.AppLanguage.effective(this)) }
|
||||
.onFailure { Log.w(TAG, "desktop language pack: $it") }
|
||||
}
|
||||
|
||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||
networkLink.attach(this)
|
||||
@@ -674,7 +683,7 @@ class SessionService : Service() {
|
||||
}
|
||||
val program = programStatus(sessionRoot)
|
||||
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
|
||||
stopSession(program ?: status ?: -1)
|
||||
stopSession(program ?: status ?: -1, gen)
|
||||
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() })
|
||||
Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
|
||||
if (gen != sessionGen || !SessionState.running) {
|
||||
@@ -696,14 +705,17 @@ class SessionService : Service() {
|
||||
SessionEvents.guestStarted(pid)
|
||||
} else {
|
||||
SessionEvents.record("guest.start_failed", mapOf("pid" to pid))
|
||||
SessionEvents.fail("GUEST_START_FAILED", "The guest process could not be started", pid)
|
||||
stopSession(-1)
|
||||
failSession(gen, "GUEST_START_FAILED", "The guest process could not be started", pid)
|
||||
stopSession(-1, gen)
|
||||
return
|
||||
}
|
||||
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")
|
||||
@@ -717,6 +729,7 @@ class SessionService : Service() {
|
||||
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
|
||||
},
|
||||
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"),
|
||||
clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-clock"),
|
||||
pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis ->
|
||||
Log.i(TAG, "paged out $processes processes ($unacknowledged unacknowledged) in $millis ms: " +
|
||||
"resident ${residentKb / 1024} MB, zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
|
||||
@@ -727,6 +740,20 @@ class SessionService : Service() {
|
||||
))
|
||||
}
|
||||
},
|
||||
readBackAllowed = { SessionPrefs.ramCapMb(this) == 0 },
|
||||
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
|
||||
if (processes == 0) {
|
||||
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (RAM cap, or ${availableKb / 1024} MB available is too little)")
|
||||
} else {
|
||||
Log.i(TAG, "read back $processes processes in $millis ms: zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
|
||||
}
|
||||
mainHandler.post {
|
||||
SessionEvents.record("session.paged_in", mapOf(
|
||||
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
|
||||
"availableMb" to availableKb / 1024, "ms" to millis,
|
||||
))
|
||||
}
|
||||
},
|
||||
)
|
||||
updateDownloadMonitoring()
|
||||
mainHandler.post { updateSuspendPolicy() }
|
||||
@@ -748,15 +775,27 @@ class SessionService : Service() {
|
||||
return sessionDir
|
||||
}
|
||||
|
||||
private fun relativeMouseForSession(): Int {
|
||||
val game = if (SessionState.mode == MODE_RUN) SessionState.program?.let { "program:$it" }
|
||||
else SessionState.gameId?.toLongOrNull()?.toString()
|
||||
return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode
|
||||
}
|
||||
|
||||
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
|
||||
guest.add("/usr/bin/env")
|
||||
guest.add("-i")
|
||||
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
|
||||
guest.add("HOME=/root")
|
||||
guest.add("USER=root")
|
||||
guest.add("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
|
||||
guest.add("PATH=" + LinuxRuntime.GUEST_PATH)
|
||||
guest.add("TERM=xterm-256color")
|
||||
guest.add("LANG=C.UTF-8")
|
||||
if (SessionState.mode == MODE_DESKTOP) {
|
||||
val appLocale = com.droiddeck.launcher.core.AppLanguage.effective(this)
|
||||
guest.add("LANG=" + DesktopLocale.lang(appLocale))
|
||||
DesktopLocale.language(appLocale)?.let { guest.add("LANGUAGE=$it") }
|
||||
} else {
|
||||
guest.add("LANG=C.UTF-8")
|
||||
}
|
||||
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
|
||||
com.droiddeck.launcher.core.AppLanguage.effective(this),
|
||||
com.droiddeck.launcher.core.AppLanguage.system(this).country,
|
||||
@@ -780,7 +819,7 @@ class SessionService : Service() {
|
||||
?: SessionPrefs.androidDriver(this),
|
||||
linuxDriverId,
|
||||
)
|
||||
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
|
||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||
val tuOverride = tuDebugOverride()
|
||||
val tuDriver = sysmemDriver(linuxDriverId)
|
||||
@@ -792,6 +831,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
|
||||
@@ -812,13 +852,14 @@ class SessionService : Service() {
|
||||
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
|
||||
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
|
||||
if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
|
||||
relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") }
|
||||
if (com.droiddeck.launcher.core.ZramSupport.supported()) {
|
||||
guest.add("BL_ZRAM=1")
|
||||
if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") }
|
||||
if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0")
|
||||
}
|
||||
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
|
||||
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
|
||||
guest.add("AUDIO_DIRECT_DECAY=0")
|
||||
val extra = extraEnv() + agentEnvironment
|
||||
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
|
||||
extra.forEach { guest.add(it) }
|
||||
@@ -834,6 +875,27 @@ class SessionService : Service() {
|
||||
private fun noSteamGame(): Boolean =
|
||||
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET)
|
||||
|
||||
private fun startVkBridge(guest: MutableList<String>, sessionDir: File) {
|
||||
if (!com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)) return
|
||||
val socket = File(filesDir, "vkbridge/server.sock")
|
||||
val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log"))
|
||||
bridge.attach(this)
|
||||
components.add(bridge)
|
||||
com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "vkbridge-clocks.log")).let {
|
||||
it.attach(this)
|
||||
components.add(it)
|
||||
}
|
||||
guest.add("BL_VKBRIDGE=1")
|
||||
guest.add("VKBRIDGE_SOCKET=" + socket.path)
|
||||
guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path)
|
||||
guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this))
|
||||
LinuxRuntime.gpuStandIn(this)?.let { node ->
|
||||
guest.add("BL_DRM_STANDIN=$node")
|
||||
LinuxRuntime.deviceNumbers(node)?.let { guest.add("VKBRIDGE_DRM_RENDER=$it") }
|
||||
}
|
||||
Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket")
|
||||
}
|
||||
|
||||
private fun startAudio(guest: MutableList<String>, sessionDir: File, directAudioPack: Boolean): PulseAudioComponent {
|
||||
val wantsDirectAudio = directAudioPack &&
|
||||
(SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
|
||||
@@ -841,7 +903,7 @@ class SessionService : Service() {
|
||||
val wantsMic = SessionPrefs.micEnabled(this) &&
|
||||
checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
guest.add("BL_MIC_ENABLED=" + if (wantsMic) "1" else "0")
|
||||
guest.add("BANNER_AUDIO_DIRECT_MIC=" + if (wantsMic) "1" else "0")
|
||||
guest.add("AUDIO_DIRECT_MIC=" + if (wantsMic) "1" else "0")
|
||||
val audioDir = File(filesDir, "directaudio").apply { mkdirs() }
|
||||
val relaySocket = File(audioDir, "relay.sock")
|
||||
val micFifo = if (wantsMic) File(audioDir, "mic.fifo") else null
|
||||
@@ -869,7 +931,11 @@ class SessionService : Service() {
|
||||
}
|
||||
if (wantsDirectAudio) {
|
||||
guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR)
|
||||
guest.add("BANNER_AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
||||
guest.add("AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath)
|
||||
val lowLatency = com.droiddeck.launcher.audio.DirectAudioTiming.lowLatencyOutput()
|
||||
val timing = com.droiddeck.launcher.audio.DirectAudioTiming.environment(lowLatency)
|
||||
guest.addAll(timing)
|
||||
Log.i(TAG, "audio: Android output " + (if (lowLatency) "is low-latency; DirectAudio keeps its defaults" else "is not low-latency; DirectAudio uses " + timing.joinToString(" ")))
|
||||
}
|
||||
Log.i(TAG, "audio: client DirectAudio (in-process sink)" + (if (wantsDirectAudio) " + DirectAudio for games" else "")
|
||||
+ (if (wantsMic) " + microphone" else "") +
|
||||
@@ -974,7 +1040,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)
|
||||
@@ -1036,7 +1102,7 @@ class SessionService : Service() {
|
||||
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
|
||||
}
|
||||
}
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRoots(this)) {
|
||||
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRootsForXodus(this)) {
|
||||
if (host.isDirectory && host.canRead()) {
|
||||
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
|
||||
binds.add(host.path + ":" + guest)
|
||||
@@ -1081,8 +1147,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")))
|
||||
@@ -1107,6 +1208,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())
|
||||
@@ -1286,13 +1408,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
|
||||
@@ -1307,7 +1422,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
|
||||
@@ -1333,19 +1447,7 @@ 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 {
|
||||
val procs = File("/proc").listFiles() ?: return false
|
||||
for (p in procs) {
|
||||
if (!p.name.all(Char::isDigit)) continue
|
||||
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
|
||||
if (cmd.isEmpty()) continue
|
||||
val text = String(cmd).replace('\u0000', ' ')
|
||||
if (text.contains("SteamLaunch AppId=") || text.contains("waitforexitandrun")) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
private fun steamGameRunning(): Boolean = SteamGameProcess.running()
|
||||
|
||||
private fun resumeSession(panelVisible: Boolean = true) {
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
@@ -1557,7 +1659,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
|
||||
@@ -1580,7 +1681,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) {
|
||||
@@ -1599,6 +1699,7 @@ class SessionService : Service() {
|
||||
))
|
||||
if (shouldSuspend) {
|
||||
freezePending = true
|
||||
SessionState.suspending = true
|
||||
freezeCancelled = false
|
||||
val freezeSteamToken = steamSleepToken
|
||||
val freezeNativeToken = nativeSleepToken
|
||||
@@ -1607,6 +1708,7 @@ class SessionService : Service() {
|
||||
) { success ->
|
||||
mainHandler.post {
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
SessionState.suspending = false
|
||||
suspendOperationPending = false
|
||||
freezePending = false
|
||||
if (success) {
|
||||
@@ -1793,11 +1895,22 @@ class SessionService : Service() {
|
||||
}, "tracer-priority").start()
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int) {
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
private fun failSession(gen: Int, code: String, message: String, status: Int?) {
|
||||
synchronized(stopLock) {
|
||||
if (gen == sessionGen) SessionEvents.fail(code, message, status)
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopSession(status: Int, gen: Int? = null) {
|
||||
if (gen != null && gen != sessionGen) {
|
||||
Log.i(TAG, "ignoring a stop from session $gen; session $sessionGen is current")
|
||||
return
|
||||
}
|
||||
completeNativeSleep()
|
||||
val (ended, endedArch) = synchronized(stopLock) {
|
||||
if (gen != null && gen != sessionGen) return
|
||||
cancelQueuedSteamGame()
|
||||
gameExitWatchToken++
|
||||
if (!SessionState.running) return
|
||||
SessionEvents.record("guest.exited", mapOf("status" to status))
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
|
||||
@@ -1819,6 +1932,7 @@ class SessionService : Service() {
|
||||
GameThreadHints.stop()
|
||||
suspendOperationPending = false
|
||||
freezePending = false
|
||||
SessionState.suspending = false
|
||||
launchWatcher?.stopWatching()
|
||||
launchWatcher = null
|
||||
syncWatcher?.stopWatching()
|
||||
@@ -1829,6 +1943,7 @@ class SessionService : Service() {
|
||||
auxiliaryProcesses.toMap().also { auxiliaryProcesses.clear() }
|
||||
}
|
||||
SessionTerminal.clear(sessionGen)
|
||||
BottomDesktop.stop(this, stoppedGen)
|
||||
val controller = suspendController
|
||||
suspendController = null
|
||||
if (ended != null) {
|
||||
@@ -1896,7 +2011,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
|
||||
@@ -1905,6 +2020,9 @@ class SessionService : Service() {
|
||||
(getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.unregisterDisplayListener(displayListener)
|
||||
displayListenerRegistered = false
|
||||
}
|
||||
downloadMonitorTask?.let(mainHandler::removeCallbacks)
|
||||
downloadMonitorTask = null
|
||||
downloadMonitorExecutor.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -2028,12 +2146,20 @@ class SessionService : Service() {
|
||||
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
|
||||
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
|
||||
|
||||
private fun runOnDownloadMonitor(task: () -> Unit) {
|
||||
try {
|
||||
downloadMonitorExecutor.execute(task)
|
||||
} catch (e: java.util.concurrent.RejectedExecutionException) {
|
||||
Log.d(TAG, "download monitor already shut down")
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateDownloadMonitoring() {
|
||||
if (!downloadWatchWanted()) {
|
||||
val wasActive = downloadActive
|
||||
downloadMonitorTask?.let(mainHandler::removeCallbacks)
|
||||
downloadMonitorTask = null
|
||||
steamDownloadMonitor.reset()
|
||||
runOnDownloadMonitor { steamDownloadMonitor.reset() }
|
||||
downloadActive = false
|
||||
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
|
||||
clientInstallActive = false
|
||||
@@ -2055,18 +2181,30 @@ class SessionService : Service() {
|
||||
val wasInstalling = clientInstallActive
|
||||
clientInstallActive = !SessionState.firstFrameSeen &&
|
||||
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
|
||||
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
|
||||
root,
|
||||
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
|
||||
client = SessionState.steamClientArch,
|
||||
mounts = steamLibraryMounts,
|
||||
)
|
||||
if (wasInstalling != clientInstallActive) {
|
||||
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
|
||||
val receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid())
|
||||
val client = SessionState.steamClientArch
|
||||
val mounts = steamLibraryMounts
|
||||
val self = this
|
||||
val finish = { monitored: Boolean ->
|
||||
if (downloadMonitorTask === self) {
|
||||
downloadActive = clientInstallActive || monitored
|
||||
if (wasInstalling != clientInstallActive) {
|
||||
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
|
||||
}
|
||||
if (wasActive != downloadActive) refreshNotification()
|
||||
updateSuspendPolicy()
|
||||
mainHandler.postDelayed(self, DOWNLOAD_POLL_MS)
|
||||
}
|
||||
}
|
||||
if (clientInstallActive || !steamDownloadsInBackground) {
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
runOnDownloadMonitor {
|
||||
val monitored = runCatching { steamDownloadMonitor.poll(root, receivedBytes = receivedBytes, client = client, mounts = mounts) }
|
||||
.getOrDefault(false)
|
||||
mainHandler.post { finish(monitored) }
|
||||
}
|
||||
if (wasActive != downloadActive) refreshNotification()
|
||||
updateSuspendPolicy()
|
||||
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
|
||||
}
|
||||
}
|
||||
downloadMonitorTask = poll
|
||||
@@ -2135,9 +2273,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
|
||||
@@ -92,6 +92,10 @@ object SessionState {
|
||||
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
|
||||
@Volatile var secondScreenDisplay = -1
|
||||
@Volatile var secondScreenAutoOpened = false
|
||||
@Volatile var secondScreenProvisional = false
|
||||
@Volatile var gameOnBottom = false
|
||||
|
||||
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
|
||||
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
@@ -101,6 +105,7 @@ object SessionState {
|
||||
|
||||
@Volatile
|
||||
var followScreen = false
|
||||
var followScale = 1f
|
||||
|
||||
@Volatile
|
||||
var refreshHz: Float = 60f
|
||||
@@ -108,7 +113,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
|
||||
|
||||
|
||||
@@ -3,6 +3,9 @@ package com.droiddeck.launcher.session
|
||||
import android.os.Process
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.RejectedExecutionException
|
||||
@@ -19,8 +22,13 @@ internal class SessionSuspendController(
|
||||
private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 },
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor(),
|
||||
private val zramControl: File? = null,
|
||||
private val clockControl: File? = null,
|
||||
private val nowNanos: () -> Long = System::nanoTime,
|
||||
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _, _ -> },
|
||||
private val readBackAllowed: () -> Boolean = { true },
|
||||
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _ -> },
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
@@ -43,6 +51,8 @@ internal class SessionSuspendController(
|
||||
@Volatile private var closing = false
|
||||
@Volatile private var cancelled = false
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
private var frozenSince: Long? = null
|
||||
private var pagedOutTargets = emptyList<ProcessRecord>()
|
||||
|
||||
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
|
||||
cancelled = false
|
||||
@@ -93,6 +103,7 @@ internal class SessionSuspendController(
|
||||
} catch (_: Exception) {
|
||||
} finally {
|
||||
frozen = records.values.toList()
|
||||
if (complete && frozenSince == null) frozenSince = nowNanos()
|
||||
if (!complete) {
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
runAudio(resumeAudio)
|
||||
@@ -100,10 +111,10 @@ internal class SessionSuspendController(
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
completion(complete)
|
||||
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
|
||||
}
|
||||
@@ -111,16 +122,19 @@ internal class SessionSuspendController(
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
submit({
|
||||
val records = frozen
|
||||
advanceClock()
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
if (resumed) readBack()
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
fun closeAndResume(completion: () -> Unit) {
|
||||
closing = true
|
||||
submit({
|
||||
advanceClock()
|
||||
if (restoreSafely(frozen)) frozen = emptyList()
|
||||
completion()
|
||||
executor.shutdown()
|
||||
@@ -135,6 +149,23 @@ internal class SessionSuspendController(
|
||||
}
|
||||
}
|
||||
|
||||
private fun advanceClock() {
|
||||
val since = frozenSince ?: return
|
||||
frozenSince = null
|
||||
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
|
||||
try {
|
||||
RandomAccessFile(control, "rw").use { file ->
|
||||
val bytes = ByteArray(Long.SIZE_BYTES)
|
||||
file.readFully(bytes)
|
||||
val shift = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).long.coerceAtLeast(0L) +
|
||||
(nowNanos() - since).coerceAtLeast(0L)
|
||||
file.seek(0L)
|
||||
file.write(ByteBuffer.allocate(Long.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(shift).array())
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun runAudio(action: () -> Unit) {
|
||||
try {
|
||||
action()
|
||||
@@ -217,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) {
|
||||
@@ -244,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 {
|
||||
@@ -263,13 +290,12 @@ internal class SessionSuspendController(
|
||||
}
|
||||
}
|
||||
if (targets.isEmpty()) return
|
||||
pagedOutTargets = (pagedOutTargets + targets).distinct()
|
||||
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
|
||||
acks.values.forEach { it.delete() }
|
||||
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
|
||||
@@ -283,6 +309,57 @@ internal class SessionSuspendController(
|
||||
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
|
||||
}
|
||||
|
||||
private fun readBack() {
|
||||
val targets = pagedOutTargets.filterNot { isGone(it) }
|
||||
pagedOutTargets = emptyList()
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return
|
||||
if (targets.isEmpty() || closing) return
|
||||
val before = memoryKb(targets).second
|
||||
val (total, available) = meminfoKb()
|
||||
if (!readBackAllowed() || !canTake(before, total, available)) {
|
||||
pagedIn(0, before, before, available, 0)
|
||||
return
|
||||
}
|
||||
try {
|
||||
control.writeText("0")
|
||||
} catch (_: IOException) {
|
||||
return
|
||||
}
|
||||
val start = nowMillis()
|
||||
for (record in targets) send(record, SIGURG)
|
||||
var swap = before
|
||||
var unchanged = 0
|
||||
try {
|
||||
while (!closing && nowMillis() - start < READ_BACK_TIMEOUT_MS) {
|
||||
sleep(READ_BACK_POLL_MS)
|
||||
val current = memoryKb(targets).second
|
||||
unchanged = if (current == swap) unchanged + 1 else 0
|
||||
swap = current
|
||||
if (swap == 0L || unchanged >= READ_BACK_STABLE_POLLS) break
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
pagedIn(targets.size, swap, before, available, nowMillis() - start)
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
private fun meminfoKb(): Pair<Long, Long> = try {
|
||||
val values = HashMap<String, Long>()
|
||||
File(procRoot, "meminfo").forEachLine { line ->
|
||||
val name = line.substringBefore(':')
|
||||
if (name == "MemTotal" || name == "MemAvailable") {
|
||||
line.substringAfter(':').trim().substringBefore(' ').toLongOrNull()?.let { values[name] = it }
|
||||
}
|
||||
}
|
||||
(values["MemTotal"] ?: 0L) to (values["MemAvailable"] ?: 0L)
|
||||
} catch (_: IOException) {
|
||||
0L to 0L
|
||||
}
|
||||
|
||||
private fun isGone(record: ProcessRecord): Boolean =
|
||||
try { readProcess(record.pid)?.started != record.started } catch (_: Exception) { false }
|
||||
|
||||
@@ -303,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)
|
||||
@@ -370,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 }
|
||||
@@ -384,6 +457,12 @@ internal class SessionSuspendController(
|
||||
const val PAGE_OUT_POLL_MS = 100L
|
||||
const val PAGE_OUT_START_MS = 2_000L
|
||||
const val PAGE_OUT_TIMEOUT_MS = 12_000L
|
||||
const val READ_BACK_POLL_MS = 100L
|
||||
const val READ_BACK_STABLE_POLLS = 5
|
||||
const val READ_BACK_TIMEOUT_MS = 5_000L
|
||||
const val READ_BACK_HEADROOM_KB = 1_048_576L
|
||||
const val READ_BACK_AVAILABLE_FACTOR = 2L
|
||||
const val READ_BACK_TOTAL_SHARE = 10L
|
||||
const val RESTORE_CHECKS = 80
|
||||
const val FREEZE_TIMEOUT_MS = 8_000L
|
||||
const val FREEZE_MAX_PASSES = 256
|
||||
|
||||
@@ -12,13 +12,13 @@ object SettingsReset {
|
||||
private const val TAG = "SettingsReset"
|
||||
|
||||
internal val SESSION_KEYS = setOf(
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
|
||||
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "fusionHud", "fusionHudPos", "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",
|
||||
"stretch16x9", "picturePosition", "railLabels", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
@@ -27,7 +27,7 @@ object SettingsReset {
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"questDefaultsV1",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
|
||||
internal val SESSION_PREFIXES = listOf(
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
enum class StatsStrip(val id: String) {
|
||||
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 } ?: 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
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
enum class StatsDash(val id: String) {
|
||||
AUTO("auto"), SPEEDOMETER("speedometer"), CIRCUIT("circuit"), TRACE("trace"), DIALS("dials"), GLANCE("glance");
|
||||
|
||||
fun resolve(source: String): StatsDash = if (this != AUTO) this else when (source) {
|
||||
"Forza" -> CIRCUIT
|
||||
"OutGauge" -> DIALS
|
||||
else -> SPEEDOMETER
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val DRAWN = listOf(SPEEDOMETER, CIRCUIT, TRACE, DIALS, GLANCE)
|
||||
|
||||
fun from(id: String?): StatsDash = entries.firstOrNull { it.id == id } ?: AUTO
|
||||
|
||||
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
|
||||
|
||||
@@ -101,34 +101,6 @@ internal class SteamDownloadMonitor {
|
||||
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
|
||||
}
|
||||
|
||||
private fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
steamRoots += primary
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
return steamRoots.flatMap { root ->
|
||||
File(root, "steamapps").listFiles { file ->
|
||||
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
|
||||
}.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
private fun read(file: File): ManifestState {
|
||||
val text = runCatching { file.readText() }.getOrDefault("")
|
||||
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
@@ -137,9 +109,6 @@ internal class SteamDownloadMonitor {
|
||||
return ManifestState(downloaded, flags != 4L && (total <= 0L || downloaded < total))
|
||||
}
|
||||
|
||||
private fun value(text: String, key: String): String? =
|
||||
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
companion object {
|
||||
fun clientInstallPending(runtimeRoot: File): Boolean {
|
||||
val home = File(runtimeRoot, "root")
|
||||
@@ -149,12 +118,43 @@ internal class SteamDownloadMonitor {
|
||||
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
|
||||
}
|
||||
|
||||
internal fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
steamRoots += primary
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
return steamRoots.flatMap { root ->
|
||||
File(root, "steamapps").listFiles { file ->
|
||||
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
|
||||
}.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
internal fun value(text: String, key: String): String? =
|
||||
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
|
||||
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
|
||||
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
|
||||
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
|
||||
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
|
||||
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
|
||||
internal val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
|
||||
internal val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
|
||||
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
data class SteamDownload(
|
||||
val appId: String,
|
||||
val name: String,
|
||||
val done: Long,
|
||||
val total: Long,
|
||||
val shader: Boolean = false,
|
||||
val paused: Boolean = false,
|
||||
)
|
||||
|
||||
object SteamDownloads {
|
||||
fun read(runtimeRoot: File, mounts: Map<String, File> = emptyMap(), client: String? = null): List<SteamDownload> {
|
||||
val names = HashMap<String, String>()
|
||||
val apps = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { file ->
|
||||
val text = runCatching { file.readText() }.getOrNull() ?: return@mapNotNull null
|
||||
val id = SteamDownloadMonitor.value(text, "appid") ?: file.name.removePrefix("appmanifest_").removeSuffix(".acf")
|
||||
val name = SteamDownloadMonitor.value(text, "name") ?: id
|
||||
names[id] = name
|
||||
fromManifest(id, name, text)
|
||||
}.let(::onePerApp)
|
||||
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
|
||||
?: SteamDownloadMonitor.STEAM_HOMES
|
||||
val log = homes.map { File(runtimeRoot, "$it/logs/content_log.txt") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||
val shaders = log?.let { runningShaderUpdates(tail(it)) }.orEmpty()
|
||||
.map { SteamDownload(it, names[it] ?: it, 0L, 0L, shader = true) }
|
||||
return apps + shaders
|
||||
}
|
||||
|
||||
internal fun onePerApp(downloads: List<SteamDownload>): List<SteamDownload> =
|
||||
downloads.groupBy { it.appId }.values.map { same -> same.maxBy { it.done } }
|
||||
|
||||
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
|
||||
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
if (flags == FULLY_INSTALLED) return null
|
||||
val done = SteamDownloadMonitor.value(text, "BytesDownloaded")?.toLongOrNull() ?: 0L
|
||||
val total = SteamDownloadMonitor.value(text, "BytesToDownload")?.toLongOrNull() ?: 0L
|
||||
if (total > 0L && done >= total) return null
|
||||
if ((flags and UPDATE_REQUIRED) == 0L && total <= 0L) return null
|
||||
return SteamDownload(id, name, done, total, paused = (flags and UPDATE_PAUSED) != 0L)
|
||||
}
|
||||
|
||||
internal fun runningShaderUpdates(lines: Sequence<String>): List<String> {
|
||||
val state = LinkedHashMap<String, Boolean>()
|
||||
for (line in lines) {
|
||||
if ("Client version:" in line) state.clear()
|
||||
val match = SteamDownloadMonitor.CONTENT_UPDATE.find(line) ?: continue
|
||||
if (match.groupValues[2] != "Shader") continue
|
||||
val running = match.groupValues[3].let { "Running Update" in it && "Stopping" !in it }
|
||||
state[match.groupValues[1]] = running
|
||||
}
|
||||
return state.filterValues { it }.keys.toList()
|
||||
}
|
||||
|
||||
private fun tail(file: File): Sequence<String> = runCatching {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val start = (raf.length() - TAIL_BYTES).coerceAtLeast(0L)
|
||||
raf.seek(start)
|
||||
val bytes = ByteArray((raf.length() - start).toInt())
|
||||
raf.readFully(bytes)
|
||||
String(bytes, Charsets.ISO_8859_1).lineSequence().drop(if (start > 0L) 1 else 0).toList().asSequence()
|
||||
}
|
||||
}.getOrDefault(emptySequence())
|
||||
|
||||
private const val FULLY_INSTALLED = 4L
|
||||
private const val UPDATE_REQUIRED = 2L
|
||||
private const val UPDATE_PAUSED = 512L
|
||||
private const val TAIL_BYTES = 256L * 1024L
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
|
||||
object SteamGameProcess {
|
||||
fun matches(cmdline: ByteArray): Boolean {
|
||||
val args = String(cmdline).split('\u0000')
|
||||
for (i in args.indices) {
|
||||
if (args[i] == "waitforexitandrun") return true
|
||||
if (args[i] == "SteamLaunch" && args.getOrNull(i + 1)?.startsWith("AppId=") == true) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun running(proc: File = File("/proc")): Boolean = proc.listFiles()?.any { p ->
|
||||
p.name.all(Char::isDigit) && runCatching { File(p, "cmdline").readBytes() }.getOrNull()?.let(::matches) == true
|
||||
} == true
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.files.StorageRoots
|
||||
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, picked: String, label: String? = null): AddResult {
|
||||
val entries = list(context)
|
||||
if (entries.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
|
||||
val path = innerLibrary(File(picked))?.path ?: picked
|
||||
val host = canonical(File(path))
|
||||
if (taken(context, entries).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 ?: defaultLabel(context, File(path))).ifEmpty { File(path).name })
|
||||
save(context, current + entry)
|
||||
SessionPrefs.setSteamLibraryNextId(context, next + 1)
|
||||
return AddResult.Added(entry)
|
||||
}
|
||||
}
|
||||
|
||||
private fun taken(context: Context, entries: List<Entry>): List<String> = entries.map { canonical(it.host) } + listOfNotNull(
|
||||
GameStorage.effective(context)?.let { canonical(File(it.path)) },
|
||||
canonical(SessionPrefs.steamRoot(context, "arm64")),
|
||||
)
|
||||
|
||||
class Found(val path: String, val shown: String, val label: String, val games: Int)
|
||||
|
||||
/** Reads storage; call off the main thread. */
|
||||
fun found(context: Context): List<Found> {
|
||||
val entries = list(context)
|
||||
val taken = taken(context, entries) + AddedGames.roots(context).map { canonical(it.host) }
|
||||
val hits = ArrayList<Pair<File, Int>>()
|
||||
for (root in StorageRoots.list(context)) {
|
||||
if (!root.readable) continue
|
||||
for (dir in candidates(rawView(root.dir), SCAN_DEPTH)) {
|
||||
val games = gameCount(dir)
|
||||
if (games > 0 && File(dir, "steamapps").canWrite() && taken.none { overlaps(it, canonical(dir)) }) hits += dir to games
|
||||
}
|
||||
}
|
||||
val picked = ArrayList<Pair<File, Int>>()
|
||||
for (hit in hits.sortedByDescending { it.second }) {
|
||||
if (picked.none { overlaps(canonical(it.first), canonical(hit.first)) }) picked += hit
|
||||
}
|
||||
return picked.map { (dir, games) ->
|
||||
val shown = File(storagePath(dir.path))
|
||||
Found(dir.path, shown.path, defaultLabel(context, shown), games)
|
||||
}
|
||||
}
|
||||
|
||||
/** The FUSE view under /storage hides files other apps wrote unless DroidDeck has all files access; the raw card mount does not. */
|
||||
private fun rawView(dir: File): File {
|
||||
if (!dir.path.startsWith("/storage/") || dir.path.startsWith("/storage/emulated")) return dir
|
||||
val raw = File("/mnt/media_rw/" + dir.path.removePrefix("/storage/"))
|
||||
return if (raw.canRead() && raw.list() != null) raw else dir
|
||||
}
|
||||
|
||||
internal fun innerLibrary(picked: File): File? {
|
||||
if (gameCount(picked) > 0) return null
|
||||
return candidates(picked, 1).filter { it != picked && gameCount(it) > 0 }.singleOrNull()
|
||||
}
|
||||
|
||||
internal fun candidates(root: File, depth: Int): List<File> {
|
||||
val out = arrayListOf(root)
|
||||
var level = listOf(root)
|
||||
repeat(depth) {
|
||||
level = level.flatMap { dir ->
|
||||
dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") && f.name != "steamapps" && !(dir == root && f.name == "Android") }
|
||||
.orEmpty().sortedBy { it.name }
|
||||
}.take(SCAN_LIMIT - out.size)
|
||||
out += level
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun gameCount(library: File): Int {
|
||||
val steamapps = File(library, "steamapps")
|
||||
val manifests = steamapps.list()?.count { it.startsWith("appmanifest_") && it.endsWith(".acf") } ?: return 0
|
||||
return manifests + depotInstalls(File(steamapps, "common")).size
|
||||
}
|
||||
|
||||
/** Finished downloads another client left without a Steam manifest; the importer registers them from depot.config. */
|
||||
fun depotInstalls(common: File): List<File> {
|
||||
val managed = AddedGames.steamInstallDirs(common)
|
||||
return common.listFiles { f ->
|
||||
f.isDirectory && f.name.lowercase() !in managed &&
|
||||
File(f, ".download_complete").isFile && depotRecord(File(f, ".DepotDownloader"))
|
||||
}.orEmpty().sortedBy { it.name.lowercase() }
|
||||
}
|
||||
|
||||
private fun depotRecord(dir: File): Boolean = File(dir, "depot.config").isFile ||
|
||||
File(dir, "completed").list()?.any { it.matches(Regex("\\d+_\\d+\\.manifest")) } == true
|
||||
|
||||
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, picked: File): String {
|
||||
val folder = File(storagePath(picked.path))
|
||||
val volume = try {
|
||||
context.getSystemService(StorageManager::class.java)?.getStorageVolume(folder)?.getDescription(context)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
val parent = folder.parentFile
|
||||
val named = if (folder.name.equals("Steam", true) && parent != null && !volumeRoot(parent)) parent else folder
|
||||
val name = named.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))
|
||||
}
|
||||
|
||||
private fun volumeRoot(dir: File): Boolean = dir.parent in setOf("/storage", "/mnt/media_rw", "/storage/emulated") || dir.parent == null
|
||||
|
||||
internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/")
|
||||
|
||||
private fun storagePath(path: String): String = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
|
||||
|
||||
private fun canonical(file: File): String = storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath))
|
||||
|
||||
private const val SCAN_DEPTH = 2
|
||||
private const val SCAN_LIMIT = 4000
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import java.io.File
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
data class WebCookie(val host: String, val header: String)
|
||||
|
||||
object SteamWebLogin {
|
||||
val HOSTS = listOf("steamcommunity.com", "steam-chat.com")
|
||||
private const val COOKIES = "config/htmlcache/Default/Cookies"
|
||||
private const val V10 = "v10"
|
||||
private const val HOST_HASH_VERSION = 24
|
||||
private const val HOST_HASH_BYTES = 32
|
||||
|
||||
private val key: SecretKeySpec by lazy {
|
||||
val spec = PBEKeySpec("peanuts".toCharArray(), "saltysalt".toByteArray(), 1, 128)
|
||||
SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).encoded, "AES")
|
||||
}
|
||||
|
||||
internal fun decrypt(encrypted: ByteArray, hostHashed: Boolean): String? = runCatching {
|
||||
if (encrypted.size <= V10.length || String(encrypted, 0, V10.length, Charsets.US_ASCII) != V10) return null
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(ByteArray(16) { ' '.code.toByte() }))
|
||||
val plain = cipher.doFinal(encrypted, V10.length, encrypted.size - V10.length)
|
||||
val value = if (hostHashed && plain.size >= HOST_HASH_BYTES) plain.copyOfRange(HOST_HASH_BYTES, plain.size) else plain
|
||||
String(value, Charsets.UTF_8)
|
||||
}.getOrNull()
|
||||
|
||||
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 ""
|
||||
}
|
||||
|
||||
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()
|
||||
scratch.deleteRecursively()
|
||||
if (!scratch.mkdirs()) return emptyList()
|
||||
return try {
|
||||
val copy = File(scratch, "Cookies")
|
||||
store.copyTo(copy, overwrite = true)
|
||||
File(store.path + "-journal").takeIf { it.length() > 0L }?.copyTo(File(scratch, "Cookies-journal"), overwrite = true)
|
||||
SQLiteDatabase.openDatabase(copy.path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->
|
||||
val version = db.rawQuery("SELECT value FROM meta WHERE key = 'version'", null).use { if (it.moveToFirst()) it.getString(0).toIntOrNull() else null } ?: 0
|
||||
val marks = HOSTS.joinToString { "?" }
|
||||
db.rawQuery("SELECT host_key, name, value, encrypted_value, is_httponly FROM cookies WHERE host_key IN ($marks)", HOSTS.toTypedArray()).use { c ->
|
||||
val out = ArrayList<WebCookie>()
|
||||
while (c.moveToNext()) {
|
||||
val name = c.getString(1)
|
||||
val value = c.getString(2).takeUnless { it.isNullOrEmpty() }
|
||||
?: decrypt(c.getBlob(3) ?: continue, version >= HOST_HASH_VERSION) ?: continue
|
||||
out += WebCookie(c.getString(0), header(name, value, c.getInt(4) != 0))
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
} finally {
|
||||
scratch.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
|
||||
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)
|
||||
|
||||
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),
|
||||
2440510 to MenuGame("Forza Motorsport", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
284160 to MenuGame("BeamNG.drive", "OutGauge", GameTelemetry.OUTGAUGE_PORT),
|
||||
)
|
||||
|
||||
internal const val ORIGINAL_SUFFIX = ".droiddeck-original"
|
||||
private const val MY_GAMES = "pfx/drive_c/users/steamuser/Documents/My Games"
|
||||
private const val CONFIG = "hardwaresettings/hardware_settings_config.xml"
|
||||
private const val ADDRESS = "127.0.0.1"
|
||||
private const val EXTRADATA = "3"
|
||||
private val TAGS = listOf("udp", "motion")
|
||||
private val BYTES = Charsets.ISO_8859_1
|
||||
|
||||
fun scan(compatdata: List<File>): List<Game> = compatdata.asSequence()
|
||||
.flatMap { root -> root.listFiles { f -> f.isDirectory }.orEmpty().asSequence() }
|
||||
.flatMap { prefix -> File(prefix, MY_GAMES).listFiles { f -> f.isDirectory }.orEmpty().asSequence().map { prefix to it } }
|
||||
.mapNotNull { (prefix, game) ->
|
||||
val file = File(game, CONFIG)
|
||||
val text = runCatching { file.readText(BYTES) }.getOrNull() ?: return@mapNotNull null
|
||||
val element = element(text) ?: return@mapNotNull null
|
||||
Game(game.name, prefix.name, file, pointsHere(element.value))
|
||||
}
|
||||
.sortedBy { it.name.lowercase() }
|
||||
.toList()
|
||||
|
||||
fun set(game: Game, on: Boolean): Boolean = runCatching {
|
||||
val file = game.file
|
||||
val original = File(file.path + ORIGINAL_SUFFIX)
|
||||
val xml = file.readText(BYTES)
|
||||
val next = if (on) {
|
||||
if (!original.exists()) file.copyTo(original)
|
||||
turnedOn(xml)
|
||||
} else {
|
||||
turnedOff(xml, original.takeIf { it.isFile }?.readText(BYTES))
|
||||
}
|
||||
checkNotNull(next)
|
||||
val tmp = File(file.path + ".droiddeck-tmp")
|
||||
tmp.writeText(next, BYTES)
|
||||
check(tmp.renameTo(file))
|
||||
if (!on) original.delete()
|
||||
true
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun applyAutomatic(context: Context, running: String?) {
|
||||
if (!SessionPrefs.telemetryAuto(context)) return
|
||||
automaticTargets(scan(Library.compatdataDirs(context)), SessionPrefs.telemetryOff(context), running).forEach { set(it, true) }
|
||||
}
|
||||
|
||||
internal fun key(game: Game) = "${game.prefixId}/${game.name}"
|
||||
|
||||
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) }
|
||||
|
||||
internal fun restoreTargets(games: List<Game>, running: String?): List<Game> =
|
||||
games.filter { File(it.file.path + ORIGINAL_SUFFIX).isFile && !isRunning(it.prefixId, running) }
|
||||
|
||||
internal fun isRunning(prefixId: String, running: String?): Boolean {
|
||||
val id = running?.toLongOrNull() ?: return running != null
|
||||
return prefixId == id.toString() || prefixId == id.toInt().toString()
|
||||
}
|
||||
|
||||
internal fun element(xml: String): MatchResult? = TAGS.firstNotNullOfOrNull { tag -> tagRegex(tag).find(xml) }
|
||||
|
||||
internal fun pointsHere(element: String): Boolean =
|
||||
attr(element, "enabled") == "true" && attr(element, "ip") == ADDRESS &&
|
||||
attr(element, "port") == GameTelemetry.CODEMASTERS_PORT.toString() &&
|
||||
(attr(element, "extradata") ?: EXTRADATA) == EXTRADATA
|
||||
|
||||
internal fun turnedOn(xml: String): String? {
|
||||
val element = element(xml) ?: return null
|
||||
var on = withAttr(element.value, "enabled", "true")
|
||||
on = withAttr(on, "ip", ADDRESS)
|
||||
on = withAttr(on, "port", GameTelemetry.CODEMASTERS_PORT.toString())
|
||||
if (attr(on, "extradata") != null) on = withAttr(on, "extradata", EXTRADATA)
|
||||
return xml.replaceRange(element.range, on)
|
||||
}
|
||||
|
||||
internal fun turnedOff(xml: String, original: String?): String? {
|
||||
val element = element(xml) ?: return null
|
||||
val tag = element.value.drop(1).takeWhile { !it.isWhitespace() }
|
||||
val before = original?.let { tagRegex(tag).find(it)?.value }
|
||||
return xml.replaceRange(element.range, before ?: withAttr(element.value, "enabled", "false"))
|
||||
}
|
||||
|
||||
internal fun attr(element: String, name: String): String? =
|
||||
Regex("\\s$name=\"([^\"]*)\"").find(element)?.groupValues?.get(1)
|
||||
|
||||
internal fun withAttr(element: String, name: String, value: String): String {
|
||||
val existing = Regex("(\\s$name=\")[^\"]*\"")
|
||||
if (existing.containsMatchIn(element)) return existing.replace(element) { it.groupValues[1] + value + "\"" }
|
||||
val selfClosing = element.endsWith("/>")
|
||||
val body = element.dropLast(if (selfClosing) 2 else 1).trimEnd()
|
||||
return "$body $name=\"$value\"" + if (selfClosing) " />" else ">"
|
||||
}
|
||||
|
||||
private fun tagRegex(tag: String) = Regex("<$tag\\s[^>]*>")
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user