mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-21 05:46:03 +00:00
Merge origin/main into feat/malibridge-v25
This commit is contained in:
commit
a2a5f84711
132 files changed
+7212
-156
No files matched your search
@@ -0,0 +1,65 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.app.Notification
|
||||
import android.content.Context
|
||||
import android.service.notification.NotificationListenerService
|
||||
import android.service.notification.StatusBarNotification
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
|
||||
/** One notification for the bottom-screen list. Kept in memory only; never written to disk or logs. */
|
||||
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
|
||||
|
||||
/**
|
||||
* Notifications from other apps for the bottom screen, so a message can be read without leaving the game.
|
||||
* Works only after the user allows DroidDeck notification access in Android settings.
|
||||
*/
|
||||
object BottomNotifications {
|
||||
val items = mutableStateListOf<BottomNotification>()
|
||||
|
||||
fun granted(context: Context): Boolean =
|
||||
context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
|
||||
|
||||
internal fun keep(own: String, pkg: String, ongoing: Boolean, groupSummary: Boolean, title: String, text: String): Boolean =
|
||||
pkg != own && !ongoing && !groupSummary && (title.isNotBlank() || text.isNotBlank())
|
||||
|
||||
internal fun add(list: MutableList<BottomNotification>, item: BottomNotification) {
|
||||
list.removeAll { it.key == item.key }
|
||||
list.add(0, item)
|
||||
while (list.size > MAX_ITEMS) list.removeAt(list.lastIndex)
|
||||
}
|
||||
|
||||
fun clear() = items.clear()
|
||||
|
||||
internal fun post(context: Context, sbn: StatusBarNotification) {
|
||||
val n = sbn.notification ?: return
|
||||
val extras = n.extras
|
||||
val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
|
||||
val text = (extras?.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras?.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
|
||||
if (!keep(context.packageName, sbn.packageName, sbn.isOngoing, (n.flags and Notification.FLAG_GROUP_SUMMARY) != 0, title, text)) return
|
||||
val app = runCatching {
|
||||
val pm = context.packageManager
|
||||
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
|
||||
}.getOrDefault(sbn.packageName)
|
||||
add(items, BottomNotification(sbn.key, app, title, text, sbn.postTime))
|
||||
}
|
||||
|
||||
internal fun remove(key: String) {
|
||||
items.removeAll { it.key == key }
|
||||
}
|
||||
|
||||
private const val MAX_ITEMS = 30
|
||||
}
|
||||
|
||||
class BottomNotificationListener : NotificationListenerService() {
|
||||
override fun onListenerConnected() {
|
||||
BottomNotifications.clear()
|
||||
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
|
||||
}
|
||||
|
||||
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
|
||||
|
||||
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
|
||||
|
||||
override fun onListenerDisconnected() = BottomNotifications.clear()
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */
|
||||
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
|
||||
val model: Any get() = uri ?: file!!
|
||||
}
|
||||
|
||||
/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */
|
||||
object BottomScreenshots {
|
||||
private const val FOLDER = "DroidDeck"
|
||||
private const val QUALITY = 95
|
||||
private const val LIMIT = 120
|
||||
|
||||
internal fun fileName(at: Long): String =
|
||||
"DroidDeck_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(at)) + ".jpg"
|
||||
|
||||
fun save(context: Context, bitmap: Bitmap, at: Long = System.currentTimeMillis()): Boolean = runCatching {
|
||||
val name = fileName(at)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = context.contentResolver
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Images.Media.DISPLAY_NAME, name)
|
||||
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
|
||||
put(MediaStore.Images.Media.DATE_TAKEN, at)
|
||||
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$FOLDER")
|
||||
put(MediaStore.Images.Media.IS_PENDING, 1)
|
||||
}
|
||||
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false
|
||||
val written = runCatching {
|
||||
resolver.openOutputStream(uri)?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } == true
|
||||
}.getOrDefault(false)
|
||||
if (!written) {
|
||||
resolver.delete(uri, null, null)
|
||||
return false
|
||||
}
|
||||
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
|
||||
true
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
|
||||
if (!dir.isDirectory && !dir.mkdirs()) return false
|
||||
val file = File(dir, name)
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) }
|
||||
android.media.MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf("image/jpeg"), null)
|
||||
true
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** Newest first, at most [LIMIT]. */
|
||||
fun list(context: Context, runtimeRoot: File): List<BottomShot> =
|
||||
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
|
||||
|
||||
private fun own(context: Context): List<BottomShot> = runCatching {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
|
||||
return dir.listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty()
|
||||
.map { BottomShot(null, it, it.lastModified(), steam = false) }
|
||||
}
|
||||
val shots = ArrayList<BottomShot>()
|
||||
context.contentResolver.query(
|
||||
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
||||
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_ADDED),
|
||||
"${MediaStore.Images.Media.RELATIVE_PATH} = ?", arrayOf("${Environment.DIRECTORY_PICTURES}/$FOLDER/"),
|
||||
"${MediaStore.Images.Media.DATE_ADDED} DESC",
|
||||
)?.use { c ->
|
||||
while (c.moveToNext() && shots.size < LIMIT) {
|
||||
val taken = c.getLong(1).takeIf { it > 0L } ?: (c.getLong(2) * 1000L)
|
||||
shots += BottomShot(android.content.ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getLong(0)),
|
||||
null, taken, steam = false)
|
||||
}
|
||||
}
|
||||
shots
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
/** The .jpg files in userdata/<account>/760/remote/<app>/screenshots of each Steam home; the thumbnails folder is skipped. */
|
||||
internal fun steam(runtimeRoot: File): List<BottomShot> =
|
||||
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
|
||||
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
|
||||
File(account, "760/remote").listFiles { f -> f.isDirectory }.orEmpty().flatMap { app ->
|
||||
File(app, "screenshots").listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
}.map { BottomShot(null, it, it.lastModified(), steam = true) }
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */
|
||||
data class Telemetry(
|
||||
val source: String,
|
||||
val speedKmh: Float? = null,
|
||||
val rpm: Float? = null,
|
||||
val maxRpm: Float? = null,
|
||||
val gear: String? = null,
|
||||
val throttle: Float? = null,
|
||||
val brake: Float? = null,
|
||||
val lap: Int? = null,
|
||||
val laps: Int? = null,
|
||||
val position: Int? = null,
|
||||
val fuel: Float? = null,
|
||||
val currentLapS: Float? = null,
|
||||
val lastLapS: Float? = null,
|
||||
val bestLapS: Float? = null,
|
||||
/** G-force as the game sends it (lateral, longitudinal) and steering from -1 (left) to 1 (right). */
|
||||
val gLat: Float? = null,
|
||||
val gLon: Float? = null,
|
||||
val steer: Float? = null,
|
||||
/** Front left, front right, rear left, rear right. */
|
||||
val tireTempsC: List<Float>? = null,
|
||||
val turboBar: Float? = null,
|
||||
val engineTempC: Float? = null,
|
||||
val oilTempC: Float? = null,
|
||||
/** OutGauge dashboard lights that are on, as GameTelemetry.DL_* bits. */
|
||||
val lights: Int? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or
|
||||
* its common tools use by default:
|
||||
* - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array), DiRT Showdown (152-byte packet).
|
||||
* - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash).
|
||||
* - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge.
|
||||
*/
|
||||
object GameTelemetry {
|
||||
const val CODEMASTERS_PORT = 20777
|
||||
const val FORZA_PORT = 5300
|
||||
const val OUTGAUGE_PORT = 4444
|
||||
val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT)
|
||||
|
||||
// Games send to 127.0.0.1; on Android InetAddress.getLoopbackAddress() is ::1, which IPv4 packets never reach.
|
||||
val LISTEN_ADDRESS: java.net.InetAddress = java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))
|
||||
|
||||
fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching {
|
||||
val buf = ByteBuffer.wrap(data, 0, length).order(ByteOrder.LITTLE_ENDIAN)
|
||||
when (port) {
|
||||
CODEMASTERS_PORT -> codemasters(buf, length)
|
||||
FORZA_PORT -> forza(buf, length)
|
||||
OUTGAUGE_PORT -> outGauge(buf, length)
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
private const val MPS_TO_KMH = 3.6f
|
||||
private const val GRAVITY = 9.81f
|
||||
|
||||
// OutGauge DashLights / ShowLights bits (Live for Speed InSim; BeamNG uses the same values).
|
||||
const val DL_SHIFT = 1
|
||||
const val DL_HANDBRAKE = 4
|
||||
const val DL_PITSPEED = 8
|
||||
const val DL_TC = 16
|
||||
const val DL_ABS = 1024
|
||||
|
||||
// Float indexes of the Codemasters packet; engine rpm values are sent divided by 10. Older games
|
||||
// (DiRT Showdown) send only the first 38 floats, so lap count, position, fuel and max rpm are missing there.
|
||||
private const val CM_LAP_TIME = 1
|
||||
private const val CM_SPEED = 7
|
||||
private const val CM_THROTTLE = 29
|
||||
private const val CM_STEER = 30
|
||||
private const val CM_BRAKE = 31
|
||||
private const val CM_GEAR = 33
|
||||
private const val CM_G_LAT = 34
|
||||
private const val CM_G_LON = 35
|
||||
private const val CM_LAP = 36
|
||||
private const val CM_RPM = 37
|
||||
private const val CM_POSITION = 39
|
||||
private const val CM_FUEL = 45
|
||||
private const val CM_FUEL_CAPACITY = 46
|
||||
private const val CM_LAPS = 60
|
||||
private const val CM_LAST_LAP = 62
|
||||
private const val CM_MAX_RPM = 63
|
||||
private const val CM_MIN_FLOATS = 38
|
||||
|
||||
internal fun codemasters(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < CM_MIN_FLOATS * 4) return null
|
||||
val floats = length / 4
|
||||
fun f(i: Int) = if (i < floats) buf.getFloat(i * 4) else 0f
|
||||
val gear = f(CM_GEAR).toInt()
|
||||
val capacity = f(CM_FUEL_CAPACITY)
|
||||
return Telemetry(
|
||||
source = "Codemasters",
|
||||
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
|
||||
rpm = f(CM_RPM) * 10f,
|
||||
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
|
||||
// Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1.
|
||||
gear = when {
|
||||
gear == 0 -> "N"
|
||||
gear < 0 || gear == 10 -> "R"
|
||||
else -> gear.toString()
|
||||
},
|
||||
throttle = f(CM_THROTTLE).coerceIn(0f, 1f),
|
||||
brake = f(CM_BRAKE).coerceIn(0f, 1f),
|
||||
lap = f(CM_LAP).toInt() + 1,
|
||||
laps = f(CM_LAPS).toInt().takeIf { it > 0 },
|
||||
position = f(CM_POSITION).toInt().takeIf { it > 0 },
|
||||
fuel = if (capacity > 0f) (f(CM_FUEL) / capacity).coerceIn(0f, 1f) else null,
|
||||
currentLapS = f(CM_LAP_TIME).takeIf { it > 0f },
|
||||
lastLapS = f(CM_LAST_LAP).takeIf { it > 0f },
|
||||
gLat = f(CM_G_LAT),
|
||||
gLon = f(CM_G_LON),
|
||||
steer = f(CM_STEER).coerceIn(-1f, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
// Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send
|
||||
// 324 bytes with 12 extra bytes before the Dash block.
|
||||
private const val FORZA_SLED = 232
|
||||
private const val FORZA_FM7 = 311
|
||||
private const val FORZA_HORIZON = 324
|
||||
private const val FORZA_FM2023 = 331
|
||||
private const val HORIZON_SHIFT = 12
|
||||
|
||||
internal fun forza(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < FORZA_SLED) return null
|
||||
val racing = buf.getInt(0) != 0
|
||||
val maxRpm = buf.getFloat(8)
|
||||
val rpm = buf.getFloat(16)
|
||||
val dash = when (length) {
|
||||
FORZA_FM7, FORZA_FM2023 -> FORZA_SLED
|
||||
FORZA_HORIZON -> FORZA_SLED + HORIZON_SHIFT
|
||||
else -> -1
|
||||
}
|
||||
if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f })
|
||||
if (!racing) return Telemetry(source = "Forza")
|
||||
val gear = buf.get(dash + 75).toInt() and 0xFF
|
||||
// Tire temperatures are read as Fahrenheit, as community Data Out parsers do; not checked on a device.
|
||||
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
|
||||
return Telemetry(
|
||||
source = "Forza",
|
||||
speedKmh = buf.getFloat(dash + 12) * MPS_TO_KMH,
|
||||
rpm = rpm,
|
||||
maxRpm = maxRpm.takeIf { it > 0f },
|
||||
gear = if (gear == 0) "R" else gear.toString(),
|
||||
throttle = (buf.get(dash + 71).toInt() and 0xFF) / 255f,
|
||||
brake = (buf.get(dash + 72).toInt() and 0xFF) / 255f,
|
||||
lap = (buf.getShort(dash + 68).toInt() and 0xFFFF) + 1,
|
||||
position = (buf.get(dash + 70).toInt() and 0xFF).takeIf { it > 0 },
|
||||
fuel = buf.getFloat(dash + 44).coerceIn(0f, 1f),
|
||||
currentLapS = buf.getFloat(dash + 60).takeIf { it > 0f },
|
||||
lastLapS = buf.getFloat(dash + 56).takeIf { it > 0f },
|
||||
bestLapS = buf.getFloat(dash + 52).takeIf { it > 0f },
|
||||
gLat = buf.getFloat(20) / GRAVITY,
|
||||
gLon = buf.getFloat(28) / GRAVITY,
|
||||
steer = (buf.get(dash + 76).toFloat() / 127f).coerceIn(-1f, 1f),
|
||||
tireTempsC = tiresF.takeIf { f -> f.any { it > 0f } }?.map { (it - 32f) * 5f / 9f },
|
||||
)
|
||||
}
|
||||
|
||||
// OutGauge: 92 bytes, or 96 with the optional id at the end.
|
||||
private const val OUTGAUGE_SIZE = 92
|
||||
|
||||
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
|
||||
if (length < OUTGAUGE_SIZE) return null
|
||||
val gear = buf.get(10).toInt() and 0xFF
|
||||
return Telemetry(
|
||||
source = "OutGauge",
|
||||
speedKmh = buf.getFloat(12) * MPS_TO_KMH,
|
||||
rpm = buf.getFloat(16),
|
||||
gear = when (gear) {
|
||||
0 -> "R"
|
||||
1 -> "N"
|
||||
else -> (gear - 1).toString()
|
||||
},
|
||||
throttle = buf.getFloat(48).coerceIn(0f, 1f),
|
||||
brake = buf.getFloat(52).coerceIn(0f, 1f),
|
||||
fuel = buf.getFloat(28).coerceIn(0f, 1f),
|
||||
turboBar = buf.getFloat(20).takeIf { it != 0f },
|
||||
engineTempC = buf.getFloat(24).takeIf { it != 0f },
|
||||
oilTempC = buf.getFloat(36).takeIf { it != 0f },
|
||||
lights = buf.getInt(44).takeIf { buf.getInt(40) != 0 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */
|
||||
object GameStatusFiles {
|
||||
const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state"
|
||||
private const val ELITE_APP = "359320"
|
||||
private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json"
|
||||
const val WAR_THUNDER_ROWS = 12
|
||||
|
||||
/** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */
|
||||
internal fun warThunder(json: String): List<Pair<String, String>> {
|
||||
val state = org.json.JSONObject(json)
|
||||
if (!state.optBoolean("valid", false)) return emptyList()
|
||||
return state.keys().asSequence().filter { it != "valid" }.mapNotNull { key ->
|
||||
val value = state.opt(key) as? Number ?: return@mapNotNull null
|
||||
key to if (value.toDouble() % 1.0 == 0.0) value.toLong().toString() else "%.1f".format(java.util.Locale.US, value.toDouble())
|
||||
}.toList()
|
||||
}
|
||||
|
||||
fun eliteStatusFile(runtimeRoot: java.io.File, mounts: Map<String, java.io.File>): java.io.File? {
|
||||
val libraries = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { it.parentFile } +
|
||||
SteamDownloadMonitor.STEAM_HOMES.map { java.io.File(runtimeRoot, "$it/steamapps") }
|
||||
return libraries.distinct().map { java.io.File(it, "compatdata/$ELITE_APP/$ELITE_STATUS") }.firstOrNull { it.isFile }
|
||||
}
|
||||
|
||||
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List<Int>?, val legal: String?, val balance: Long?)
|
||||
|
||||
/** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */
|
||||
internal fun elite(json: String): Elite? {
|
||||
val s = org.json.JSONObject(json)
|
||||
val fuel = s.optJSONObject("Fuel")
|
||||
val pips = s.optJSONArray("Pips")?.let { a -> (0 until a.length()).map { a.optInt(it) } }
|
||||
if (fuel == null && pips == null && !s.has("Cargo") && !s.has("Balance")) return null
|
||||
return Elite(
|
||||
fuelMain = fuel?.optDouble("FuelMain")?.takeIf { !it.isNaN() },
|
||||
fuelReserve = fuel?.optDouble("FuelReservoir")?.takeIf { !it.isNaN() },
|
||||
cargo = s.optDouble("Cargo").takeIf { !it.isNaN() },
|
||||
pips = pips,
|
||||
legal = s.optString("LegalState").takeIf { it.isNotEmpty() },
|
||||
balance = if (s.has("Balance")) s.optLong("Balance") else null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,7 @@ object SessionFiles {
|
||||
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
|
||||
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
|
||||
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
|
||||
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
|
||||
) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
|
||||
|
||||
@@ -100,6 +100,38 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("secondScreenPanel", mode).apply()
|
||||
}
|
||||
|
||||
fun statsStrip(context: Context): String? = prefs(context).getString("statsStrip", null)
|
||||
|
||||
fun setStatsStrip(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsStrip", id).apply()
|
||||
}
|
||||
|
||||
fun statsSpeedUnit(context: Context): String? = prefs(context).getString("statsSpeedUnit", null)
|
||||
|
||||
fun setStatsSpeedUnit(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsSpeedUnit", id).apply()
|
||||
}
|
||||
|
||||
fun statsDash(context: Context): String? = prefs(context).getString("statsDash", null)
|
||||
|
||||
fun setStatsDash(context: Context, id: String) {
|
||||
prefs(context).edit().putString("statsDash", id).apply()
|
||||
}
|
||||
|
||||
/** In-game stats "Send dashboard data" Automatic: on unless the user switched it off. */
|
||||
fun telemetryAuto(context: Context): Boolean = prefs(context).getBoolean("telemetryAuto", true)
|
||||
|
||||
fun setTelemetryAuto(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
|
||||
}
|
||||
|
||||
/** Games the user switched off by hand, as TelemetryOutput keys; Automatic leaves them alone. */
|
||||
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
|
||||
|
||||
fun setTelemetryOff(context: Context, keys: Set<String>) {
|
||||
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
|
||||
}
|
||||
|
||||
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
|
||||
|
||||
fun setDualScreenLauncher(context: Context, on: Boolean) {
|
||||
@@ -1133,7 +1165,7 @@ object SessionPrefs {
|
||||
|
||||
/** The drawer's frame limit slider: its first stop is Off. */
|
||||
const val FPS_LIMIT_OFF = 15
|
||||
const val FPS_LIMIT_MAX = 120
|
||||
const val FPS_LIMIT_MAX = 165
|
||||
|
||||
/**
|
||||
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
|
||||
|
||||
@@ -73,7 +73,9 @@ class SessionService : Service() {
|
||||
private var downloadMonitorTask: Runnable? = null
|
||||
private var downloadActive = false
|
||||
private var clientInstallActive = false
|
||||
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
|
||||
private var steamLibraryMounts: Map<String, File>
|
||||
get() = SessionState.steamLibraryMounts
|
||||
set(value) { SessionState.steamLibraryMounts = value }
|
||||
private var suspendDownloadNow = false
|
||||
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
|
||||
private var steamDownloadsInBackground = false
|
||||
@@ -728,6 +730,20 @@ class SessionService : Service() {
|
||||
))
|
||||
}
|
||||
},
|
||||
readBackAllowed = { SessionPrefs.ramCapMb(this) == 0 },
|
||||
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
|
||||
if (processes == 0) {
|
||||
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (RAM cap, or ${availableKb / 1024} MB available is too little)")
|
||||
} else {
|
||||
Log.i(TAG, "read back $processes processes in $millis ms: zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
|
||||
}
|
||||
mainHandler.post {
|
||||
SessionEvents.record("session.paged_in", mapOf(
|
||||
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
|
||||
"availableMb" to availableKb / 1024, "ms" to millis,
|
||||
))
|
||||
}
|
||||
},
|
||||
)
|
||||
updateDownloadMonitoring()
|
||||
mainHandler.post { updateSuspendPolicy() }
|
||||
|
||||
@@ -94,6 +94,9 @@ object SessionState {
|
||||
@Volatile var secondScreenAutoOpened = false
|
||||
@Volatile var secondScreenProvisional = false
|
||||
|
||||
/** Guest library paths on removable storage and the host folders they are mounted from, set by SessionService. */
|
||||
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
|
||||
|
||||
@Volatile
|
||||
var mode = "steam"
|
||||
|
||||
|
||||
@@ -26,6 +26,11 @@ internal class SessionSuspendController(
|
||||
private val nowNanos: () -> Long = System::nanoTime,
|
||||
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _, _ -> },
|
||||
// False with a RAM cap set: the user asked for the session to use less memory, so nothing is read back.
|
||||
private val readBackAllowed: () -> Boolean = { true },
|
||||
// processes is 0 when the read-back was skipped: a RAM cap, or MemAvailable could not take it.
|
||||
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _ -> },
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
@@ -49,6 +54,7 @@ internal class SessionSuspendController(
|
||||
@Volatile private var cancelled = false
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
private var frozenSince: Long? = null
|
||||
private var pagedOutTargets = emptyList<ProcessRecord>()
|
||||
|
||||
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
|
||||
cancelled = false
|
||||
@@ -107,6 +113,8 @@ internal class SessionSuspendController(
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
completion(complete)
|
||||
// A cancelled or failed freeze leaves the game running with whatever the page-out already moved.
|
||||
if (!complete && frozen.isEmpty() && !interrupted) readBack()
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
@@ -123,6 +131,7 @@ internal class SessionSuspendController(
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
if (resumed) readBack()
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
@@ -289,6 +298,7 @@ internal class SessionSuspendController(
|
||||
}
|
||||
}
|
||||
if (targets.isEmpty()) return
|
||||
pagedOutTargets = (pagedOutTargets + targets).distinct()
|
||||
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
|
||||
acks.values.forEach { it.delete() }
|
||||
val start = nowMillis()
|
||||
@@ -309,6 +319,69 @@ internal class SessionSuspendController(
|
||||
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
|
||||
}
|
||||
|
||||
// Left in zram, the paged-out memory comes back one major fault at a time while the game runs; in a heavy
|
||||
// game that is hundreds of faults per frame and stalls of a quarter second and more, long after the resume.
|
||||
// libblsession's handler reads back only the swapped pages (mode 0, as the session script does for the client).
|
||||
// The handler runs on whichever thread takes the signal, so that thread pauses for the read-back,
|
||||
// once and right after the resume instead of mid-game.
|
||||
// It signals even with nothing in zram yet: after a cancelled freeze a page-out handler may not have started,
|
||||
// and it reads the mode only when it starts, so it reads back instead of paging out.
|
||||
private fun readBack() {
|
||||
val targets = pagedOutTargets.filterNot { isGone(it) }
|
||||
pagedOutTargets = emptyList()
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return
|
||||
if (targets.isEmpty() || closing) return
|
||||
val before = memoryKb(targets).second
|
||||
val (total, available) = meminfoKb()
|
||||
if (!readBackAllowed() || !canTake(before, total, available)) {
|
||||
pagedIn(0, before, before, available, 0)
|
||||
return
|
||||
}
|
||||
try {
|
||||
control.writeText("0")
|
||||
} catch (_: IOException) {
|
||||
return
|
||||
}
|
||||
val start = nowMillis()
|
||||
for (record in targets) send(record, SIGURG)
|
||||
var swap = before
|
||||
var unchanged = 0
|
||||
try {
|
||||
while (!closing && nowMillis() - start < READ_BACK_TIMEOUT_MS) {
|
||||
sleep(READ_BACK_POLL_MS)
|
||||
val current = memoryKb(targets).second
|
||||
unchanged = if (current == swap) unchanged + 1 else 0
|
||||
swap = current
|
||||
if (swap == 0L || unchanged >= READ_BACK_STABLE_POLLS) break
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
pagedIn(targets.size, swap, before, available, nowMillis() - start)
|
||||
}
|
||||
|
||||
// Reading back moves the swap into resident memory, out of MemAvailable. On a device short on memory that
|
||||
// could push Android's low-memory killer onto DroidDeck itself, so the memory comes back only when
|
||||
// MemAvailable is at least twice the swap and keeps 1 GB or a tenth of MemTotal, whichever is more, after it.
|
||||
// Otherwise it stays in zram and faults back in as the game touches it, as before.
|
||||
private fun canTake(swapKb: Long, totalKb: Long, availableKb: Long): Boolean =
|
||||
availableKb >= swapKb * READ_BACK_AVAILABLE_FACTOR &&
|
||||
availableKb - swapKb >= maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
|
||||
|
||||
// MemTotal and MemAvailable, 0 when unreadable (which skips the read-back).
|
||||
private fun meminfoKb(): Pair<Long, Long> = try {
|
||||
val values = HashMap<String, Long>()
|
||||
File(procRoot, "meminfo").forEachLine { line ->
|
||||
val name = line.substringBefore(':')
|
||||
if (name == "MemTotal" || name == "MemAvailable") {
|
||||
line.substringAfter(':').trim().substringBefore(' ').toLongOrNull()?.let { values[name] = it }
|
||||
}
|
||||
}
|
||||
(values["MemTotal"] ?: 0L) to (values["MemAvailable"] ?: 0L)
|
||||
} catch (_: IOException) {
|
||||
0L to 0L
|
||||
}
|
||||
|
||||
private fun isGone(record: ProcessRecord): Boolean =
|
||||
try { readProcess(record.pid)?.started != record.started } catch (_: Exception) { false }
|
||||
|
||||
@@ -410,6 +483,12 @@ internal class SessionSuspendController(
|
||||
const val PAGE_OUT_POLL_MS = 100L
|
||||
const val PAGE_OUT_START_MS = 2_000L
|
||||
const val PAGE_OUT_TIMEOUT_MS = 12_000L
|
||||
const val READ_BACK_POLL_MS = 100L
|
||||
const val READ_BACK_STABLE_POLLS = 5
|
||||
const val READ_BACK_TIMEOUT_MS = 5_000L
|
||||
const val READ_BACK_HEADROOM_KB = 1_048_576L
|
||||
const val READ_BACK_AVAILABLE_FACTOR = 2L
|
||||
const val READ_BACK_TOTAL_SHARE = 10L
|
||||
const val RESTORE_CHECKS = 80
|
||||
const val FREEZE_TIMEOUT_MS = 8_000L
|
||||
const val FREEZE_MAX_PASSES = 256
|
||||
|
||||
@@ -26,7 +26,7 @@ object SettingsReset {
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen",
|
||||
"questDefaultsV1",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
|
||||
internal val SESSION_PREFIXES = listOf(
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** The In-game stats page's top strip, picked on the page (tap or the Layout row) and remembered. */
|
||||
enum class StatsStrip(val id: String) {
|
||||
PANEL("panel"), TILES("tiles"), RINGS("rings");
|
||||
|
||||
fun next(): StatsStrip = entries[(ordinal + 1) % entries.size]
|
||||
|
||||
companion object {
|
||||
fun from(id: String?): StatsStrip = entries.firstOrNull { it.id == id } ?: PANEL
|
||||
}
|
||||
}
|
||||
|
||||
/** Speeds on the racing dashes; telemetry arrives in km/h. */
|
||||
enum class SpeedUnit(val id: String, val label: String, val perKmh: Float) {
|
||||
AUTO("auto", "", 1f), KMH("kmh", "km/h", 1f), MPH("mph", "mph", 0.621371f);
|
||||
|
||||
/** Auto is mph where road speed limits are signed in mph, by the device's region, else km/h. */
|
||||
fun resolve(country: String): SpeedUnit = if (this != AUTO) this else if (country.uppercase() in MPH_REGIONS) MPH else KMH
|
||||
|
||||
fun next(): SpeedUnit = entries[(ordinal + 1) % entries.size]
|
||||
|
||||
companion object {
|
||||
/** The United States and its territories, the United Kingdom and its Crown Dependencies, Liberia, the Bahamas, Belize. */
|
||||
private val MPH_REGIONS = setOf("US", "PR", "GU", "VI", "AS", "MP", "GB", "IM", "JE", "GG", "LR", "BS", "BZ")
|
||||
|
||||
fun from(id: String?): SpeedUnit = entries.firstOrNull { it.id == id } ?: AUTO
|
||||
}
|
||||
}
|
||||
|
||||
/** The racing dash under the strip; Auto picks one by the game's data format. */
|
||||
enum class StatsDash(val id: String) {
|
||||
AUTO("auto"), SPEEDOMETER("speedometer"), CIRCUIT("circuit"), TRACE("trace"), DIALS("dials"), GLANCE("glance");
|
||||
|
||||
/** The dash to draw for data from [source] (Telemetry.source). */
|
||||
fun resolve(source: String): StatsDash = if (this != AUTO) this else when (source) {
|
||||
"Forza" -> CIRCUIT
|
||||
"OutGauge" -> DIALS
|
||||
else -> SPEEDOMETER
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val DRAWN = listOf(SPEEDOMETER, CIRCUIT, TRACE, DIALS, GLANCE)
|
||||
|
||||
fun from(id: String?): StatsDash = entries.firstOrNull { it.id == id } ?: AUTO
|
||||
|
||||
/** A tap on the dash moves on from the one on screen, so Auto never looks like a tap did nothing. */
|
||||
fun tapped(shown: StatsDash): StatsDash = DRAWN[(DRAWN.indexOf(shown) + 1).mod(DRAWN.size)]
|
||||
}
|
||||
}
|
||||
@@ -101,34 +101,6 @@ internal class SteamDownloadMonitor {
|
||||
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
|
||||
}
|
||||
|
||||
private fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
steamRoots += primary
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
return steamRoots.flatMap { root ->
|
||||
File(root, "steamapps").listFiles { file ->
|
||||
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
|
||||
}.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
private fun read(file: File): ManifestState {
|
||||
val text = runCatching { file.readText() }.getOrDefault("")
|
||||
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
@@ -137,9 +109,6 @@ internal class SteamDownloadMonitor {
|
||||
return ManifestState(downloaded, flags != 4L && (total <= 0L || downloaded < total))
|
||||
}
|
||||
|
||||
private fun value(text: String, key: String): String? =
|
||||
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
companion object {
|
||||
fun clientInstallPending(runtimeRoot: File): Boolean {
|
||||
val home = File(runtimeRoot, "root")
|
||||
@@ -149,12 +118,43 @@ internal class SteamDownloadMonitor {
|
||||
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
|
||||
}
|
||||
|
||||
internal fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
|
||||
val steamRoots = linkedSetOf<File>()
|
||||
for (home in STEAM_HOMES) {
|
||||
val primary = File(runtimeRoot, home)
|
||||
steamRoots += primary
|
||||
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
|
||||
runCatching {
|
||||
PATH.findAll(libraryFolders.readText()).forEach { match ->
|
||||
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
|
||||
}
|
||||
}
|
||||
}
|
||||
return steamRoots.flatMap { root ->
|
||||
File(root, "steamapps").listFiles { file ->
|
||||
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
|
||||
}.orEmpty().toList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
|
||||
val path = guest.trimEnd('/')
|
||||
for ((mount, host) in mounts) {
|
||||
if (path == mount) return host
|
||||
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
|
||||
}
|
||||
return File(runtimeRoot, path.removePrefix("/"))
|
||||
}
|
||||
|
||||
internal fun value(text: String, key: String): String? =
|
||||
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
|
||||
|
||||
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
|
||||
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
|
||||
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
|
||||
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
|
||||
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
|
||||
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
|
||||
internal val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
|
||||
internal val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
|
||||
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
|
||||
/** A Steam download or update the client is working on. [total] is 0 while Steam has not sized it yet. */
|
||||
data class SteamDownload(
|
||||
val appId: String,
|
||||
val name: String,
|
||||
val done: Long,
|
||||
val total: Long,
|
||||
val shader: Boolean = false,
|
||||
val paused: Boolean = false,
|
||||
)
|
||||
|
||||
/** Reads Steam's own appmanifests and content log, the same files [SteamDownloadMonitor] watches. */
|
||||
object SteamDownloads {
|
||||
fun read(runtimeRoot: File, mounts: Map<String, File> = emptyMap(), client: String? = null): List<SteamDownload> {
|
||||
val names = HashMap<String, String>()
|
||||
val apps = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { file ->
|
||||
val text = runCatching { file.readText() }.getOrNull() ?: return@mapNotNull null
|
||||
val id = SteamDownloadMonitor.value(text, "appid") ?: file.name.removePrefix("appmanifest_").removeSuffix(".acf")
|
||||
val name = SteamDownloadMonitor.value(text, "name") ?: id
|
||||
names[id] = name
|
||||
fromManifest(id, name, text)
|
||||
}.let(::onePerApp)
|
||||
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
|
||||
?: SteamDownloadMonitor.STEAM_HOMES
|
||||
val log = homes.map { File(runtimeRoot, "$it/logs/content_log.txt") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||
val shaders = log?.let { runningShaderUpdates(tail(it)) }.orEmpty()
|
||||
.map { SteamDownload(it, names[it] ?: it, 0L, 0L, shader = true) }
|
||||
return apps + shaders
|
||||
}
|
||||
|
||||
/** The arm64 and x86-64 Steam homes can both hold an unfinished manifest of one app; the page keys rows by app. */
|
||||
internal fun onePerApp(downloads: List<SteamDownload>): List<SteamDownload> =
|
||||
downloads.groupBy { it.appId }.values.map { same -> same.maxBy { it.done } }
|
||||
|
||||
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
|
||||
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
|
||||
if (flags == FULLY_INSTALLED) return null
|
||||
val done = SteamDownloadMonitor.value(text, "BytesDownloaded")?.toLongOrNull() ?: 0L
|
||||
val total = SteamDownloadMonitor.value(text, "BytesToDownload")?.toLongOrNull() ?: 0L
|
||||
if (total > 0L && done >= total) return null
|
||||
if ((flags and UPDATE_REQUIRED) == 0L && total <= 0L) return null
|
||||
return SteamDownload(id, name, done, total, paused = (flags and UPDATE_PAUSED) != 0L)
|
||||
}
|
||||
|
||||
/** App ids whose latest shader-cache line in the content log says the update is still running. */
|
||||
internal fun runningShaderUpdates(lines: Sequence<String>): List<String> {
|
||||
val state = LinkedHashMap<String, Boolean>()
|
||||
for (line in lines) {
|
||||
if ("Client version:" in line) state.clear()
|
||||
val match = SteamDownloadMonitor.CONTENT_UPDATE.find(line) ?: continue
|
||||
if (match.groupValues[2] != "Shader") continue
|
||||
val running = match.groupValues[3].let { "Running Update" in it && "Stopping" !in it }
|
||||
state[match.groupValues[1]] = running
|
||||
}
|
||||
return state.filterValues { it }.keys.toList()
|
||||
}
|
||||
|
||||
private fun tail(file: File): Sequence<String> = runCatching {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
val start = (raf.length() - TAIL_BYTES).coerceAtLeast(0L)
|
||||
raf.seek(start)
|
||||
val bytes = ByteArray((raf.length() - start).toInt())
|
||||
raf.readFully(bytes)
|
||||
String(bytes, Charsets.ISO_8859_1).lineSequence().drop(if (start > 0L) 1 else 0).toList().asSequence()
|
||||
}
|
||||
}.getOrDefault(emptySequence())
|
||||
|
||||
private const val FULLY_INSTALLED = 4L
|
||||
private const val UPDATE_REQUIRED = 2L
|
||||
private const val UPDATE_PAUSED = 512L
|
||||
private const val TAIL_BYTES = 256L * 1024L
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import java.io.File
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/** A cookie for one https host, in the form CookieManager.setCookie takes. */
|
||||
data class WebCookie(val host: String, val header: String)
|
||||
|
||||
/**
|
||||
* The web sign-in the Steam client in the session already has, so the bottom-screen chat opens signed in.
|
||||
* Steam's built-in browser keeps it in its Chromium cookie store under config/htmlcache. With no keyring
|
||||
* (SteamOS and DroidDeck) Chromium encrypts values as "v10": AES-128-CBC, key PBKDF2-SHA1("peanuts",
|
||||
* "saltysalt", 1 round), IV of 16 spaces. Values are never logged.
|
||||
*/
|
||||
object SteamWebLogin {
|
||||
val HOSTS = listOf("steamcommunity.com", "steam-chat.com")
|
||||
private const val COOKIES = "config/htmlcache/Default/Cookies"
|
||||
private const val V10 = "v10"
|
||||
// From cookie store version 24 Chromium puts the SHA-256 of the host before each value.
|
||||
private const val HOST_HASH_VERSION = 24
|
||||
private const val HOST_HASH_BYTES = 32
|
||||
|
||||
private val key: SecretKeySpec by lazy {
|
||||
val spec = PBEKeySpec("peanuts".toCharArray(), "saltysalt".toByteArray(), 1, 128)
|
||||
SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).encoded, "AES")
|
||||
}
|
||||
|
||||
internal fun decrypt(encrypted: ByteArray, hostHashed: Boolean): String? = runCatching {
|
||||
if (encrypted.size <= V10.length || String(encrypted, 0, V10.length, Charsets.US_ASCII) != V10) return null
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(ByteArray(16) { ' '.code.toByte() }))
|
||||
val plain = cipher.doFinal(encrypted, V10.length, encrypted.size - V10.length)
|
||||
val value = if (hostHashed && plain.size >= HOST_HASH_BYTES) plain.copyOfRange(HOST_HASH_BYTES, plain.size) else plain
|
||||
String(value, Charsets.UTF_8)
|
||||
}.getOrNull()
|
||||
|
||||
/** Steam's own pages send the sign-in with its "||" separator percent-encoded. */
|
||||
internal fun header(name: String, value: String, httpOnly: Boolean): String {
|
||||
val v = if (name == "steamLoginSecure") value.replace("||", "%7C%7C") else value
|
||||
return "$name=$v; Path=/; Secure" + if (httpOnly) "; HttpOnly" else ""
|
||||
}
|
||||
|
||||
/** Empty when the client has no web sign-in, for example before the first login. */
|
||||
fun read(runtimeRoot: File, client: String?, scratch: File): List<WebCookie> {
|
||||
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
|
||||
?: SteamDownloadMonitor.STEAM_HOMES
|
||||
val store = homes.map { File(runtimeRoot, "$it/$COOKIES") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
|
||||
?: return emptyList()
|
||||
// A copy, journal included: Steam keeps the store open and may be in the middle of a write.
|
||||
scratch.deleteRecursively()
|
||||
if (!scratch.mkdirs()) return emptyList()
|
||||
return try {
|
||||
val copy = File(scratch, "Cookies")
|
||||
store.copyTo(copy, overwrite = true)
|
||||
File(store.path + "-journal").takeIf { it.length() > 0L }?.copyTo(File(scratch, "Cookies-journal"), overwrite = true)
|
||||
SQLiteDatabase.openDatabase(copy.path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->
|
||||
val version = db.rawQuery("SELECT value FROM meta WHERE key = 'version'", null).use { if (it.moveToFirst()) it.getString(0).toIntOrNull() else null } ?: 0
|
||||
val marks = HOSTS.joinToString { "?" }
|
||||
db.rawQuery("SELECT host_key, name, value, encrypted_value, is_httponly FROM cookies WHERE host_key IN ($marks)", HOSTS.toTypedArray()).use { c ->
|
||||
val out = ArrayList<WebCookie>()
|
||||
while (c.moveToNext()) {
|
||||
val name = c.getString(1)
|
||||
val value = c.getString(2).takeUnless { it.isNullOrEmpty() }
|
||||
?: decrypt(c.getBlob(3) ?: continue, version >= HOST_HASH_VERSION) ?: continue
|
||||
out += WebCookie(c.getString(0), header(name, value, c.getInt(4) != 0))
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
} finally {
|
||||
scratch.deleteRecursively()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Codemasters games keep their UDP / motion output in My Games/<game>/hardwaresettings/hardware_settings_config.xml
|
||||
* inside the game's Proton prefix and read it when the game starts. Turning it on points that element at the
|
||||
* In-game stats listener; the file as it was is kept beside it, and its element is put back when turned off.
|
||||
*/
|
||||
object TelemetryOutput {
|
||||
data class Game(val name: String, val prefixId: String, val file: File, val on: Boolean)
|
||||
|
||||
data class MenuGame(val name: String, val setting: String, val port: Int)
|
||||
|
||||
/** Games whose output is only a setting in the game's own menus, by Steam app id. */
|
||||
val MENU_GAMES: Map<Int, MenuGame> = mapOf(
|
||||
1293830 to MenuGame("Forza Horizon 4", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
1551360 to MenuGame("Forza Horizon 5", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
2440510 to MenuGame("Forza Motorsport", "Data Out", GameTelemetry.FORZA_PORT),
|
||||
284160 to MenuGame("BeamNG.drive", "OutGauge", GameTelemetry.OUTGAUGE_PORT),
|
||||
)
|
||||
|
||||
internal const val ORIGINAL_SUFFIX = ".droiddeck-original"
|
||||
private const val MY_GAMES = "pfx/drive_c/users/steamuser/Documents/My Games"
|
||||
private const val CONFIG = "hardwaresettings/hardware_settings_config.xml"
|
||||
private const val ADDRESS = "127.0.0.1"
|
||||
private const val EXTRADATA = "3"
|
||||
private val TAGS = listOf("udp", "motion")
|
||||
// Byte-for-byte: every byte maps to one char and back, whatever the file's own encoding is.
|
||||
private val BYTES = Charsets.ISO_8859_1
|
||||
|
||||
fun scan(compatdata: List<File>): List<Game> = compatdata.asSequence()
|
||||
.flatMap { root -> root.listFiles { f -> f.isDirectory }.orEmpty().asSequence() }
|
||||
.flatMap { prefix -> File(prefix, MY_GAMES).listFiles { f -> f.isDirectory }.orEmpty().asSequence().map { prefix to it } }
|
||||
.mapNotNull { (prefix, game) ->
|
||||
val file = File(game, CONFIG)
|
||||
val text = runCatching { file.readText(BYTES) }.getOrNull() ?: return@mapNotNull null
|
||||
val element = element(text) ?: return@mapNotNull null
|
||||
Game(game.name, prefix.name, file, pointsHere(element.value))
|
||||
}
|
||||
.sortedBy { it.name.lowercase() }
|
||||
.toList()
|
||||
|
||||
/** Turns the game's output on or off; false when the file could not be read or written. */
|
||||
fun set(game: Game, on: Boolean): Boolean = runCatching {
|
||||
val file = game.file
|
||||
val original = File(file.path + ORIGINAL_SUFFIX)
|
||||
val xml = file.readText(BYTES)
|
||||
val next = if (on) {
|
||||
if (!original.exists()) file.copyTo(original)
|
||||
turnedOn(xml)
|
||||
} else {
|
||||
turnedOff(xml, original.takeIf { it.isFile }?.readText(BYTES))
|
||||
}
|
||||
checkNotNull(next)
|
||||
val tmp = File(file.path + ".droiddeck-tmp")
|
||||
tmp.writeText(next, BYTES)
|
||||
check(tmp.renameTo(file))
|
||||
if (!on) original.delete()
|
||||
true
|
||||
}.getOrDefault(false)
|
||||
|
||||
/** Automatic: turns the output on for every found game the user has not switched off and that is not running. */
|
||||
fun applyAutomatic(context: Context, running: String?) {
|
||||
if (!SessionPrefs.telemetryAuto(context)) return
|
||||
automaticTargets(scan(Library.compatdataDirs(context)), SessionPrefs.telemetryOff(context), running).forEach { set(it, true) }
|
||||
}
|
||||
|
||||
internal fun key(game: Game) = "${game.prefixId}/${game.name}"
|
||||
|
||||
internal fun automaticTargets(games: List<Game>, off: Set<String>, running: String?): List<Game> =
|
||||
games.filter { !it.on && key(it) !in off && !isRunning(it.prefixId, running) }
|
||||
|
||||
/** Games DroidDeck changed, which go back to their own setting when Automatic is switched off. */
|
||||
internal fun restoreTargets(games: List<Game>, running: String?): List<Game> =
|
||||
games.filter { File(it.file.path + ORIGINAL_SUFFIX).isFile && !isRunning(it.prefixId, running) }
|
||||
|
||||
/** Whether [running] (the focused Steam app id, or another key for non-Steam programs) may be the game in [prefixId]. */
|
||||
internal fun isRunning(prefixId: String, running: String?): Boolean {
|
||||
val id = running?.toLongOrNull() ?: return running != null
|
||||
return prefixId == id.toString() || prefixId == id.toInt().toString()
|
||||
}
|
||||
|
||||
internal fun element(xml: String): MatchResult? = TAGS.firstNotNullOfOrNull { tag -> tagRegex(tag).find(xml) }
|
||||
|
||||
internal fun pointsHere(element: String): Boolean =
|
||||
attr(element, "enabled") == "true" && attr(element, "ip") == ADDRESS &&
|
||||
attr(element, "port") == GameTelemetry.CODEMASTERS_PORT.toString() &&
|
||||
(attr(element, "extradata") ?: EXTRADATA) == EXTRADATA
|
||||
|
||||
internal fun turnedOn(xml: String): String? {
|
||||
val element = element(xml) ?: return null
|
||||
var on = withAttr(element.value, "enabled", "true")
|
||||
on = withAttr(on, "ip", ADDRESS)
|
||||
on = withAttr(on, "port", GameTelemetry.CODEMASTERS_PORT.toString())
|
||||
if (attr(on, "extradata") != null) on = withAttr(on, "extradata", EXTRADATA)
|
||||
return xml.replaceRange(element.range, on)
|
||||
}
|
||||
|
||||
internal fun turnedOff(xml: String, original: String?): String? {
|
||||
val element = element(xml) ?: return null
|
||||
val tag = element.value.drop(1).takeWhile { !it.isWhitespace() }
|
||||
val before = original?.let { tagRegex(tag).find(it)?.value }
|
||||
return xml.replaceRange(element.range, before ?: withAttr(element.value, "enabled", "false"))
|
||||
}
|
||||
|
||||
internal fun attr(element: String, name: String): String? =
|
||||
Regex("\\s$name=\"([^\"]*)\"").find(element)?.groupValues?.get(1)
|
||||
|
||||
internal fun withAttr(element: String, name: String, value: String): String {
|
||||
val existing = Regex("(\\s$name=\")[^\"]*\"")
|
||||
if (existing.containsMatchIn(element)) return existing.replace(element) { it.groupValues[1] + value + "\"" }
|
||||
val selfClosing = element.endsWith("/>")
|
||||
val body = element.dropLast(if (selfClosing) 2 else 1).trimEnd()
|
||||
return "$body $name=\"$value\"" + if (selfClosing) " />" else ">"
|
||||
}
|
||||
|
||||
private fun tagRegex(tag: String) = Regex("<$tag\\s[^>]*>")
|
||||
}
|
||||
Reference in new issue
Block a user