mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Rename the app SteamDeck → DroidDeck
App name, app ID and code package: DroidDeck, com.droiddeck.launcher (sources moved to com/droiddeck/launcher, the 68 JNI functions renamed with them). The new app ID installs beside SteamDeck rather than over it. Everywhere the name was the app's own: the sidebar title, the session report, share zips, the shell title, wake-lock and log tags, User-Agents, the Compose theme, the Download folder and switch files (droiddeck-env, -osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the old names are not read), and inside the runtime (droiddeck-desktop, Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project, README and the progress log follow. Kept on purpose: Valve's Steam Deck (the -steamdeck flag, steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud package URLs) and names inside the hosted desktop package (steamdeck.png, steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for labwc instead of the launcher the app stages itself. A committed __pycache__ .pyc is removed.
This commit is contained in:
1 parent
a19dfb88a0
commit
d160f464b6
118 files changed
+498
-487
No files matched your search
@@ -0,0 +1,134 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.File
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* The battery the Steam client can see.
|
||||
*
|
||||
* The client reads `/sys/class/power_supply/BAT<n>/...` - a laptop's or a Deck's naming and files
|
||||
* (`energy_now`, `power_now`, `time_to_empty_now`, a `uevent` of `POWER_SUPPLY_*` lines). Android
|
||||
* names its supply `battery` and lays it out differently, and on many phones an app may not read
|
||||
* it at all, so the client showed no battery. This writes a `BAT0` (and a `BAT1`, the Deck's name)
|
||||
* from Android's own battery API - the same on every device - into a directory the session binds
|
||||
* over `/sys/class/power_supply`, refreshed every few seconds while the session runs.
|
||||
*
|
||||
* Values: charge in µAh from the charge counter; energy in µWh from charge × voltage; power in µW
|
||||
* from |current| × voltage; time to empty from charge ÷ |average current| while discharging. Where
|
||||
* a device reports no current, the client still gets status and percentage.
|
||||
*/
|
||||
class BatteryComponent(val dir: File) : SessionPart() {
|
||||
@Volatile private var running = false
|
||||
private var thread: Thread? = null
|
||||
|
||||
override fun start() {
|
||||
running = true
|
||||
write()
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (running) write()
|
||||
}
|
||||
}, "battery-sysfs").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "battery: BAT0/BAT1 written to ${dir.path} every ${PERIOD_MS / 1000} s")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
running = false
|
||||
thread?.interrupt()
|
||||
thread = null
|
||||
}
|
||||
|
||||
private fun write() {
|
||||
val ctx = app() ?: return
|
||||
try {
|
||||
val bm = ctx.getSystemService(BatteryManager::class.java)
|
||||
val sticky: Intent? = ctx.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
val status = sticky?.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN) ?: BatteryManager.BATTERY_STATUS_UNKNOWN
|
||||
val level = sticky?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||
val scale = sticky?.getIntExtra(BatteryManager.EXTRA_SCALE, 100)?.takeIf { it > 0 } ?: 100
|
||||
val pct = if (level >= 0) level * 100 / scale else (bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: 50)
|
||||
val voltageUv = ((sticky?.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) ?: 0).toLong() * 1000L).takeIf { it > 0 } ?: 3_800_000L
|
||||
val tempDeci = sticky?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) ?: 0
|
||||
val tech = sticky?.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY)?.takeIf { it.isNotBlank() } ?: "Li-ion"
|
||||
val chargeNowUah = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER)?.takeIf { it > 0 && it != Long.MIN_VALUE } ?: 0L
|
||||
val currentNowUa = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)?.takeIf { it != Long.MIN_VALUE } ?: 0L
|
||||
val currentAvgUa = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE)?.takeIf { it != Long.MIN_VALUE && it != 0L } ?: currentNowUa
|
||||
// Android's sign convention varies by vendor; the status says which way the current flows.
|
||||
val discharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING
|
||||
val chargeFullUah = if (chargeNowUah > 0 && pct > 0) chargeNowUah * 100 / pct else 0L
|
||||
val energyNowUwh = chargeNowUah * voltageUv / 1_000_000L
|
||||
val energyFullUwh = chargeFullUah * voltageUv / 1_000_000L
|
||||
val powerNowUw = abs(currentNowUa) * voltageUv / 1_000_000L
|
||||
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
|
||||
val statusText = when (status) {
|
||||
BatteryManager.BATTERY_STATUS_CHARGING -> "Charging"
|
||||
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
|
||||
BatteryManager.BATTERY_STATUS_FULL -> "Full"
|
||||
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging"
|
||||
else -> "Unknown"
|
||||
}
|
||||
val capacityLevel = when {
|
||||
status == BatteryManager.BATTERY_STATUS_FULL || pct >= 100 -> "Full"
|
||||
pct <= 5 -> "Critical"
|
||||
pct <= 15 -> "Low"
|
||||
else -> "Normal"
|
||||
}
|
||||
for (name in listOf("BAT0", "BAT1")) {
|
||||
val bat = File(dir, name).apply { mkdirs() }
|
||||
val attrs = linkedMapOf(
|
||||
"type" to "Battery",
|
||||
"present" to "1",
|
||||
"status" to statusText,
|
||||
"capacity" to pct.toString(),
|
||||
"capacity_level" to capacityLevel,
|
||||
"technology" to tech,
|
||||
"voltage_now" to voltageUv.toString(),
|
||||
"voltage_min_design" to voltageUv.toString(),
|
||||
"current_now" to currentNowUa.toString(),
|
||||
"current_avg" to currentAvgUa.toString(),
|
||||
"charge_now" to chargeNowUah.toString(),
|
||||
"charge_full" to chargeFullUah.toString(),
|
||||
"charge_full_design" to chargeFullUah.toString(),
|
||||
"energy_now" to energyNowUwh.toString(),
|
||||
"energy_full" to energyFullUwh.toString(),
|
||||
"energy_full_design" to energyFullUwh.toString(),
|
||||
"power_now" to powerNowUw.toString(),
|
||||
"time_to_empty_now" to timeToEmptyS.toString(),
|
||||
"time_to_empty_avg" to timeToEmptyS.toString(),
|
||||
"time_to_full_now" to timeToFullS.toString(),
|
||||
"time_to_full_avg" to timeToFullS.toString(),
|
||||
"temp" to tempDeci.toString(),
|
||||
"model_name" to android.os.Build.MODEL.replace(' ', '_'),
|
||||
"manufacturer" to android.os.Build.MANUFACTURER.replace(' ', '_'),
|
||||
"scope" to "System",
|
||||
)
|
||||
for ((k, v) in attrs) put(File(bat, k), v + "\n")
|
||||
val uevent = StringBuilder("POWER_SUPPLY_NAME=$name\n")
|
||||
for ((k, v) in attrs) uevent.append("POWER_SUPPLY_").append(k.uppercase()).append('=').append(v).append('\n')
|
||||
put(File(bat, "uevent"), uevent.toString())
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "battery: could not write", t)
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomic per file: a reader in the guest never sees a half-written value. */
|
||||
private fun put(target: File, text: String) {
|
||||
val tmp = File(target.parentFile, "." + target.name + ".tmp")
|
||||
tmp.writeText(text)
|
||||
if (!tmp.renameTo(target)) { target.writeText(text); tmp.delete() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val PERIOD_MS = 5_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.io.PrintWriter
|
||||
import java.io.StringWriter
|
||||
|
||||
/**
|
||||
* The last thing that runs when our own code throws on any thread: the stack trace into the
|
||||
* session's folder, then the folder's ending ([SessionArtifacts.collect]), then Android's own
|
||||
* handler so the crash is still reported and still lands in the crash buffer. Bounded, because
|
||||
* a handler that hangs turns a crash into a frozen app: the collect gets a few seconds and the
|
||||
* process dies regardless.
|
||||
*
|
||||
* A native crash (the compositor, a JNI call) never reaches here - the process is gone before
|
||||
* Java sees anything. [SessionArtifacts.finishAbandoned] at the next start covers that case.
|
||||
*/
|
||||
object CrashHandler {
|
||||
private const val TAG = "CrashHandler"
|
||||
|
||||
fun install(context: Context) {
|
||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
try {
|
||||
Log.e(TAG, "uncaught on ${thread.name}", error)
|
||||
val dir = SessionPaths.current()
|
||||
if (dir != null && dir.isDirectory) {
|
||||
val trace = StringWriter().also { error.printStackTrace(PrintWriter(it)) }.toString()
|
||||
File(dir, "crash-app.txt").writeText(
|
||||
"The app itself crashed on thread \"${thread.name}\":\n\n$trace"
|
||||
)
|
||||
val worker = Thread({ SessionArtifacts.collect(context, dir, "app crash") }, "crash-collect")
|
||||
worker.start()
|
||||
worker.join(8000)
|
||||
}
|
||||
// The session's tree would outlive us otherwise, and block the next launch.
|
||||
OrphanReaper.reap("app crash")
|
||||
} catch (e: Throwable) {
|
||||
// Nothing more to do for a crash inside the crash handler.
|
||||
} finally {
|
||||
previous?.uncaughtException(thread, error) ?: Runtime.getRuntime().halt(2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Where a second Steam library can live on this device.
|
||||
*
|
||||
* An SD card is offered through the app's own folder on it ({@code Android/data/<pkg>/files/steam}):
|
||||
* the one place on a card a targetSdk-28 app may write without a permission prompt, and a real
|
||||
* filesystem path the session can bind. Any other folder comes from the File Manager's pick mode
|
||||
* and is checked for writing before it is accepted. Both are FUSE-backed on Android and stream
|
||||
* slowly (intro movies, big asset loads); internal stays the default and the dialog says so.
|
||||
*/
|
||||
object GameStorage {
|
||||
class Option(val label: String, val path: String)
|
||||
|
||||
/** Every removable volume, as its app folder, with the free space it has. */
|
||||
fun options(context: Context): List<Option> {
|
||||
val sm = context.getSystemService(StorageManager::class.java)
|
||||
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
|
||||
val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
|
||||
if (!removable) return@mapNotNull null
|
||||
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
|
||||
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: "SD card"
|
||||
Option("$name · ${free(dir)} free", File(dir, "steam").absolutePath)
|
||||
}
|
||||
}
|
||||
|
||||
fun free(dir: File): String = try {
|
||||
FileUtils.sizeToString(StatFs(dir.path).availableBytes)
|
||||
} catch (e: Exception) {
|
||||
"?"
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes [path] a library root the session can bind - the folder and its steamapps/ - and proves
|
||||
* it writable. Returns why it cannot be used, or null when it can.
|
||||
*/
|
||||
fun prepare(path: String): String? {
|
||||
val root = File(path)
|
||||
val steamapps = File(root, "steamapps")
|
||||
if (!steamapps.isDirectory && !steamapps.mkdirs()) return "cannot create folders in $path"
|
||||
val probe = File(steamapps, ".writable")
|
||||
return try {
|
||||
if (!probe.createNewFile() && !probe.isFile) "cannot write in $path" else { probe.delete(); null }
|
||||
} catch (e: Exception) {
|
||||
"cannot write in $path (${e.message})"
|
||||
}
|
||||
}
|
||||
|
||||
/** The root the session binds, from the setting: automatic = the first card in the phone. */
|
||||
fun effective(context: Context): Option? {
|
||||
val pref = SessionPrefs.gameStorage(context)
|
||||
return when {
|
||||
pref == SessionPrefs.GAME_STORAGE_OFF -> null
|
||||
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.label.substringBefore(" ·"), it.path) }
|
||||
else -> Option(SessionPrefs.gameStorageLabel(context), pref)
|
||||
}
|
||||
}
|
||||
|
||||
/** The label the client shows for a chosen folder: its last name, or the volume's. */
|
||||
fun labelFor(context: Context, path: String): String =
|
||||
options(context).firstOrNull { it.path == path }?.label?.substringBefore(" ·")
|
||||
?: File(path).name.ifEmpty { "Folder" }
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
/**
|
||||
* The loading overlay's state: what to say, read out of the session log, and a clock so a user
|
||||
* can see that time is passing even when the log is quiet. The runtime script marks its
|
||||
* milestones with "== STEP"; the client's own bootstrap does not, but it does print its download
|
||||
* progress, and lifting that out is the difference between "starting the Steam client" for three
|
||||
* minutes and a percentage that moves.
|
||||
*/
|
||||
class LoadingState(context: Context) {
|
||||
var visible by mutableStateOf(true)
|
||||
var step by mutableStateOf("Starting the session…")
|
||||
var percent by mutableIntStateOf(-1)
|
||||
var elapsed by mutableStateOf("")
|
||||
var hint by mutableStateOf("")
|
||||
var ended by mutableStateOf(false)
|
||||
|
||||
private val hints = context.resources.getStringArray(com.droiddeck.launcher.R.array.loading_hints)
|
||||
private val startedAt = SystemClock.elapsedRealtime()
|
||||
|
||||
/** Once a second: the clock and the hint. */
|
||||
fun tick() {
|
||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||
elapsed = String.format(java.util.Locale.US, "%d:%02d elapsed · still working", seconds / 60, seconds % 60)
|
||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||
}
|
||||
|
||||
fun showEnded(message: String) {
|
||||
visible = true
|
||||
ended = true
|
||||
step = message
|
||||
}
|
||||
|
||||
/** Re-reads the end of the log and updates the line and the bar. */
|
||||
fun update(context: Context, log: File?) {
|
||||
val state = read(context, log) ?: return
|
||||
step = state.first
|
||||
percent = state.second
|
||||
}
|
||||
|
||||
/** Only the tail is read: the client alone writes megabytes an hour. */
|
||||
private fun read(context: Context, log: File?): Pair<String, Int>? {
|
||||
if (log == null || !log.isFile) return null
|
||||
val text = try {
|
||||
RandomAccessFile(log, "r").use { file ->
|
||||
val length = file.length()
|
||||
val want = minOf(length, TAIL_BYTES)
|
||||
file.seek(length - want)
|
||||
val bytes = ByteArray(want.toInt())
|
||||
file.readFully(bytes)
|
||||
String(bytes, StandardCharsets.UTF_8)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
return null
|
||||
}
|
||||
var stepAt = -1
|
||||
var stepText: String? = null
|
||||
var downloadAt = -1
|
||||
var downloadPercent = -1
|
||||
var clientDownloadAt = -1
|
||||
var clientDownload: String? = null
|
||||
var clientPercent = -1
|
||||
var offset = 0
|
||||
for (line in text.split('\n')) {
|
||||
val at = offset
|
||||
offset += line.length + 1
|
||||
if (line.startsWith("== STEP ")) {
|
||||
stepAt = at
|
||||
stepText = line.substringAfter("== STEP ").substringAfter(' ')
|
||||
val m = INSTALL_COUNT.find(line)
|
||||
if (m != null) {
|
||||
clientDownloadAt = at
|
||||
clientDownload = m.groupValues[1]
|
||||
clientPercent = m.groupValues[2].toInt() * 100 / maxOf(1, m.groupValues[3].toInt())
|
||||
}
|
||||
} else {
|
||||
val m = UPDATE_PROGRESS.find(line)
|
||||
if (m != null) {
|
||||
downloadAt = at
|
||||
val done = m.groupValues[1].toLong()
|
||||
val total = maxOf(1L, m.groupValues[2].toLong())
|
||||
downloadPercent = (done * 100 / total).toInt()
|
||||
}
|
||||
}
|
||||
}
|
||||
return when {
|
||||
downloadAt > stepAt && downloadPercent >= 0 ->
|
||||
Pair("Downloading the Steam client update · $downloadPercent%", downloadPercent)
|
||||
clientDownloadAt == stepAt && clientDownload != null ->
|
||||
Pair("Downloading the Steam client · $clientDownload", clientPercent)
|
||||
stepText != null -> Pair(stepText, -1)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAIL_BYTES = 48L * 1024
|
||||
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
|
||||
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Starting the Steam client signed out of Valve's servers.
|
||||
*
|
||||
* The client can run without a connection - installed games launch, Proton and the frame-gen are
|
||||
* all local - but only if it has credentials from an earlier successful sign-in. Two keys in
|
||||
* loginusers.vdf decide what it does when it cannot reach a CM: WantsOfflineMode makes it go
|
||||
* offline on its own, SkipOfflineModeWarning stops it asking first. Both are read once, while the
|
||||
* client starts, which is why this belongs to the main screen and not to the in-session drawer:
|
||||
* changing it during a session would write the file and change nothing until the next launch.
|
||||
*
|
||||
* The client rewrites this file when it exits, so the request is kept as our own preference and
|
||||
* written into the file again at every session start.
|
||||
*/
|
||||
object OfflineMode {
|
||||
private const val TAG = "OfflineMode"
|
||||
private const val KEY = "steam_offline"
|
||||
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
||||
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
||||
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
||||
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
|
||||
|
||||
/** Whether the client has an account it could sign in as offline. */
|
||||
fun account(context: Context): String? {
|
||||
val file = loginUsers(LinuxRuntime.rootDir(context))
|
||||
val text = try {
|
||||
if (file.isFile) file.readText() else return null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
||||
}
|
||||
if (!REMEMBER.containsMatchIn(text)) return null
|
||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() } ?: "signed in"
|
||||
}
|
||||
|
||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
||||
|
||||
fun setEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
apply(context, LinuxRuntime.rootDir(context))
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the request into loginusers.vdf. Every account block gets the same answer: the client
|
||||
* signs in as one of them and we have no say in which. Keys the file does not carry are added
|
||||
* beside the account's name; a file without an account block is left alone, since there is
|
||||
* nothing to be offline as.
|
||||
*/
|
||||
fun apply(context: Context, root: File) {
|
||||
val file = loginUsers(root)
|
||||
if (!file.isFile) return
|
||||
val want = if (enabled(context)) "1" else "0"
|
||||
try {
|
||||
val lines = file.readLines()
|
||||
val out = ArrayList<String>(lines.size + 4)
|
||||
var sawWants = false
|
||||
var sawSkip = false
|
||||
var changed = false
|
||||
for (line in lines) {
|
||||
val wants = WANTS.matchEntire(line)
|
||||
val skip = SKIP.matchEntire(line)
|
||||
when {
|
||||
wants != null -> {
|
||||
sawWants = true
|
||||
if (wants.groupValues[2] != want) changed = true
|
||||
out.add(wants.groupValues[1] + want + wants.groupValues[3])
|
||||
}
|
||||
skip != null -> {
|
||||
sawSkip = true
|
||||
if (skip.groupValues[2] != want) changed = true
|
||||
out.add(skip.groupValues[1] + want + skip.groupValues[3])
|
||||
}
|
||||
else -> {
|
||||
out.add(line)
|
||||
if (line.contains("\"AccountName\"")) {
|
||||
val indent = line.takeWhile { it == ' ' || it == '\t' }
|
||||
if (!lines.any { WANTS.matchEntire(it) != null }) {
|
||||
out.add("$indent\"WantsOfflineMode\"\t\t\"$want\""); changed = true
|
||||
}
|
||||
if (!lines.any { SKIP.matchEntire(it) != null }) {
|
||||
out.add("$indent\"SkipOfflineModeWarning\"\t\t\"$want\""); changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!changed) return
|
||||
val staged = File(file.parentFile, "loginusers.vdf.staged")
|
||||
staged.writeText(out.joinToString("\n", postfix = "\n"))
|
||||
if (!staged.renameTo(file)) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not replace loginusers.vdf")
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "offline=$want (wants=$sawWants skip=$sawSkip)")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not write loginusers.vdf", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Kills every process of this app's uid other than the app itself.
|
||||
*
|
||||
* A session is a tree of processes under proot, and proot dies with the app only when the app's
|
||||
* own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the
|
||||
* rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never
|
||||
* comes up, or comes up beside a client that is already running. A user on a Thor Pro had to
|
||||
* force-stop the app before every launch. Everything of ours that should be alive between
|
||||
* sessions is inside the app process, so at session start anything else under our uid is a
|
||||
* leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name.
|
||||
*/
|
||||
object OrphanReaper {
|
||||
private const val TAG = "OrphanReaper"
|
||||
|
||||
fun reap(reason: String): Int {
|
||||
val me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
var killed = 0
|
||||
File("/proc").listFiles()?.forEach { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@forEach
|
||||
if (pid == me || pid <= 1) return@forEach
|
||||
if (uidOf(pid) != uid) return@forEach
|
||||
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
|
||||
try {
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
Log.i(TAG, "killed leftover $pid ($name) - $reason")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not kill $pid ($name)", e)
|
||||
}
|
||||
}
|
||||
if (killed > 0) Log.i(TAG, "$killed leftover process(es) from an earlier session - $reason")
|
||||
return killed
|
||||
}
|
||||
|
||||
private fun uidOf(pid: Int): Int {
|
||||
return try {
|
||||
File("/proc/$pid/status").useLines { lines ->
|
||||
lines.firstOrNull { it.startsWith("Uid:") }
|
||||
?.substringAfter("Uid:")?.trim()?.split(Regex("\\s+"))?.firstOrNull()?.toIntOrNull() ?: -1
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
-1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PerformanceHintManager
|
||||
import android.util.Log
|
||||
import androidx.annotation.RequiresApi
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/**
|
||||
* ADPF (Android 12+): a PerformanceHintManager session over the compositor thread, told the
|
||||
* panel's frame period as its target and each presented frame's interval as the actual. When a
|
||||
* frame runs long the power HAL raises CPU clocks for the next one at once, instead of the
|
||||
* governor waiting for the load average to climb - the difference between a menu that stutters
|
||||
* on the first scroll and one that does not.
|
||||
*
|
||||
* The session may only carry this process's threads, so the guest (gamescope, the Steam client
|
||||
* under FEX) cannot join it; they are covered by the app-wide game category and sustained mode.
|
||||
* Below API 31 nothing here runs; on a power HAL without hint sessions createHintSession returns
|
||||
* null and the log says so.
|
||||
*/
|
||||
object PerfHints {
|
||||
private const val TAG = "PerfHints"
|
||||
|
||||
@Volatile private var session: PerformanceHintManager.Session? = null
|
||||
@Volatile private var target = 0L
|
||||
/** Compositor thread only. */
|
||||
private var last = 0L
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
/** Reports leave the compositor thread: each one is a binder call to the power HAL. */
|
||||
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "adpf-report").apply { isDaemon = true } }
|
||||
|
||||
/** Opens the session once the compositor thread exists (it is started just before this). */
|
||||
fun arm(context: Context, refreshHz: Float) {
|
||||
if (Build.VERSION.SDK_INT < 31) { Log.i(TAG, "adpf: needs Android 12; this is API ${Build.VERSION.SDK_INT}"); return }
|
||||
val wanted = (1_000_000_000.0 / refreshHz.coerceAtLeast(30f)).toLong()
|
||||
val s = session
|
||||
if (s != null) {
|
||||
if (wanted != target) { target = wanted; try { s.updateTargetWorkDuration(wanted) } catch (t: Throwable) { Log.w(TAG, "adpf: retarget", t) } }
|
||||
return
|
||||
}
|
||||
target = wanted
|
||||
val app = context.applicationContext
|
||||
var tries = 0
|
||||
main.post(object : Runnable {
|
||||
override fun run() {
|
||||
if (session != null) return
|
||||
val tid = try { WaylandCompositor.nativeCompositorTid() } catch (t: Throwable) { 0 }
|
||||
if (tid == 0) {
|
||||
if (++tries < 30) main.postDelayed(this, 100) else Log.w(TAG, "adpf: the compositor thread never reported its tid")
|
||||
return
|
||||
}
|
||||
open(app, tid)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@RequiresApi(31)
|
||||
private fun open(app: Context, tid: Int) {
|
||||
val pm = app.getSystemService(PerformanceHintManager::class.java)
|
||||
if (pm == null) { Log.i(TAG, "adpf: no PerformanceHintManager on this device"); return }
|
||||
val s = try { pm.createHintSession(intArrayOf(tid), target) } catch (t: Throwable) { Log.w(TAG, "adpf: createHintSession", t); null }
|
||||
if (s == null) { Log.i(TAG, "adpf: unsupported here (the power HAL has no hint sessions)"); return }
|
||||
last = 0L
|
||||
session = s
|
||||
Log.i(TAG, "adpf: session on compositor thread $tid · target ${target / 1000} µs · HAL wants updates every ${pm.preferredUpdateRateNanos / 1000} µs")
|
||||
}
|
||||
|
||||
/** Compositor thread, once per presented game frame; the interval since the last is the actual. */
|
||||
@JvmStatic
|
||||
fun onFrame() {
|
||||
val s = session ?: return
|
||||
val now = System.nanoTime()
|
||||
val prev = last
|
||||
last = now
|
||||
if (prev == 0L) return
|
||||
val dt = now - prev
|
||||
// Under half a millisecond is a double present; over half a second is a pause, not a frame.
|
||||
if (dt < 500_000L || dt > 500_000_000L) return
|
||||
worker.execute {
|
||||
try { s.reportActualWorkDuration(dt) } catch (t: Throwable) { Log.w(TAG, "adpf: report failed, session dropped", t); session = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* The numbers behind the top-right line: the game's own frame rate and, when frame generation
|
||||
* is on, what the screen is actually being shown - "60 → 118 fps" is the proof that the engine
|
||||
* is doing something, and "FG starting" or a reason is the proof that it is not.
|
||||
*
|
||||
* The base rate is counted here from the compositor's per-frame callback, so it is right with or
|
||||
* without an engine. The presented rate comes from the engine's own telemetry while it generates.
|
||||
*/
|
||||
class PerfHud(context: Context) {
|
||||
/** Empty when the HUD is off or not yet started. */
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
|
||||
private val context = context.applicationContext
|
||||
private val frames = AtomicInteger()
|
||||
private var lastTick = 0L
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
/** The session's own switch (drawer), with the Downloads file as a device-side override. */
|
||||
private val enabled: Boolean
|
||||
get() = SessionPrefs.hudEnabled(context)
|
||||
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
/** Told, on the main thread, when the window presenting frames changes. */
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
private var lastWindow: String? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
// gamescope forwards a fullscreen game's own buffers straight through and its composited
|
||||
// output when the Steam menu is up; each is a different window here. Compositor thread.
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
}
|
||||
}
|
||||
override fun onGameFrame() { frames.incrementAndGet() }
|
||||
}
|
||||
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
|
||||
lastTick = now
|
||||
text = line(frames.getAndSet(0) / dt)
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads the switch: starts or stops to match it. */
|
||||
fun refresh() {
|
||||
if (enabled) start() else stop()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (!enabled || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
frames.set(0)
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.post(tick)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
WaylandCompositor.setGameListener(null)
|
||||
text = ""
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
val engine = FrameGen.engine(context)
|
||||
if (engine == FrameGen.ENGINE_OFF) return fps(base)
|
||||
val name = if (engine == FrameGen.ENGINE_LSFG) "LSFG" else "Win-FG"
|
||||
val multiplier = FrameGen.multiplier(context)
|
||||
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
|
||||
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
|
||||
return when {
|
||||
problem == 1 -> "$name: unsupported"
|
||||
problem == 2 -> "$name: engine failed"
|
||||
stats != null && stats[3] > 1f -> {
|
||||
val source = if (stats[2] > 1f) stats[2] else base
|
||||
String.format(Locale.US, "%s %d× %.0f → %.0f fps", name, multiplier, source, stats[3])
|
||||
}
|
||||
else -> String.format(Locale.US, "%s %d× %s · FG starting", name, multiplier, fps(base))
|
||||
}
|
||||
}
|
||||
|
||||
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.GameManager
|
||||
import android.app.GameState
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* What a session tells Android about itself so the SoC is run for a game, not for an app.
|
||||
*
|
||||
* The manifest already makes the app a game (appCategory + game_mode_config); this is the
|
||||
* per-window half, applied when the session activity is created:
|
||||
*
|
||||
* - sustained performance mode (Android 7+): a clock floor that does not throttle away after
|
||||
* two minutes, which suits an hour in Big Picture better than a boost that fades;
|
||||
* - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to
|
||||
* 120 Hz for the menu, not only when a game votes for it;
|
||||
* - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases
|
||||
* its boost on loading screens or menus keeps it up.
|
||||
*
|
||||
* Every step is version-guarded and skipped silently below its API; the returned line is what
|
||||
* the session log shows, which is the first thing to read on a device that feels slow.
|
||||
*/
|
||||
object PerfMode {
|
||||
private const val TAG = "PerfMode"
|
||||
|
||||
fun apply(a: Activity): String {
|
||||
val parts = ArrayList<String>(3)
|
||||
|
||||
// Sustained performance mode.
|
||||
parts += if (Build.VERSION.SDK_INT >= 24) {
|
||||
val pm = a.getSystemService(PowerManager::class.java)
|
||||
if (pm?.isSustainedPerformanceModeSupported == true) {
|
||||
try { a.window.setSustainedPerformanceMode(true); "sustained mode on" } catch (t: Throwable) { Log.w(TAG, "sustained mode", t); "sustained mode refused" }
|
||||
} else "sustained mode unsupported"
|
||||
} else "sustained mode needs Android 7"
|
||||
|
||||
// The fastest display mode at the panel's current size.
|
||||
parts += try {
|
||||
val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay
|
||||
if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else {
|
||||
val cur = display.mode
|
||||
val best = display.supportedModes
|
||||
.filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight }
|
||||
.maxByOrNull { it.refreshRate }
|
||||
if (best != null && best.modeId != cur.modeId && best.refreshRate > cur.refreshRate + 0.5f) {
|
||||
a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId }
|
||||
"display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})"
|
||||
} else "display ${cur.refreshRate.toInt()} Hz"
|
||||
}
|
||||
} catch (t: Throwable) { Log.w(TAG, "display mode", t); "display mode failed" }
|
||||
|
||||
// GameManager: what mode the OS put us in, and that we are playing.
|
||||
parts += if (Build.VERSION.SDK_INT >= 31) {
|
||||
val gm = a.getSystemService(GameManager::class.java)
|
||||
if (gm == null) "no GameManager" else {
|
||||
val mode = when (gm.gameMode) {
|
||||
GameManager.GAME_MODE_PERFORMANCE -> "performance"
|
||||
GameManager.GAME_MODE_BATTERY -> "battery"
|
||||
GameManager.GAME_MODE_STANDARD -> "standard"
|
||||
else -> "unsupported"
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
try { gm.setGameState(GameState(false, GameState.MODE_GAMEPLAY_INTERRUPTIBLE)) } catch (t: Throwable) { Log.w(TAG, "game state", t) }
|
||||
}
|
||||
"game mode $mode"
|
||||
}
|
||||
} else "game mode needs Android 12"
|
||||
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.StatFs
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import org.json.JSONArray
|
||||
|
||||
/** Immediate download and installation of the optional ARM64 Proton builds. */
|
||||
object ProtonExtras {
|
||||
private const val TAG = "ProtonExtras"
|
||||
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
|
||||
@Volatile
|
||||
var installInProgress = false
|
||||
private set
|
||||
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
|
||||
private data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long)
|
||||
|
||||
val tools = listOf(
|
||||
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
|
||||
)
|
||||
|
||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
private fun requests(context: Context) = File(home(context), ".bl-proton-extra")
|
||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||
|
||||
/** The installed build's directory name (e.g. GE-Proton11-7), or null. */
|
||||
fun installed(context: Context, tool: Tool): String? =
|
||||
toolsDir(context).listFiles()
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && File(it, "toolmanifest.vdf").isFile }
|
||||
?.maxByOrNull { it.name }?.name
|
||||
|
||||
/** A request left by an earlier app version, still consumed by the session shim. */
|
||||
fun queued(context: Context, tool: Tool): Boolean =
|
||||
requestLines(context).any { it.trim() == tool.id || it.trim().startsWith(tool.id + " ") }
|
||||
|
||||
fun unqueue(context: Context, tool: Tool) {
|
||||
val lines = requestLines(context).filterNot { it.trim() == tool.id || it.trim().startsWith(tool.id + " ") }
|
||||
val file = requests(context)
|
||||
if (lines.isEmpty()) file.delete()
|
||||
else file.writeText(lines.joinToString("\n") + "\n")
|
||||
}
|
||||
|
||||
/** Deletes the installed build; Steam discovers its absence on its next start. */
|
||||
fun remove(context: Context, tool: Tool) {
|
||||
installed(context, tool)?.let { File(toolsDir(context), it).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** Downloads, verifies and registers the latest build without waiting for another session. */
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress) return "A compatibility tool install is already running"
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return "Stop the active session before installing compatibility tools"
|
||||
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
|
||||
|
||||
val asset = findLatestAsset(tool) ?: return "Could not find an ARM64 release for ${tool.name}"
|
||||
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
|
||||
val archive = File(downloads, "${tool.id}-${asset.name}")
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
|
||||
return "At least 4 GB free plus the download size is required to install ${tool.name}"
|
||||
}
|
||||
|
||||
onProgress("Downloading ${tool.name} ${asset.tag}", 0)
|
||||
var downloaded = false
|
||||
for (attempt in 0 until 5) {
|
||||
downloaded = Downloader.downloadFile(asset.url, archive, true) { fraction ->
|
||||
onProgress("Downloading ${tool.name} ${asset.tag}", if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||
}
|
||||
if (downloaded) break
|
||||
if (attempt < 4) {
|
||||
onProgress("Retrying download · attempt ${attempt + 2} of 5", -1)
|
||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
return "Download interrupted"
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!downloaded) return "Download failed; the partial file is kept so a retry can resume"
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
return "Download exceeded the release size and was deleted"
|
||||
}
|
||||
return "Download was incomplete; the partial file is kept for a resumable retry"
|
||||
}
|
||||
|
||||
asset.sha512?.let { checksumUrl ->
|
||||
onProgress("Verifying download", -1)
|
||||
val checksumText = Downloader.downloadString(checksumUrl)
|
||||
val expected = checksumText?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
||||
if (expected != null && !expected.equals(sha512(archive), ignoreCase = true)) {
|
||||
archive.delete()
|
||||
return "Checksum mismatch; the download was deleted"
|
||||
}
|
||||
}
|
||||
|
||||
if (SessionState.running) return "A session started during the download; stop it before installing compatibility tools"
|
||||
onProgress("Installing ${tool.name}", -1)
|
||||
return try {
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
|
||||
val runtimeDir = File(context.filesDir, ".proton-install-rt").apply { mkdirs() }
|
||||
val guest = listOf(
|
||||
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
|
||||
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share",
|
||||
"/usr/local/bin/bannerlator-proton-extra", "/root/.local/share/Steam", archive.absolutePath,
|
||||
)
|
||||
val command = LinuxRuntime.command(context, null, runtimeDir, null, guest)
|
||||
val process = ProcessBuilder(command)
|
||||
.directory(root)
|
||||
.redirectErrorStream(true)
|
||||
val hostEnv = process.environment()
|
||||
hostEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(context).path
|
||||
hostEnv["PROOT_TMP_DIR"] = context.cacheDir.path
|
||||
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { hostEnv["LD_LIBRARY_PATH"] = it }
|
||||
val child = process.start()
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
Log.i(TAG, line)
|
||||
if (line.contains("unpacking", ignoreCase = true) || line.contains("adopted", ignoreCase = true)) {
|
||||
onProgress("Installing ${tool.name}", -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
val status = child.waitFor()
|
||||
if (status != 0) "${tool.name} installation failed (exit $status)"
|
||||
else {
|
||||
archive.delete()
|
||||
unqueue(context, tool)
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "install ${tool.id}", e)
|
||||
e.message ?: "Could not install ${tool.name}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun findLatestAsset(tool: Tool): Asset? {
|
||||
val releases = Downloader.downloadString(RELEASES.format(tool.repo)) ?: return null
|
||||
return try {
|
||||
val array = JSONArray(releases)
|
||||
for (i in 0 until array.length()) {
|
||||
val release = array.getJSONObject(i)
|
||||
if (release.optBoolean("draft", false)) continue
|
||||
val assets = release.optJSONArray("assets") ?: continue
|
||||
val entries = (0 until assets.length()).map { assets.getJSONObject(it) }
|
||||
val archive = entries.sortedBy { it.optString("name") }.firstOrNull { tool.assetPattern.containsMatchIn(it.optString("name")) } ?: continue
|
||||
val name = archive.optString("name")
|
||||
val stem = name.substringBefore(".tar")
|
||||
val checksum = entries.firstOrNull {
|
||||
it.optString("name").startsWith(stem) && it.optString("name").contains("sha512", ignoreCase = true)
|
||||
}?.optString("browser_download_url")?.takeIf { it.startsWith("http") }
|
||||
return Asset(
|
||||
release.optString("tag_name"), name,
|
||||
archive.optString("browser_download_url").takeIf { it.startsWith("http") } ?: continue, checksum,
|
||||
archive.optLong("size", 0L),
|
||||
)
|
||||
}
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "release metadata for ${tool.id}", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha512(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-512")
|
||||
file.inputStream().buffered().use { input ->
|
||||
val buffer = ByteArray(4 * 1024 * 1024)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it.toInt() and 0xff) }
|
||||
}
|
||||
|
||||
private fun requestLines(context: Context): List<String> =
|
||||
FileUtils.readString(requests(context))?.lines()?.filter { it.isNotBlank() } ?: emptyList()
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
|
||||
/**
|
||||
* Other apps on the device that sign into the user's Steam account with their own client. Steam
|
||||
* allows one session per account: the moment one of them signs in, ours is signed out - which
|
||||
* shows up as "Session Replaced" in the client's log 2-3 seconds after every login, and looks
|
||||
* like a bug in this app.
|
||||
*
|
||||
* Installed is the most a normal app can know (since Android 7 `getRunningAppProcesses()` returns
|
||||
* only the caller's own), so the list is checked for presence and then asked to stop.
|
||||
* `killBackgroundProcesses` is a normal permission: it ends an app's background processes and
|
||||
* leaves anything in the foreground alone - and background is exactly the case that keeps
|
||||
* happening, because GameHub declares boot receivers and is running from the moment the phone
|
||||
* starts without ever having been opened. Telling someone to close an app they never opened is
|
||||
* not much help. Ported from Bannerlator's Linux session (GPL-3.0).
|
||||
*/
|
||||
object RivalClients {
|
||||
private const val TAG = "RivalClients"
|
||||
|
||||
private val PACKAGES = arrayOf(
|
||||
"com.xiaoji.egggame", // GameHub
|
||||
)
|
||||
|
||||
fun installed(context: Context): List<String> =
|
||||
PACKAGES.filter { pkg ->
|
||||
try { context.packageManager.getPackageInfo(pkg, 0); true } catch (e: Throwable) { false }
|
||||
}
|
||||
|
||||
fun name(pkg: String): String = if (pkg == "com.xiaoji.egggame") "GameHub" else pkg
|
||||
|
||||
/**
|
||||
* Stop the installed rivals' background processes before the client starts, and say so. A
|
||||
* rival in the foreground survives this, so the wording covers that case too. Call on the main
|
||||
* thread; the Toast is shown from here.
|
||||
*/
|
||||
fun stopBeforeSession(context: Context) {
|
||||
val rivals = installed(context)
|
||||
if (rivals.isEmpty()) return
|
||||
val who = name(rivals[0])
|
||||
Log.w(TAG, "competing Steam client installed: $rivals")
|
||||
var asked = false
|
||||
try {
|
||||
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
|
||||
if (am != null) {
|
||||
for (pkg in rivals) am.killBackgroundProcesses(pkg)
|
||||
asked = true
|
||||
Log.i(TAG, "asked Android to stop background processes of $rivals")
|
||||
}
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "could not stop competing Steam clients", t)
|
||||
}
|
||||
Toast.makeText(
|
||||
context,
|
||||
if (asked) "Closed $who in the background - it signs into your Steam account."
|
||||
else "If $who is open, close it first - it signs into your Steam account and will sign this client out.",
|
||||
Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.net.LocalServerSocket
|
||||
import android.os.Build
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.os.VibratorManager
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import java.io.DataInputStream
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Rumble for the on-screen pad, on the phone itself.
|
||||
*
|
||||
* When a game plays a force-feedback effect on the fake pad, the fake evdev layer inside the guest
|
||||
* connects to the abstract socket [NAME] and sends one packet: strong, weak, duration in ms and
|
||||
* the pad slot, four little-endian 16-bit values. This listens for those and drives the device's
|
||||
* vibrator with the stronger motor's strength for the effect's duration. Best effort both ways:
|
||||
* a missing listener costs the guest nothing, and a bad packet is dropped.
|
||||
*/
|
||||
class RumbleComponent : SessionPart() {
|
||||
@Volatile private var server: LocalServerSocket? = null
|
||||
|
||||
override fun start() {
|
||||
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
|
||||
server = s
|
||||
Thread({
|
||||
while (server === s) {
|
||||
val client = try { s.accept() } catch (e: Exception) { break }
|
||||
try {
|
||||
val bytes = ByteArray(8)
|
||||
DataInputStream(client.inputStream).readFully(bytes)
|
||||
val strong = u16(bytes, 0); val weak = u16(bytes, 2); val ms = u16(bytes, 4)
|
||||
buzz(max(strong, weak), ms)
|
||||
} catch (e: Exception) {
|
||||
// A partial packet or a closed peer: nothing to play.
|
||||
} finally {
|
||||
try { client.close() } catch (e: Exception) { /* already gone */ }
|
||||
}
|
||||
}
|
||||
}, "rumble").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "rumble: listening on @$NAME")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
val s = server ?: return
|
||||
server = null
|
||||
try { s.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
|
||||
}
|
||||
|
||||
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
|
||||
|
||||
private fun buzz(strength: Int, ms: Int) {
|
||||
val ctx = app() ?: return
|
||||
val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator ?: return
|
||||
else @Suppress("DEPRECATION") (ctx.getSystemService(Vibrator::class.java) ?: return)
|
||||
if (!vibrator.hasVibrator()) return
|
||||
if (strength == 0 || ms == 0) { vibrator.cancel(); return }
|
||||
val amplitude = (strength * 255L / 65535L).toInt().coerceIn(1, 255)
|
||||
val duration = ms.toLong().coerceIn(1L, 5000L)
|
||||
try {
|
||||
if (vibrator.hasAmplitudeControl()) vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))
|
||||
else vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "rumble: $e")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
|
||||
const val NAME = "droiddeck-rumble"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.LogRedactor
|
||||
import com.droiddeck.launcher.core.SessionLogCapture
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Finishes a session's folder: the compositor's log, the Steam client's logs scrubbed line by
|
||||
* line, Android's crash buffer, and a marker that says the folder is complete.
|
||||
*
|
||||
* Three callers, because a session ends three ways. [collect] runs at an ordinary stop. The
|
||||
* app's uncaught-exception handler ([CrashHandler]) runs it as the process dies, so a crash in
|
||||
* our own code leaves a full folder and not a half one. And [finishAbandoned] runs at the next
|
||||
* app start for a folder that has no marker: the process was killed outright (Android's phantom
|
||||
* process killer, a native crash in the compositor, the battery) and nothing of ours got to run.
|
||||
* Everything written *during* the session - session.log, app.log, wayland.log, audio.log, the
|
||||
* device report - is already on disk at that point; only the pieces gathered at the end were
|
||||
* missing, and the crash buffer keeps its entries after the process is gone, which is the whole
|
||||
* reason it is worth coming back for.
|
||||
*/
|
||||
object SessionArtifacts {
|
||||
private const val TAG = "SessionArtifacts"
|
||||
|
||||
/** Written last; a folder without it did not get its ending. */
|
||||
const val COMPLETE_MARKER = ".complete"
|
||||
|
||||
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
|
||||
fun collect(context: Context, dir: File, reason: String) {
|
||||
try {
|
||||
val wayland = File(dir, "wayland.log")
|
||||
if (!wayland.exists()) {
|
||||
WaylandCompositor.currentLogFile()?.takeIf { it.isFile }?.let { src ->
|
||||
src.copyTo(wayland, overwrite = true)
|
||||
}
|
||||
}
|
||||
copySteamLogs(context, dir)
|
||||
// A session the system killed leaves its trace here and nowhere else.
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "collecting session artifacts", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Steam's logs: redacted into steam/, never copied verbatim. */
|
||||
private fun copySteamLogs(context: Context, dir: File) {
|
||||
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
|
||||
if (!logs.isDirectory) return
|
||||
val out = File(dir, "steam").apply { mkdirs() }
|
||||
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
|
||||
try {
|
||||
File(out, src.name).bufferedWriter().use { w ->
|
||||
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not scrub ${src.name}", e)
|
||||
}
|
||||
}
|
||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||
}
|
||||
|
||||
/**
|
||||
* Every session folder without a marker gets its ending now. Only the newest of them gets the
|
||||
* Steam logs - the runtime holds one set, and it belongs to the last session that ran; an
|
||||
* older folder would be handed logs that are not its own. Runs on a worker thread at app
|
||||
* start; nothing here touches the session that is about to begin.
|
||||
*/
|
||||
fun finishAbandoned(context: Context) {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
val abandoned = parent.listFiles { f ->
|
||||
f.isDirectory && f.name.startsWith("session-") && !File(f, COMPLETE_MARKER).exists()
|
||||
}?.sortedBy { it.name } ?: return
|
||||
if (abandoned.isEmpty()) return
|
||||
val current = SessionPaths.current()
|
||||
abandoned.forEachIndexed { i, dir ->
|
||||
if (dir == current) return@forEachIndexed
|
||||
val newest = i == abandoned.lastIndex
|
||||
try {
|
||||
File(dir, "ended-without-teardown.txt").writeText(
|
||||
"This session's process ended without running its own teardown - killed by\n" +
|
||||
"Android, a native crash, or the device going down - so the files below were\n" +
|
||||
"gathered when the app next started, at ${now()}.\n" +
|
||||
"The logs written during the session (session.log, app.log, wayland.log,\n" +
|
||||
"audio.log, device.txt) were on disk already and are as they were left.\n" +
|
||||
(if (newest) "" else "Steam's logs are not included: a later session has overwritten them.\n") +
|
||||
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
|
||||
"session died of a crash, the entry is in there unless the device rebooted.\n"
|
||||
)
|
||||
if (newest) {
|
||||
copySteamLogs(context, dir)
|
||||
}
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
|
||||
Log.i(TAG, "finished the abandoned session folder $dir")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not finish $dir", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date())
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
/** Everything the session needs written into the runtime before it starts. */
|
||||
object SessionFiles {
|
||||
private const val TAG = "SessionFiles"
|
||||
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
|
||||
/** Where the DirectAudio driver lives inside the runtime; the wrappers get it as BL_DIRECTAUDIO. */
|
||||
const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio"
|
||||
|
||||
/**
|
||||
* The libraries and scripts the session runs, refreshed from the apk at every launch.
|
||||
*
|
||||
* The runtime image carries its own copies, but a runtime installed months ago carries the
|
||||
* copies of that day and a device has no way to replace them from outside the app. Staging
|
||||
* them here is how a fix inside the session shim, the controller reader or one of the scripts
|
||||
* reaches an already-installed runtime without a ~790 MB re-download. Each lands through a
|
||||
* rename, so a session that still has one mapped keeps the file it opened.
|
||||
*/
|
||||
fun stage(context: Context, root: File) {
|
||||
val files = arrayOf(
|
||||
"libblsession.so" to "usr/local/lib/libblsession.so",
|
||||
"libfakeinput.so" to "usr/local/lib/libfakeinput.so",
|
||||
"usr/local/bin/bannerlator-session" to "usr/local/bin/bannerlator-session",
|
||||
"usr/local/bin/bannerlator-steam-compat" to "usr/local/bin/bannerlator-steam-compat",
|
||||
"usr/local/bin/bannerlator-steam-install" to "usr/local/bin/bannerlator-steam-install",
|
||||
"usr/local/bin/bannerlator-steam-library" to "usr/local/bin/bannerlator-steam-library",
|
||||
"usr/local/bin/bannerlator-seed-redists" to "usr/local/bin/bannerlator-seed-redists",
|
||||
"usr/local/bin/bannerlator-proton-extra" to "usr/local/bin/bannerlator-proton-extra",
|
||||
"usr/local/bin/bannerlator-netmanager" to "usr/local/bin/bannerlator-netmanager",
|
||||
"usr/local/bin/bannerlator-steam-launch" to "usr/local/bin/bannerlator-steam-launch",
|
||||
"usr/local/bin/bannerlator-desktop-games" to "usr/local/bin/bannerlator-desktop-games",
|
||||
"usr/local/bin/bannerlator-steam-shim" to "usr/local/bin/bannerlator-steam-shim",
|
||||
"usr/local/bin/bannerlator-steam-shortcuts" to "usr/local/bin/bannerlator-steam-shortcuts",
|
||||
// The SteamOS helpers the client calls in Deck mode: the two Armada found it needs, plus
|
||||
// the three under /usr/bin, all no-ops that answer "nothing to do" (see each file).
|
||||
"usr/bin/steamos-update" to "usr/bin/steamos-update",
|
||||
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
|
||||
"usr/bin/jupiter-biosupdate" to "usr/bin/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-priv-write" to "usr/bin/steamos-polkit-helpers/steamos-priv-write",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-set-timezone" to "usr/bin/steamos-polkit-helpers/steamos-set-timezone",
|
||||
// On device the client called these four by their polkit-helpers path, not /usr/bin: the
|
||||
// "Update Error" dialog was steamos-update missing there.
|
||||
"usr/bin/steamos-polkit-helpers/steamos-update" to "usr/bin/steamos-polkit-helpers/steamos-update",
|
||||
"usr/bin/steamos-polkit-helpers/steamos-select-branch" to "usr/bin/steamos-polkit-helpers/steamos-select-branch",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-biosupdate" to "usr/bin/steamos-polkit-helpers/jupiter-biosupdate",
|
||||
"usr/bin/steamos-polkit-helpers/jupiter-dock-updater" to "usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
|
||||
)
|
||||
// The desktop's launcher and labwc defaults, only where the desktop package is installed:
|
||||
// staging them into a runtime without it would make the desktop look present when it is not.
|
||||
val desktop = arrayOf(
|
||||
"usr/local/bin/droiddeck-desktop" to "usr/local/bin/droiddeck-desktop",
|
||||
"etc/xdg/labwc/autostart" to "etc/xdg/labwc/autostart",
|
||||
"etc/xdg/labwc/rc.xml" to "etc/xdg/labwc/rc.xml",
|
||||
"etc/xdg/lxqt/panel.conf" to "etc/xdg/lxqt/panel.conf",
|
||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||
)
|
||||
// The patched gamescope (tools/gamescope): the runtime's own version rebuilt with the ARM64
|
||||
// client fixes, over /usr/local/bin so it comes first in the session's PATH. Only when the
|
||||
// apk carries it - a build without the asset leaves the runtime's copy alone.
|
||||
// Valve's mangoapp (tools/mangoapp) - Deck mode's performance overlay - with the five
|
||||
// libraries the runtime lacks beside it, and the wrapper on PATH that points it at them.
|
||||
val mangoapp = listOf(
|
||||
"usr/local/bin/mangoapp",
|
||||
"usr/local/lib/mangoapp/mangoapp",
|
||||
"usr/local/lib/mangoapp/libfmt.so.10",
|
||||
"usr/local/lib/mangoapp/libspdlog.so.1.13",
|
||||
"usr/local/lib/mangoapp/libglfw.so.3",
|
||||
"usr/local/lib/mangoapp/libtraceevent.so.1",
|
||||
"usr/local/lib/mangoapp/libtracefs.so.1",
|
||||
).map { it to it }
|
||||
val optional = (arrayOf(
|
||||
"usr/local/bin/gamescope" to "usr/local/bin/gamescope",
|
||||
) + mangoapp).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
}
|
||||
val all = (if (File(root, "usr/bin/labwc").isFile) files + desktop else files) + optional
|
||||
for ((asset, relative) in all) {
|
||||
val target = File(root, relative)
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("linuxfs/$asset").use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setExecutable(true, false) && staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage $relative", e)
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (!installed) Log.e(TAG, "$relative NOT staged")
|
||||
}
|
||||
// The DirectAudio driver for games under Proton: the glibc build of winedirectaudio, which
|
||||
// the Proton wrappers add to WINEDLLPATH when the session asks for it (BL_DIRECTAUDIO).
|
||||
// Staged like the scripts, so a driver fix reaches an installed runtime without re-hosting.
|
||||
val directAudio = arrayOf(
|
||||
"aarch64-unix/winedirectaudio.so",
|
||||
"aarch64-windows/winedirectaudio.drv",
|
||||
"i386-windows/winedirectaudio.drv",
|
||||
)
|
||||
for (relative in directAudio) {
|
||||
val target = File(root, "$DIRECTAUDIO_DIR/lib/wine/$relative")
|
||||
val staged = File(target.parentFile, target.name + ".staged")
|
||||
var installed = false
|
||||
try {
|
||||
target.parentFile?.mkdirs()
|
||||
context.assets.open("directaudio/linux-wine11/$relative").use { input ->
|
||||
staged.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
installed = staged.setReadable(true, false) && staged.renameTo(target)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage DirectAudio $relative", e)
|
||||
} finally {
|
||||
if (!installed) staged.delete()
|
||||
}
|
||||
if (!installed) Log.e(TAG, "DirectAudio $relative NOT staged")
|
||||
}
|
||||
// What every process in the session preloads. LD_PRELOAD in the environment would not
|
||||
// survive: the Steam client rebuilds it for each process it starts and appends its own
|
||||
// overlay entry without a separator, which silently drops whatever was there.
|
||||
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
|
||||
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
|
||||
preload.append("/usr/local/lib/libfakeinput.so\n")
|
||||
}
|
||||
val etc = File(root, "etc").apply { mkdirs() }
|
||||
val staged = File(etc, "ld.so.preload.staged")
|
||||
if (!FileUtils.writeString(staged, preload.toString())
|
||||
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write ld.so.preload")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
|
||||
* folder rather than dug out of app-private storage - but the session script redirects its own
|
||||
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
|
||||
* shell. So a public directory is used only once it is proven writable; otherwise the app's
|
||||
* own files directory, which is bound into the session anyway, stands in.
|
||||
*/
|
||||
fun logDirectory(context: Context): File {
|
||||
val public = LinuxRuntime.debugLogDir()
|
||||
if (public.isDirectory || public.mkdirs()) {
|
||||
val probe = File(public, ".writable")
|
||||
try {
|
||||
if (probe.createNewFile() || probe.isFile) {
|
||||
probe.delete()
|
||||
return public
|
||||
}
|
||||
} catch (ignored: Exception) {
|
||||
}
|
||||
}
|
||||
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
|
||||
return File(context.filesDir, "logs").apply { mkdirs() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
/**
|
||||
* Zips the most recent session's log folder and hands it to Android's share sheet. Works where
|
||||
* the folder could not be written to Downloads (no storage permission, or a device that refuses
|
||||
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
|
||||
*/
|
||||
object SessionLogShare {
|
||||
/** The newest session folder in either place logs are written, or null if there is none. */
|
||||
fun latest(context: Context): File? =
|
||||
listOf(LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
|
||||
.flatMap { dir -> dir.listFiles { f -> f.isDirectory && f.name.startsWith("session-") }?.toList() ?: emptyList() }
|
||||
.maxByOrNull { it.name }
|
||||
|
||||
/** Builds the zip (blocking). Returns null when there is no session to share. */
|
||||
fun zipLatest(context: Context): File? {
|
||||
val folder = latest(context) ?: return null
|
||||
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
|
||||
val zip = File(out, "DroidDeck-${folder.name}.zip")
|
||||
ZipOutputStream(zip.outputStream().buffered()).use { z ->
|
||||
folder.walkTopDown().filter { it.isFile }.forEach { f ->
|
||||
z.putNextEntry(ZipEntry(folder.name + "/" + f.relativeTo(folder).path))
|
||||
f.inputStream().use { it.copyTo(z) }
|
||||
z.closeEntry()
|
||||
}
|
||||
}
|
||||
return zip
|
||||
}
|
||||
|
||||
fun shareIntent(context: Context, zip: File): Intent {
|
||||
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
|
||||
val send = Intent(Intent.ACTION_SEND)
|
||||
.setType("application/zip")
|
||||
.putExtra(Intent.EXTRA_STREAM, uri)
|
||||
.putExtra(Intent.EXTRA_SUBJECT, zip.nameWithoutExtension)
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
send.clipData = ClipData.newRawUri(zip.name, uri)
|
||||
return Intent.createChooser(send, "Share session logs").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded:
|
||||
*
|
||||
* ```
|
||||
* Download/DroidDeck/session-20260921-161256/
|
||||
* device.txt what this device is, and every setting the session ran with
|
||||
* session.log the guest session: proot, gamescope, the client's stdout
|
||||
* wayland.log the app's compositor
|
||||
* steam.log the Steam client's own log, scrubbed (Steam mode)
|
||||
* steam/ the rest of the client's logs, scrubbed (Steam mode)
|
||||
* desktop.log labwc, the panel and the programs on it (desktop mode)
|
||||
* ```
|
||||
*
|
||||
* The folder is claimed by whoever starts first - the activity starts the compositor before the
|
||||
* service starts the session - so both write into the same one, and a recreated activity (a
|
||||
* foldable opening mid-session) joins the folder in progress instead of opening another.
|
||||
*/
|
||||
object SessionPaths {
|
||||
private const val TAG = "SessionPaths"
|
||||
|
||||
@Volatile
|
||||
private var dir: File? = null
|
||||
|
||||
/**
|
||||
* The folder for the session now starting, or the one already in progress. With logs turned
|
||||
* off on the main screen the folder lives in the app's cache instead of Downloads - the
|
||||
* scripts and the compositor still need somewhere to write - and [release] deletes it.
|
||||
*/
|
||||
@Synchronized
|
||||
fun beginOrCurrent(context: Context): File {
|
||||
dir?.let { if (it.isDirectory) return it }
|
||||
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
|
||||
val parent = if (SessionPrefs.logsEnabled(context)) SessionFiles.logDirectory(context)
|
||||
else File(context.cacheDir, "session-logs")
|
||||
val made = File(parent, "session-$stamp")
|
||||
if (!made.isDirectory && !made.mkdirs()) Log.e(TAG, "could not create $made")
|
||||
dir = made
|
||||
Log.i(TAG, "session logs: $made" + if (SessionPrefs.logsEnabled(context)) "" else " (logs off: discarded at the end)")
|
||||
return made
|
||||
}
|
||||
|
||||
/** The current session's folder, or null between sessions. */
|
||||
fun current(): File? = dir
|
||||
|
||||
/**
|
||||
* The ending session takes its folder with it: the next session (one that replaces this one
|
||||
* in place) then claims a folder of its own instead of sharing, and this one's collector
|
||||
* finishes the folder it was handed. Called on the main thread as the session stops.
|
||||
*/
|
||||
@Synchronized
|
||||
fun take(): File? {
|
||||
val ended = dir
|
||||
dir = null
|
||||
return ended
|
||||
}
|
||||
|
||||
/** A file in the current session's folder, or null between sessions. */
|
||||
fun file(name: String): File? = dir?.let { File(it, name) }
|
||||
|
||||
/** Let the next session claim a new folder. Called when a session ends. */
|
||||
@Synchronized
|
||||
fun release(context: Context, ended: File) {
|
||||
// Only the session that owns the folder lets go of it (take() usually has already): the
|
||||
// next session may have claimed its own by the time the last one's collector gets here.
|
||||
if (dir == ended) dir = null
|
||||
// A folder kept in the cache was never meant to outlive its session.
|
||||
if (ended != null && ended.path.startsWith(context.cacheDir.path)) {
|
||||
com.droiddeck.launcher.core.FileUtils.delete(ended)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
|
||||
object SessionPrefs {
|
||||
const val SUSPEND_AUTO = "auto"
|
||||
const val SUSPEND_MANUAL = "manual"
|
||||
const val SUSPEND_NEVER = "never"
|
||||
|
||||
const val OSC_AUTO = "auto"
|
||||
const val OSC_ALWAYS = "always"
|
||||
const val OSC_STEAM_QAM = "steam-qam"
|
||||
const val OSC_NEVER = "never"
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean("hud", true)
|
||||
|
||||
fun setHudEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hud", on).apply()
|
||||
}
|
||||
|
||||
const val TOUCH_AUTO = "auto"
|
||||
const val TOUCH_PAD = "touchpad"
|
||||
const val TOUCH_DIRECT = "direct"
|
||||
|
||||
/** How touch drives the pointer: a touchpad (drag moves it from where it is) or direct
|
||||
* (it jumps under the finger). Auto = touchpad on the desktop, direct in Steam. */
|
||||
fun touchMode(context: Context): String = prefs(context).getString("touch", TOUCH_AUTO) ?: TOUCH_AUTO
|
||||
|
||||
fun setTouchMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("touch", mode).apply()
|
||||
}
|
||||
|
||||
const val SHAPE_AUTO = "auto"
|
||||
const val SHAPE_WIDE = "16:9"
|
||||
const val SHAPE_EXACT = "exact"
|
||||
|
||||
/** The choices the settings offer, in order. */
|
||||
val shapeChoices = listOf(
|
||||
SHAPE_AUTO to "The panel's shape (16:9 or wider)",
|
||||
SHAPE_EXACT to "Exactly this panel (4:3, 3:2…)",
|
||||
SHAPE_WIDE to "16:9 with bars",
|
||||
)
|
||||
|
||||
/**
|
||||
* The shape of the display the session presents: the panel's own (never narrower than 16:9),
|
||||
* exactly the panel's (a 4:3 or 3:2 handheld, drawn edge to edge), or a fixed 16:9. A foldable defaults to 16:9, which sits with modest bars on either of its
|
||||
* panels; the panel's own shape would fit one and leave a strip on the other, and gamescope's
|
||||
* display cannot change size once the session is up.
|
||||
*/
|
||||
fun shapeMode(context: Context): String =
|
||||
prefs(context).getString("shape", null)
|
||||
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
|
||||
|
||||
fun setShapeMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("shape", mode).apply()
|
||||
}
|
||||
|
||||
fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO
|
||||
|
||||
fun setOscMode(context: Context, mode: String) {
|
||||
prefs(context).edit().putString("osc", mode).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The imported glibc Turnip a mode draws with inside the runtime, keyed by
|
||||
* SessionService.MODE_STEAM / MODE_DESKTOP so Steam and the desktop can differ; "" = the
|
||||
* driver built into the runtime. Resolved by LinuxVulkanDriver at session start.
|
||||
*/
|
||||
fun linuxDriver(context: Context, mode: String): String =
|
||||
prefs(context).getString("linuxDriver.$mode", "") ?: ""
|
||||
|
||||
fun setLinuxDriver(context: Context, mode: String, id: String) {
|
||||
prefs(context).edit().putString("linuxDriver.$mode", id).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The Steam client's own sound through the DirectAudio relay instead of the classic AAudio
|
||||
* sink. Off by default: on an AYN Thor (Android 13, 20 ms bursts) the relay path stayed choppy
|
||||
* where the classic sink - the one 0.1.5 shipped - was fine.
|
||||
*/
|
||||
fun clientDirectAudio(context: Context): Boolean = prefs(context).getBoolean("clientDirectAudio", false)
|
||||
|
||||
fun setClientDirectAudio(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("clientDirectAudio", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* DirectAudio for games: their Wine audio driver talks to the relay helper on this side. On
|
||||
* unless the user turned it off.
|
||||
*/
|
||||
fun directAudio(context: Context): Boolean = prefs(context).getBoolean("directAudio", true)
|
||||
|
||||
fun setDirectAudio(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("directAudio", on).apply()
|
||||
}
|
||||
|
||||
/** The microphone for voice chat, on unless turned off; used only once RECORD_AUDIO is granted. */
|
||||
fun micEnabled(context: Context): Boolean = prefs(context).getBoolean("mic", true)
|
||||
|
||||
/** Whether the app has already asked for the microphone once at start-up. */
|
||||
fun micAsked(context: Context): Boolean = prefs(context).getBoolean("micAsked", false)
|
||||
|
||||
fun setMicAsked(context: Context) {
|
||||
prefs(context).edit().putBoolean("micAsked", true).apply()
|
||||
}
|
||||
|
||||
fun setMicEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("mic", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the client's own core pick is overridden. When on, BL_CLIENT_CPUS is sent even when
|
||||
* it names every core - unlike a game mask, the point here is to undo a pin Steam applies to
|
||||
* itself, and the scheduler's default is exactly what Steam's choice takes away.
|
||||
*/
|
||||
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false)
|
||||
|
||||
fun setClientCpusOverride(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
|
||||
}
|
||||
|
||||
/** Comma-separated core list for the client (taskset -c syntax); "" = every core. */
|
||||
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "") ?: ""
|
||||
|
||||
fun setClientCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("clientCpus", list).apply()
|
||||
}
|
||||
|
||||
/** Comma-separated core list for games (taskset -c syntax); "" = every core = nothing sent. */
|
||||
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "") ?: ""
|
||||
|
||||
fun setGameCpus(context: Context, list: String) {
|
||||
prefs(context).edit().putString("gameCpus", list).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Steam's xalia helper is kept out of the session (PROTON_USE_XALIA=0).
|
||||
*
|
||||
* xalia is an x86 Windows program Proton launches to give Windows programs gamepad navigation.
|
||||
* Under FEX it cannot load the session's aarch64 preload shim, so its socket() and memfd calls
|
||||
* reach the vendor's seccomp filter raw; where that answers ENOSYS - a Galaxy Fold, measured -
|
||||
* it storms, and the session dies seconds after Big Picture appears.
|
||||
*/
|
||||
fun noXalia(context: Context): Boolean = prefs(context).getBoolean("noXalia", false)
|
||||
|
||||
fun setNoXalia(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("noXalia", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether proot runs without its seccomp acceleration (PROOT_NO_SECCOMP=1).
|
||||
*
|
||||
* proot normally installs a seccomp filter so only the syscalls it must rewrite stop in the
|
||||
* tracer; everything else runs untraced, which is most of proot's speed. Where a vendor kernel
|
||||
* handles that filter badly the wrong calls are trapped or refused - ENOSYS from calls that
|
||||
* plainly exist is the signature - and the fallback is to trace everything instead: slower,
|
||||
* but correct. Max's advice for devices whose kernels "don't work well with it".
|
||||
*/
|
||||
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
|
||||
|
||||
fun setProotNoSeccomp(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
|
||||
}
|
||||
|
||||
/** Turnip's sysmem rendering (TU_DEBUG=sysmem) for the runtime's driver: bypasses GMEM tiling. */
|
||||
fun tuSysmem(context: Context): Boolean = prefs(context).getBoolean("tuSysmem", false)
|
||||
|
||||
fun setTuSysmem(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("tuSysmem", on).apply()
|
||||
}
|
||||
|
||||
/*
|
||||
* The client's interface is drawn Chromium -> ANGLE -> Zink -> Turnip, and that chain is what
|
||||
* limits its menus (~14 fps on an Adreno 840 while a game ran 89). These make the chain
|
||||
* cheaper rather than asking for more; the three environment switches are on by default,
|
||||
* Deck mode off. Bannerlator's LinuxTuning, carried over; none device-proven here yet.
|
||||
*/
|
||||
/** mesa_glthread=true: GL marshalled off the calling thread. */
|
||||
fun glThread(context: Context): Boolean = prefs(context).getBoolean("glThread", true)
|
||||
fun setGlThread(context: Context, on: Boolean) { prefs(context).edit().putBoolean("glThread", on).apply() }
|
||||
|
||||
/** MESA_NO_ERROR=1: no GL error checking. */
|
||||
fun noGlError(context: Context): Boolean = prefs(context).getBoolean("noGlError", true)
|
||||
fun setNoGlError(context: Context, on: Boolean) { prefs(context).edit().putBoolean("noGlError", on).apply() }
|
||||
|
||||
/** `steam -steamdeck -steamos3`: the client as SteamOS runs it. Expects Deck hardware; untested. */
|
||||
fun steamDeckMode(context: Context): Boolean = prefs(context).getBoolean("steamDeckMode", false)
|
||||
fun setSteamDeckMode(context: Context, on: Boolean) { prefs(context).edit().putBoolean("steamDeckMode", on).apply() }
|
||||
|
||||
/** Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) for the client's GL-on-Vulkan UI. On by default. */
|
||||
fun zinkLazy(context: Context): Boolean = prefs(context).getBoolean("zinkLazy", true)
|
||||
|
||||
fun setZinkLazy(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("zinkLazy", on).apply()
|
||||
}
|
||||
|
||||
/** The Android driver the compositor loads: "" = pick by GPU, else a bundled or imported id. */
|
||||
@JvmStatic
|
||||
fun androidDriver(context: Context): String = prefs(context).getString("androidDriver", "") ?: ""
|
||||
|
||||
@JvmStatic
|
||||
fun setAndroidDriver(context: Context, id: String) {
|
||||
prefs(context).edit().putString("androidDriver", id).apply()
|
||||
}
|
||||
|
||||
// ── Storage the session can see ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The folder on this device that every session shows at `/root/ROMs`, for the emulators on the
|
||||
* desktop. "" = none chosen. All of internal storage is at `/root/Storage` regardless.
|
||||
*/
|
||||
fun romsDir(context: Context): String =
|
||||
prefs(context).getString("romsDir", "") ?: ""
|
||||
|
||||
fun setRomsDir(context: Context, path: String) {
|
||||
prefs(context).edit().putString("romsDir", path).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a session writes its folder under Download/DroidDeck. Off, the same logs are kept in
|
||||
* the app's cache for the session's lifetime (the scripts need somewhere to write) and thrown
|
||||
* away at the end, so nothing accumulates in Downloads.
|
||||
*/
|
||||
fun logsEnabled(context: Context): Boolean =
|
||||
prefs(context).getBoolean("logs", true)
|
||||
|
||||
fun setLogsEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("logs", on).apply()
|
||||
}
|
||||
|
||||
// ── Per-mode display ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The tallest the session's display may be, in pixels, for MODE_STEAM / MODE_DESKTOP:
|
||||
* 0 = the panel's own height, otherwise a cap. Both modes default to 720p: the client's CEF
|
||||
* is the heaviest thing in a session, Big Picture is drawn for a TV at arm's length, and on
|
||||
* a handheld panel 720p is where its menus stay responsive on a regular flagship; the desktop
|
||||
* and the emulators under it get the same GPU headroom. Read once, when the session's display
|
||||
* is sized; a cap the user chose wins over the default.
|
||||
*/
|
||||
fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", defaultResolutionCap(mode))
|
||||
|
||||
/** The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults. */
|
||||
fun fexPreset(context: Context): String = prefs(context).getString("fexPreset", "") ?: ""
|
||||
|
||||
fun setFexPreset(context: Context, id: String) {
|
||||
prefs(context).edit().putString("fexPreset", id).apply()
|
||||
}
|
||||
|
||||
/** The Steam client branch forced on the command line: "publicbeta" (every session so far) or "steamdeck_publicbeta" (Armada's). */
|
||||
fun steamChannel(context: Context): String =
|
||||
prefs(context).getString("steamChannel", null)
|
||||
// Deck mode on the publicbeta channel reinstalls the same client at every start (the
|
||||
// client reports "installed version 0" against that manifest and exits 42 to apply it,
|
||||
// losing the launch URL each time); on steamdeck_publicbeta the second launch comes up
|
||||
// clean. Seen on device 2026-09-23. So Deck mode takes the Deck channel unless chosen.
|
||||
?: if (steamDeckMode(context)) "steamdeck_publicbeta" else "publicbeta"
|
||||
|
||||
fun setSteamChannel(context: Context, id: String) {
|
||||
prefs(context).edit().putString("steamChannel", id).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders of the user's own Windows games (one game per subfolder), any number of them
|
||||
* from anywhere on the device. The single folder an earlier build kept is carried in.
|
||||
*/
|
||||
fun addedGamesDirs(context: Context): List<String> {
|
||||
val p = prefs(context)
|
||||
val list = p.getString("addedGamesDirs", null)
|
||||
if (list != null) return list.split('\n').filter { it.isNotEmpty() }
|
||||
val old = p.getString("addedGamesDir", "") ?: ""
|
||||
return if (old.isEmpty()) emptyList() else listOf(old)
|
||||
}
|
||||
|
||||
fun setAddedGamesDirs(context: Context, dirs: List<String>) {
|
||||
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
|
||||
}
|
||||
|
||||
/** Whether added games without art of their own get Steam's store art fetched for them. */
|
||||
fun addedGamesArt(context: Context): Boolean = prefs(context).getBoolean("addedGamesArt", true)
|
||||
|
||||
fun setAddedGamesArt(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("addedGamesArt", on).apply()
|
||||
}
|
||||
|
||||
/** The .exe the user chose for one game folder (by its path), "" = the scanner's pick. */
|
||||
fun addedGameExe(context: Context, folderPath: String): String = prefs(context).getString("addedExe:$folderPath", "") ?: ""
|
||||
|
||||
fun setAddedGameExe(context: Context, folderPath: String, path: String) {
|
||||
prefs(context).edit().putString("addedExe:$folderPath", path).apply()
|
||||
}
|
||||
|
||||
/** The app's colour theme (ui/Themes ids); Paper on black unless chosen otherwise. */
|
||||
fun theme(context: Context): String = prefs(context).getString("theme", "paper") ?: "paper"
|
||||
|
||||
fun setTheme(context: Context, id: String) {
|
||||
prefs(context).edit().putString("theme", id).apply()
|
||||
}
|
||||
|
||||
/** What a mode gets when nothing was chosen. */
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
fun defaultResolutionCap(mode: String): Int = 720
|
||||
|
||||
fun setResolutionCap(context: Context, mode: String, cap: Int) {
|
||||
prefs(context).edit().putInt("resolutionCap.$mode", cap).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* A fixed size for the session's display, per mode, or null. When set it replaces both the
|
||||
* cap and the shape: the compositor fits it to the panel with bars where the shapes differ.
|
||||
*/
|
||||
fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
|
||||
parseResolution(prefs(context).getString("customRes.$mode", null))
|
||||
|
||||
fun setCustomResolution(context: Context, mode: String, size: Pair<Int, Int>?) {
|
||||
prefs(context).edit().putString("customRes.$mode", size?.let { "${it.first}x${it.second}" }).apply()
|
||||
}
|
||||
|
||||
/** "1024x768" (or ×, or *) to an even size inside 320x240..3840x2160; anything else is null. */
|
||||
fun parseResolution(text: String?): Pair<Int, Int>? {
|
||||
val parts = text?.trim()?.split('x', 'X', '×', '*')?.map { it.trim() } ?: return null
|
||||
if (parts.size != 2) return null
|
||||
val w = parts[0].toIntOrNull() ?: return null
|
||||
val h = parts[1].toIntOrNull() ?: return null
|
||||
if (w !in 320..3840 || h !in 240..2160) return null
|
||||
return Pair(w and 1.inv(), h and 1.inv())
|
||||
}
|
||||
|
||||
/**
|
||||
* What the desktop shell composites with: pixman (software, the default - the Adreno stand-in
|
||||
* is not a DRM render node, so labwc's gbm allocator cannot use it), or gles2 / vulkan for a
|
||||
* device that has a real node. `Download/droiddeck-wlr-renderer` still overrides it.
|
||||
*/
|
||||
fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "pixman") ?: "pixman"
|
||||
|
||||
fun setDesktopRenderer(context: Context, renderer: String) {
|
||||
prefs(context).edit().putString("desktopRenderer", renderer).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel
|
||||
* lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app
|
||||
* process: a change applies after the app is fully closed and opened again.
|
||||
*/
|
||||
fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false)
|
||||
|
||||
fun setHdr(context: Context, mode: String, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hdr.$mode", on).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a
|
||||
* fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices.
|
||||
*/
|
||||
fun prefMode(mode: String): String = if (mode == SessionService.MODE_RUN) SessionService.MODE_STEAM else mode
|
||||
|
||||
fun suspendPolicy(context: Context, mode: String): String =
|
||||
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
|
||||
?.takeIf { it == SUSPEND_AUTO || it == SUSPEND_MANUAL || it == SUSPEND_NEVER }
|
||||
?: SUSPEND_MANUAL
|
||||
|
||||
fun setSuspendPolicy(context: Context, mode: String, policy: String) {
|
||||
val normalized = policy.takeIf { it == SUSPEND_AUTO || it == SUSPEND_MANUAL || it == SUSPEND_NEVER }
|
||||
?: SUSPEND_MANUAL
|
||||
prefs(context).edit().putString("suspendPolicy.${prefMode(mode)}", normalized).apply()
|
||||
}
|
||||
|
||||
// ── Game storage ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A second Steam library on this device: the folder bound at /mnt/bannerlator-sd and
|
||||
* registered with the client, which then asks where to install every game and shows both
|
||||
* on its Storage page. "" = automatic: the SD card when one is in the phone (the default,
|
||||
* so the choice is made inside the client like anywhere else); GAME_STORAGE_OFF = internal
|
||||
* only; otherwise the folder chosen.
|
||||
*/
|
||||
fun gameStorage(context: Context): String = prefs(context).getString("gameStorage", "") ?: ""
|
||||
|
||||
const val GAME_STORAGE_OFF = "off"
|
||||
|
||||
fun gameStorageLabel(context: Context): String = prefs(context).getString("gameStorageLabel", "SD Card") ?: "SD Card"
|
||||
|
||||
fun setGameStorage(context: Context, path: String, label: String) {
|
||||
prefs(context).edit().putString("gameStorage", path).putString("gameStorageLabel", label).apply()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,59 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
|
||||
/**
|
||||
* The little that the activity and the service have to agree on. Process-wide rather than passed
|
||||
* through intents, because both halves live in one process and the point of the split is that
|
||||
* either can outlive the other.
|
||||
*/
|
||||
object SessionState {
|
||||
@Volatile
|
||||
var running = false
|
||||
var suspended by mutableStateOf(false)
|
||||
/** MODE_RUN: the program inside the runtime the session was started for. */
|
||||
var program: String? = null
|
||||
var programArgs: List<String> = emptyList()
|
||||
/** MODE_STEAM: "desktop" for the client's desktop UI, else Big Picture; and a steam:// URL to hand it. */
|
||||
var steamUi: String? = null
|
||||
var steamUrl: String? = null
|
||||
/** A session the guest asked for (the desktop's Steam launchers): started by the activity once this one has ended. */
|
||||
var relaunch: android.content.Intent? = null
|
||||
/** HDR10 was asked for and the panel can show it: the compositor was told, and the session
|
||||
* gets DXVK_HDR=1 and gamescope --hdr-enabled. Decided by the activity before the compositor starts. */
|
||||
@JvmStatic var hdr = false
|
||||
|
||||
/** Which session this is: SessionService.MODE_STEAM or MODE_DESKTOP. */
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
|
||||
/** The size gamescope was told to render at; set by the activity before the service starts. */
|
||||
@Volatile
|
||||
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
||||
|
||||
@Volatile
|
||||
var refreshHz: Float = 60f
|
||||
|
||||
/** The compositor has presented a frame, so the loading panel is behind us for this session. */
|
||||
@Volatile
|
||||
var firstFrameSeen = false
|
||||
|
||||
/** Where this session is writing its log, for the "it ended" message. */
|
||||
@Volatile
|
||||
var logFile: File? = null
|
||||
|
||||
/** The fake evdev directory, once the service has prepared the rings. */
|
||||
@Volatile
|
||||
var fakeInputDir: File? = null
|
||||
|
||||
/** Told when the session ends, so a visible activity can close itself. */
|
||||
@Volatile
|
||||
var endListener: ((Int) -> Unit)? = null
|
||||
|
||||
fun notifyEnded(status: Int) {
|
||||
endListener?.invoke(status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.os.Process
|
||||
import java.io.File
|
||||
import java.util.concurrent.ExecutorService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
internal class SessionSuspendController(
|
||||
private val sessionRoot: () -> Int,
|
||||
private val helperRoots: () -> List<Int>,
|
||||
private val suspendAudio: () -> Unit,
|
||||
private val resumeAudio: () -> Unit,
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
private data class ProcessRecord(
|
||||
val pid: Int,
|
||||
val started: Long,
|
||||
val role: Role,
|
||||
)
|
||||
|
||||
private data class ProcessInfo(
|
||||
val pid: Int,
|
||||
val parent: Int,
|
||||
val started: Long,
|
||||
val state: Char,
|
||||
)
|
||||
|
||||
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
|
||||
@Volatile private var closing = false
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
|
||||
fun freeze(completion: (Boolean) -> Unit) {
|
||||
submit {
|
||||
if (closing) {
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
if (frozen.isNotEmpty()) {
|
||||
val fullyFrozen = frozen.any { it.role == Role.SESSION_ROOT } && frozen.all(::isStoppedOrGone)
|
||||
if (!fullyFrozen && restore(frozen)) frozen = emptyList()
|
||||
completion(fullyFrozen)
|
||||
return@submit
|
||||
}
|
||||
val records = LinkedHashMap<Pair<Int, Long>, ProcessRecord>()
|
||||
val root = sessionRoot()
|
||||
if (root <= 1) {
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
runAudio(suspendAudio)
|
||||
val helpers = helperRoots().filter { it > 1 && it != root }.distinct()
|
||||
var stablePasses = 0
|
||||
var complete = false
|
||||
repeat(10) { pass ->
|
||||
if (closing) {
|
||||
restore(records.values.toList())
|
||||
runAudio(resumeAudio)
|
||||
completion(false)
|
||||
return@submit
|
||||
}
|
||||
val includeRoots = pass >= 2
|
||||
addSnapshot(records, root, helpers, includeRoots)
|
||||
stop(records.values.toList(), includeRoots)
|
||||
Thread.sleep(if (pass == 0) 70L else 35L)
|
||||
val rootCaptured = records.values.any { it.role == Role.SESSION_ROOT }
|
||||
if (rootCaptured && records.isNotEmpty() && records.values.all(::isStoppedOrGone)) {
|
||||
stablePasses++
|
||||
if (stablePasses >= 2) complete = true
|
||||
} else {
|
||||
stablePasses = 0
|
||||
}
|
||||
}
|
||||
if (complete) {
|
||||
frozen = records.values.toList()
|
||||
completion(true)
|
||||
} else {
|
||||
val restored = restore(records.values.toList())
|
||||
runAudio(resumeAudio)
|
||||
if (!restored) frozen = records.values.toList()
|
||||
completion(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
submit {
|
||||
val records = frozen
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restore(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
}
|
||||
}
|
||||
|
||||
fun closeAndResume(completion: () -> Unit) {
|
||||
closing = true
|
||||
submit {
|
||||
restore(frozen)
|
||||
frozen = emptyList()
|
||||
completion()
|
||||
executor.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
private fun submit(task: () -> Unit) {
|
||||
try {
|
||||
executor.execute {
|
||||
try {
|
||||
task()
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
} catch (_: RuntimeException) {
|
||||
task()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runAudio(action: () -> Unit) {
|
||||
try {
|
||||
action()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun addSnapshot(
|
||||
records: MutableMap<Pair<Int, Long>, ProcessRecord>,
|
||||
root: Int,
|
||||
helpers: List<Int>,
|
||||
includeRoots: Boolean,
|
||||
) {
|
||||
val processes = readProcesses()
|
||||
val byPid = processes.associateBy { it.pid }
|
||||
for (process in descendants(root, processes, byPid)) {
|
||||
records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.SESSION_CHILD)
|
||||
}
|
||||
for (helper in helpers) {
|
||||
for (process in descendants(helper, processes, byPid)) {
|
||||
records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.HELPER_CHILD)
|
||||
}
|
||||
}
|
||||
if (includeRoots) {
|
||||
byPid[root]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) }
|
||||
for (helper in helpers) {
|
||||
byPid[helper]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun descendants(root: Int, processes: List<ProcessInfo>, byPid: Map<Int, ProcessInfo>): List<ProcessInfo> {
|
||||
if (root !in byPid) return emptyList()
|
||||
val children = HashMap<Int, MutableList<ProcessInfo>>()
|
||||
for (process in processes) children.getOrPut(process.parent) { ArrayList() }.add(process)
|
||||
val excluded = Process.myPid()
|
||||
val found = ArrayList<ProcessInfo>()
|
||||
val seen = HashSet<Int>()
|
||||
val queue = ArrayDeque<Int>().apply { add(root) }
|
||||
while (queue.isNotEmpty()) {
|
||||
val parent = queue.removeFirst()
|
||||
for (child in children[parent].orEmpty()) {
|
||||
if (child.pid <= 1 || child.pid == excluded || !seen.add(child.pid)) continue
|
||||
found.add(child)
|
||||
queue.add(child.pid)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
private fun readProcesses(): List<ProcessInfo> =
|
||||
File("/proc").listFiles().orEmpty().mapNotNull { entry ->
|
||||
val pid = entry.name.toIntOrNull() ?: return@mapNotNull null
|
||||
readProcess(pid)
|
||||
}
|
||||
|
||||
private fun readProcess(pid: Int): ProcessInfo? {
|
||||
val stat = try {
|
||||
File("/proc/$pid/stat").readText()
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
val close = stat.lastIndexOf(')')
|
||||
if (close < 0 || close + 2 >= stat.length) return null
|
||||
val fields = stat.substring(close + 2).trim().split(Regex("\\s+"))
|
||||
if (fields.size < 20) return null
|
||||
return try {
|
||||
ProcessInfo(pid, fields[1].toInt(), fields[19].toLong(), fields[0].first())
|
||||
} catch (_: NumberFormatException) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun stop(records: List<ProcessRecord>, includeRoots: Boolean) {
|
||||
val descendants = records.filter { it.role == Role.SESSION_CHILD || it.role == Role.HELPER_CHILD }
|
||||
val session = records.filter { it.role == Role.SESSION_ROOT }
|
||||
val helpers = records.filter { it.role == Role.HELPER_ROOT }
|
||||
for (record in descendants) send(record, SIGSTOP)
|
||||
if (includeRoots) {
|
||||
for (record in session) send(record, SIGSTOP)
|
||||
for (record in helpers) send(record, SIGSTOP)
|
||||
}
|
||||
}
|
||||
|
||||
private fun restore(records: List<ProcessRecord>): Boolean {
|
||||
val ordered = records.sortedBy {
|
||||
when (it.role) {
|
||||
Role.SESSION_ROOT -> 0
|
||||
Role.HELPER_ROOT -> 1
|
||||
Role.SESSION_CHILD -> 2
|
||||
Role.HELPER_CHILD -> 3
|
||||
}
|
||||
}
|
||||
for (record in ordered) send(record, SIGCONT)
|
||||
repeat(8) {
|
||||
Thread.sleep(25L)
|
||||
if (ordered.all(::isRunningOrGone)) return true
|
||||
}
|
||||
return ordered.all(::isRunningOrGone)
|
||||
}
|
||||
|
||||
private fun send(record: ProcessRecord, signal: Int) {
|
||||
val current = readProcess(record.pid) ?: return
|
||||
if (current.started != record.started) return
|
||||
try {
|
||||
Process.sendSignal(record.pid, signal)
|
||||
} catch (_: Throwable) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun isStoppedOrGone(record: ProcessRecord): Boolean {
|
||||
val current = readProcess(record.pid) ?: return true
|
||||
if (current.started != record.started) return true
|
||||
return current.state == 'T' || current.state == 't' || current.state == 'Z' || current.state == 'X'
|
||||
}
|
||||
|
||||
private fun isRunningOrGone(record: ProcessRecord): Boolean {
|
||||
val current = readProcess(record.pid) ?: return true
|
||||
if (current.started != record.started) return true
|
||||
return current.state != 'T' && current.state != 't'
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SIGSTOP = 19
|
||||
const val SIGCONT = 18
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.termux.terminal.TerminalSession
|
||||
import com.termux.terminal.TerminalSessionClient
|
||||
import java.io.File
|
||||
|
||||
/** Immutable launch context for the optional PTY shell attached to the active Linux runtime. */
|
||||
object SessionTerminal {
|
||||
private data class Launch(
|
||||
val command: Array<String>,
|
||||
val hostEnvironment: Array<String>,
|
||||
val workingDirectory: String,
|
||||
val generation: Int,
|
||||
)
|
||||
|
||||
@Volatile private var launch: Launch? = null
|
||||
|
||||
fun prepare(
|
||||
command: List<String>,
|
||||
hostEnvironment: Array<String>,
|
||||
workingDirectory: File,
|
||||
generation: Int,
|
||||
) {
|
||||
launch = Launch(command.toTypedArray(), hostEnvironment.copyOf(), workingDirectory.path, generation)
|
||||
}
|
||||
|
||||
fun create(client: TerminalSessionClient): TerminalSession? {
|
||||
val current = launch ?: return null
|
||||
if (!SessionState.running) return null
|
||||
return TerminalSession(
|
||||
current.command.first(), current.workingDirectory, current.command,
|
||||
current.hostEnvironment, 3000, client,
|
||||
).also { it.mSessionName = "DroidDeck Linux shell" }
|
||||
}
|
||||
|
||||
fun clear(generation: Int? = null) {
|
||||
val current = launch ?: return
|
||||
if (generation == null || current.generation == generation) launch = null
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user