Merge remote-tracking branch 'origin/main' into review/malibridge-1950

This commit is contained in:
Kurt Himebauch committed 2026-11-02 18:14:00 -05:00
commit f05e0df39e
135 files changed
+5415 -979

No files matched your search

@@ -61,7 +61,9 @@ object BottomDesktop {
/** The proot to freeze with the session when it pauses. */
val suspendPid: Int get() = guestPid
private var guestGeneration = 0
private var outputSize = 0 to 0
var outputSize = 0 to 0
private set
private var attachedSurface: Surface? = null
private var cursorShown = false
/** The session generation whose launch the running compositor and guest belong to; -1 when none. */
private var owner = -1
@@ -97,16 +99,8 @@ object BottomDesktop {
fun available(): Boolean =
launch?.installed == true && SessionState.running && SessionState.mode != SessionService.MODE_DESKTOP
/**
* The desktop renders below the panel's resolution: about 720 pixels on the short side keeps
* Plasma's text big enough to touch and its software rendering cheap. A running desktop keeps its size.
*/
fun outputSizeFor(width: Int, height: Int): Pair<Int, Int> {
if ((state == State.STARTING || state == State.RUNNING) && outputSize.first > 0) return outputSize
if (width <= 0 || height <= 0) return 0 to 0
val scale = maxOf(1f, Math.round(minOf(width, height) / TARGET_SHORT_SIDE * 2f) / 2f)
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
}
fun outputSizeFor(width: Int, height: Int, fullResolution: Boolean = false): Pair<Int, Int> =
desktopOutputSize(width, height, fullResolution, TARGET_SHORT_SIDE)
fun addListener(listener: () -> Unit) { listeners.add(listener) }
@@ -148,6 +142,7 @@ object BottomDesktop {
appContext = context.applicationContext
owner = current.generation
outputSize = width to height
attachedSurface = surface
val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
val msg = Message.obtain(null, Comp.MSG_ATTACH).apply {
arg1 = owner
@@ -169,7 +164,19 @@ object BottomDesktop {
}
}
fun detach() {
fun resize(surface: Surface, width: Int, height: Int) {
if (surface !== attachedSurface || width <= 0 || height <= 0 || outputSize == (width to height)) return
outputSize = width to height
pendingAttach?.data?.apply {
putInt(Comp.KEY_WIDTH, width)
putInt(Comp.KEY_HEIGHT, height)
}
service?.let { send(it, Message.obtain(null, Comp.MSG_RESIZE, width, height)) }
}
fun detach(surface: Surface? = null) {
if (surface != null && attachedSurface != null && surface !== attachedSurface) return
attachedSurface = null
pendingAttach = null
service?.let { send(it, Message.obtain(null, Comp.MSG_DETACH)) }
}
@@ -351,3 +358,9 @@ object BottomDesktop {
}, "bottom-desktop-start").start()
}
}
internal fun desktopOutputSize(width: Int, height: Int, fullResolution: Boolean, targetShortSide: Float): Pair<Int, Int> {
if (width <= 0 || height <= 0) return 0 to 0
val scale = if (fullResolution) 1f else maxOf(1f, Math.round(minOf(width, height) / targetShortSide * 2f) / 2f)
return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
}
@@ -0,0 +1,64 @@
package com.droiddeck.launcher.session
import java.util.Locale
object DesktopLocale {
const val DEFAULT = "C.UTF-8"
private val regions = mapOf(
"en" to "US", "id" to "ID", "ms" to "MY", "cs" to "CZ", "da" to "DK", "de" to "DE",
"es" to "ES", "fr" to "FR", "it" to "IT", "hu" to "HU", "nl" to "NL", "nb" to "NO",
"pl" to "PL", "pt" to "PT", "ro" to "RO", "fi" to "FI", "sv" to "SE", "vi" to "VN",
"tr" to "TR", "el" to "GR", "bg" to "BG", "ru" to "RU", "uk" to "UA", "ar" to "EG",
"hi" to "IN", "th" to "TH", "ja" to "JP", "ko" to "KR", "zh" to "CN",
)
private val systemRegions = mapOf(
"en" to setOf("US", "GB", "AU", "CA", "IN", "NZ", "IE", "ZA", "SG"),
"fr" to setOf("FR", "CA", "BE", "CH", "LU"),
"de" to setOf("DE", "AT", "CH", "LU"),
"it" to setOf("IT", "CH"),
"nl" to setOf("NL", "BE"),
"pt" to setOf("PT", "BR"),
"sv" to setOf("SE", "FI"),
"ar" to setOf("EG", "SA", "AE", "MA", "DZ", "TN", "JO", "KW", "IQ"),
)
private val traditionalRegions = setOf("TW", "HK", "MO")
fun lang(locale: Locale): String {
val language = when (locale.language) {
"in" -> "id"
"no", "nn" -> "nb"
else -> locale.language
}
val region = when {
language == "es" && SteamLanguage.forLocale(locale) == "latam" ->
locale.country.takeIf { it.length == 2 && it != "US" } ?: "MX"
language == "zh" -> chineseRegion(locale)
locale.country in systemRegions[language].orEmpty() -> locale.country
else -> regions[language] ?: return DEFAULT
}
return "${language}_$region.UTF-8"
}
private fun chineseRegion(locale: Locale): String = when {
locale.script == "Hans" -> "CN"
locale.script == "Hant" -> if (locale.country == "HK") "HK" else "TW"
locale.country == "HK" -> "HK"
locale.country in traditionalRegions -> "TW"
else -> "CN"
}
fun language(locale: Locale): String? {
val lang = lang(locale)
if (lang == DEFAULT) return null
val full = lang.removeSuffix(".UTF-8")
val short = full.substringBefore('_')
return when {
short == "en" -> full
full == "zh_HK" -> "zh_HK:zh_TW:zh"
else -> "$full:$short"
}
}
}
@@ -31,6 +31,8 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
fun prepare(): Boolean {
sources = ""
KgslBusy.status = "not tried"
KgslClock.status = "not tried"
if (!File(KGSL).exists()) return false
val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }
// Where SELinux hides the kgsl nodes completely (exists() is false too), the layer and cycle-counter feeds stand in.
@@ -96,6 +98,7 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
if (load.failed) {
memstore?.close()
memstore = null
KgslBusy.status += ", but the stamps never moved"
Log.i(TAG, "hud: kgsl memstore timestamps never moved; GPU load from Vulkan timing")
} else if (load.working) {
Log.i(TAG, "hud: GPU load from the kgsl memstore (all GPU work)")
@@ -114,7 +117,9 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
}
private fun memstoreSource(): String = when {
memstoreLoad?.working == true -> "kgsl memstore ringbuffer timestamps (all GPU work)"
memstoreLoad?.working == true ->
if (memstore?.mode == KgslBusy.MODE_CONTEXTS) "kgsl memstore per-context timestamps (all GPU work)"
else "kgsl memstore ringbuffer timestamps (all GPU work)"
memstoreLoad?.failed == true -> LAYER_SOURCE
else -> "kgsl memstore once its timestamps move; until then $LAYER_SOURCE"
}
@@ -339,6 +344,12 @@ class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
/** Where the running session's GPU feeds come from, for the HUD diagnostics export. */
@Volatile var sources = ""
/** Why the no-root GPU readers work or not, for the HUD diagnostics export; empty where they were not needed. */
fun readerStatus(): String =
if (KgslBusy.status == "not tried" && KgslClock.status == "not tried") ""
else "kgsl memstore ${KgslBusy.status}; GPU cycle counter ${KgslClock.status}"
private const val STALE_MS = 30_000L
fun guestLoadDir(root: File) = File(root, GUEST_LOAD_DIR.removePrefix("/"))
@@ -10,6 +10,7 @@ object KgslBusy {
private const val TAG = "SessionService"
@JvmStatic private external fun nativeOpen(error: IntArray): Long
@JvmStatic private external fun nativeMode(handle: Long): Int
@JvmStatic private external fun nativeRun(handle: Long, on: Boolean)
@JvmStatic private external fun nativeRead(handle: Long, out: LongArray): Boolean
@JvmStatic private external fun nativeClose(handle: Long)
@@ -24,7 +25,10 @@ object KgslBusy {
if (handle != 0L) nativeRun(handle, on)
}
/** Running totals: busy samples, samples, samples in which a ringbuffer started new work. */
/** Which memstore entries are watched: [MODE_RINGBUFFER] or [MODE_CONTEXTS] (hardware-scheduled kernels). */
val mode: Int = if (handle != 0L) runCatching { nativeMode(handle) }.getOrDefault(0) else 0
/** Running totals: busy samples, samples, samples in which a ringbuffer or context started new work. */
@Synchronized fun counts(): LongArray? {
if (handle == 0L) return null
val out = LongArray(3)
@@ -37,14 +41,27 @@ object KgslBusy {
}
}
const val MODE_RINGBUFFER = 1
const val MODE_CONTEXTS = 2
/** What the last [open] found, for the HUD diagnostics export. */
@Volatile var status = "not tried"
fun open(): Reader? {
if (!loaded) return null
if (!loaded) {
status = "gpuclock library did not load"
return null
}
val error = IntArray(1)
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
if (handle == 0L) {
status = "open failed: ${KgslErrors.describe(error[0])}"
Log.i(TAG, "hud: no GPU load from the kgsl memstore (open error ${error[0]})")
return null
}
return Reader(handle)
val reader = Reader(handle)
status = if (reader.mode == MODE_CONTEXTS) "per-context stamps (hardware-scheduled kernel)" else "ringbuffer stamps"
Log.i(TAG, "hud: kgsl memstore reader uses $status")
return reader
}
}
@@ -20,7 +20,10 @@ object KgslClock {
class Sampler internal constructor(private var handle: Long) : AutoCloseable {
/** MHz, or null when this sample was refused or failed its checks. */
@Synchronized fun mhz(): Int? = if (handle == 0L) null else nativeSample(handle).takeIf { it > 0 }
@Synchronized fun mhz(): Int? = sample().takeIf { it > 0 }
/** MHz, or a negative native code: -errno from kgsl or [RANGE_CHECK_FAILED]. */
@Synchronized fun sample(): Int = if (handle == 0L) CLOSED else nativeSample(handle)
@Synchronized override fun close() {
if (handle != 0L) nativeClose(handle)
@@ -28,22 +31,41 @@ object KgslClock {
}
}
/** A sampler that already produced one good reading, or null (the reason goes to the log). */
/** -EBADF, what the native side also returns for a closed handle. */
private const val CLOSED = -9
/** The native sample code for a reading that failed its range checks (kgsl_clock.c sampler_mhz). */
const val RANGE_CHECK_FAILED = -1000
/** What the last [open] found, for the HUD diagnostics export. */
@Volatile var status = "not tried"
/** A sampler that already produced one good reading, or null (the reason goes to the log and [status]). */
fun open(): Sampler? {
if (!loaded) return null
if (!loaded) {
status = "gpuclock library did not load"
return null
}
val error = IntArray(1)
val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
if (handle == 0L) {
status = "open failed: ${KgslErrors.describe(error[0])}"
Log.i(TAG, "hud: no GPU clock from the cycle counter (open error ${error[0]})")
return null
}
val sampler = Sampler(handle)
val first = (0 until 3).firstNotNullOfOrNull { sampler.mhz() }
var code = 0
val first = (0 until 3).firstNotNullOfOrNull {
code = sampler.sample()
code.takeIf { it > 0 }
}
if (first == null) {
Log.i(TAG, "hud: GPU cycle counter gave no usable reading")
status = "no usable reading: ${KgslErrors.describe(code)}"
Log.i(TAG, "hud: GPU cycle counter gave no usable reading ($code)")
sampler.close()
return null
}
status = "working ($first MHz at start)"
Log.i(TAG, "hud: GPU clock from the cycle counter ($first MHz now)")
return sampler
}
@@ -0,0 +1,11 @@
package com.droiddeck.launcher.session
/** Readable text for the negative errno codes the gpuclock library returns. */
internal object KgslErrors {
fun describe(code: Int): String {
if (code == 0) return "no error code"
if (code == KgslClock.RANGE_CHECK_FAILED) return "sample out of range"
val name = runCatching { android.system.OsConstants.errnoName(-code) }.getOrNull()
return if (name != null) "$name ($code)" else "error $code"
}
}
@@ -86,12 +86,26 @@ object SessionPrefs {
prefs(context).edit().putBoolean("animations", on).apply()
}
fun dualScreenMode(context: Context): String =
prefs(context).getString("dualScreenMode", null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
private fun savedDualScreenMode(context: Context, key: String): String? =
prefs(context).getString(key, null)?.takeIf { it in com.droiddeck.launcher.input.DualScreen.modes }
private fun legacyDualScreenMode(context: Context): String =
if (!prefs(context).getBoolean("dualScreenLauncher", true)) com.droiddeck.launcher.input.DualScreen.MODE_OFF
else savedDualScreenMode(context, "dualScreenMode") ?: com.droiddeck.launcher.input.DualScreen.MODE_AUTO
fun dualScreenMode(context: Context): String = legacyDualScreenMode(context)
fun setDualScreenMode(context: Context, mode: String) {
prefs(context).edit().putString("dualScreenMode", mode).apply()
val sessions = dualScreenSessionMode(context)
prefs(context).edit().remove("dualScreenLauncher").putString("dualScreenMode", mode).putString("dualScreenSessionMode", sessions).apply()
}
fun dualScreenSessionMode(context: Context): String =
savedDualScreenMode(context, "dualScreenSessionMode") ?: legacyDualScreenMode(context)
fun setDualScreenSessionMode(context: Context, mode: String) {
val launcher = dualScreenMode(context)
prefs(context).edit().remove("dualScreenLauncher").putString("dualScreenMode", launcher).putString("dualScreenSessionMode", mode).apply()
}
fun secondScreenPanel(context: Context): String? = prefs(context).getString("secondScreenPanel", null)
@@ -162,12 +176,6 @@ object SessionPrefs {
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
}
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
fun setDualScreenLauncher(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("dualScreenLauncher", on).apply()
}
fun dualScreenSessionControls(context: Context): Boolean = prefs(context).getBoolean("dualScreenSessionControls", true)
fun setDualScreenSessionControls(context: Context, on: Boolean) {
@@ -856,6 +864,9 @@ object SessionPrefs {
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
fun battleNetFolder(context: Context, code: String): String? = prefs(context).getString("battleNetFolder:$code", null)
fun setBattleNetFolder(context: Context, code: String, path: String) { prefs(context).edit().putString("battleNetFolder:$code", path).apply() }
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
@@ -975,10 +986,17 @@ object SessionPrefs {
prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply()
}
fun runSteamAtStartup(context: Context): Boolean = prefs(context).getBoolean("runSteamAtStartup", false)
const val STARTUP_OFF = ""
const val STARTUP_STEAM = "steam"
const val STARTUP_DESKTOP = "desktop"
fun setRunSteamAtStartup(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("runSteamAtStartup", on).apply()
fun startupSession(context: Context): String {
val p = prefs(context)
return p.getString("startupSession", null) ?: if (p.getBoolean("runSteamAtStartup", false)) STARTUP_STEAM else STARTUP_OFF
}
fun setStartupSession(context: Context, id: String) {
prefs(context).edit().putString("startupSession", id).remove("runSteamAtStartup").apply()
}
fun addedGamesDirs(context: Context): List<String> {
@@ -70,6 +70,7 @@ class SessionService : Service() {
private val mainHandler = Handler(Looper.getMainLooper())
private var suspendController: SessionSuspendController? = null
private val steamDownloadMonitor = SteamDownloadMonitor()
private val downloadMonitorExecutor = java.util.concurrent.Executors.newSingleThreadExecutor { Thread(it, "steam-download-monitor").apply { isDaemon = true } }
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
@@ -346,7 +347,7 @@ class SessionService : Service() {
screenOn = readScreenOn()
manualPauseRequested = false
suspendDownloadNow = false
steamDownloadMonitor.reset()
runOnDownloadMonitor { steamDownloadMonitor.reset() }
downloadActive = false
clientInstallActive = false
steamSleepToken = null
@@ -649,6 +650,10 @@ class SessionService : Service() {
}
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) OfflineMode.apply(this, root)
if (SessionState.mode == MODE_DESKTOP) {
runCatching { com.droiddeck.launcher.runtime.DesktopLanguage.ensure(this, com.droiddeck.launcher.core.AppLanguage.effective(this)) }
.onFailure { Log.w(TAG, "desktop language pack: $it") }
}
val networkLink = LinuxNetworkLinkComponent(this, root)
networkLink.attach(this)
@@ -778,7 +783,13 @@ class SessionService : Service() {
guest.add("USER=root")
guest.add("PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games")
guest.add("TERM=xterm-256color")
guest.add("LANG=C.UTF-8")
if (SessionState.mode == MODE_DESKTOP) {
val appLocale = com.droiddeck.launcher.core.AppLanguage.effective(this)
guest.add("LANG=" + DesktopLocale.lang(appLocale))
DesktopLocale.language(appLocale)?.let { guest.add("LANGUAGE=$it") }
} else {
guest.add("LANG=C.UTF-8")
}
guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale(
com.droiddeck.launcher.core.AppLanguage.effective(this),
com.droiddeck.launcher.core.AppLanguage.system(this).country,
@@ -1991,6 +2002,9 @@ class SessionService : Service() {
(getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.unregisterDisplayListener(displayListener)
displayListenerRegistered = false
}
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
downloadMonitorExecutor.shutdown()
super.onDestroy()
}
@@ -2114,12 +2128,20 @@ class SessionService : Service() {
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
private fun runOnDownloadMonitor(task: () -> Unit) {
try {
downloadMonitorExecutor.execute(task)
} catch (e: java.util.concurrent.RejectedExecutionException) {
Log.d(TAG, "download monitor already shut down")
}
}
private fun updateDownloadMonitoring() {
if (!downloadWatchWanted()) {
val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
steamDownloadMonitor.reset()
runOnDownloadMonitor { steamDownloadMonitor.reset() }
downloadActive = false
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
clientInstallActive = false
@@ -2141,18 +2163,30 @@ class SessionService : Service() {
val wasInstalling = clientInstallActive
clientInstallActive = !SessionState.firstFrameSeen &&
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
root,
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
client = SessionState.steamClientArch,
mounts = steamLibraryMounts,
)
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
val receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid())
val client = SessionState.steamClientArch
val mounts = steamLibraryMounts
val self = this
val finish = { monitored: Boolean ->
if (downloadMonitorTask === self) {
downloadActive = clientInstallActive || monitored
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(self, DOWNLOAD_POLL_MS)
}
}
if (clientInstallActive || !steamDownloadsInBackground) {
finish(false)
return
}
runOnDownloadMonitor {
val monitored = runCatching { steamDownloadMonitor.poll(root, receivedBytes = receivedBytes, client = client, mounts = mounts) }
.getOrDefault(false)
mainHandler.post { finish(monitored) }
}
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
}
}
downloadMonitorTask = poll
@@ -93,6 +93,7 @@ object SessionState {
@Volatile var secondScreenDisplay = -1
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
@Volatile var gameOnBottom = false
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
@@ -11,8 +11,8 @@ object SettingsReset {
private const val TAG = "SettingsReset"
internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
"dualScreenMode", "dualScreenLauncher", "dualScreenSessionControls",
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls",
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.session
import android.content.Context
import android.os.storage.StorageManager
import com.droiddeck.launcher.R
import com.droiddeck.launcher.files.StorageRoots
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
import org.json.JSONArray
@@ -49,15 +50,12 @@ object SteamLibraries {
class Refused(val reason: String) : AddResult()
}
fun add(context: Context, path: String, label: String = defaultLabel(context, File(path))): AddResult {
fun add(context: Context, picked: String, label: String? = null): AddResult {
val entries = list(context)
if (entries.size >= MAX) return AddResult.Refused(context.getString(R.string.libraries_full, MAX))
val path = innerLibrary(File(picked))?.path ?: picked
val host = canonical(File(path))
val taken = entries.map { canonical(it.host) } + listOfNotNull(
GameStorage.effective(context)?.let { canonical(File(it.path)) },
canonical(SessionPrefs.steamRoot(context, "arm64")),
)
if (taken.any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
if (taken(context, entries).any { overlaps(it, host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
// Adding a Games folder itself is fine; a child of one would make it overlap and hide the rest of that folder.
if (AddedGames.roots(context).any { host.startsWith(canonical(it.host) + "/") }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
GameStorage.prepare(context, path)?.let { return AddResult.Refused(it) }
@@ -67,13 +65,70 @@ object SteamLibraries {
if (current.any { overlaps(canonical(it.host), host) }) return AddResult.Refused(context.getString(R.string.libraries_overlap))
// A removed library's mount stays registered with Steam until its next session, so ids are never reused.
val next = maxOf(SessionPrefs.steamLibraryNextId(context), (current.maxOfOrNull { it.id.toInt() } ?: 0) + 1)
val entry = Entry(next.toString(), path, clean(label).ifEmpty { File(path).name })
val entry = Entry(next.toString(), path, clean(label ?: defaultLabel(context, File(path))).ifEmpty { File(path).name })
save(context, current + entry)
SessionPrefs.setSteamLibraryNextId(context, next + 1)
return AddResult.Added(entry)
}
}
private fun taken(context: Context, entries: List<Entry>): List<String> = entries.map { canonical(it.host) } + listOfNotNull(
GameStorage.effective(context)?.let { canonical(File(it.path)) },
canonical(SessionPrefs.steamRoot(context, "arm64")),
)
class Found(val path: String, val shown: String, val label: String, val games: Int)
/** Reads storage; call off the main thread. */
fun found(context: Context): List<Found> {
val entries = list(context)
val taken = taken(context, entries) + AddedGames.roots(context).map { canonical(it.host) }
val hits = ArrayList<Pair<File, Int>>()
for (root in StorageRoots.list(context)) {
if (!root.readable) continue
for (dir in candidates(rawView(root.dir), SCAN_DEPTH)) {
val games = gameCount(dir)
if (games > 0 && File(dir, "steamapps").canWrite() && taken.none { overlaps(it, canonical(dir)) }) hits += dir to games
}
}
val picked = ArrayList<Pair<File, Int>>()
for (hit in hits.sortedByDescending { it.second }) {
if (picked.none { overlaps(canonical(it.first), canonical(hit.first)) }) picked += hit
}
return picked.map { (dir, games) ->
val shown = File(storagePath(dir.path))
Found(dir.path, shown.path, defaultLabel(context, shown), games)
}
}
/** The FUSE view under /storage hides files other apps wrote unless DroidDeck has all files access; the raw card mount does not. */
private fun rawView(dir: File): File {
if (!dir.path.startsWith("/storage/") || dir.path.startsWith("/storage/emulated")) return dir
val raw = File("/mnt/media_rw/" + dir.path.removePrefix("/storage/"))
return if (raw.canRead() && raw.list() != null) raw else dir
}
internal fun innerLibrary(picked: File): File? {
if (gameCount(picked) > 0) return null
return candidates(picked, 1).filter { it != picked && gameCount(it) > 0 }.singleOrNull()
}
internal fun candidates(root: File, depth: Int): List<File> {
val out = arrayListOf(root)
var level = listOf(root)
repeat(depth) {
level = level.flatMap { dir ->
dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") && f.name != "steamapps" && !(dir == root && f.name == "Android") }
.orEmpty().sortedBy { it.name }
}.take(SCAN_LIMIT - out.size)
out += level
}
return out
}
internal fun gameCount(library: File): Int =
File(library, "steamapps").list()?.count { it.startsWith("appmanifest_") && it.endsWith(".acf") } ?: 0
fun rename(context: Context, id: String, label: String) {
val name = clean(label).takeIf { it.isNotEmpty() } ?: return
synchronized(lock) { save(context, list(context).map { if (it.id == id) Entry(it.id, it.path, name) else it }) }
@@ -84,17 +139,27 @@ object SteamLibraries {
synchronized(lock) { save(context, list(context).filterNot { it.id == id }) }
}
fun defaultLabel(context: Context, folder: File): String {
fun defaultLabel(context: Context, picked: File): String {
val folder = File(storagePath(picked.path))
val volume = try {
context.getSystemService(StorageManager::class.java)?.getStorageVolume(folder)?.getDescription(context)
} catch (e: Exception) {
null
}
val name = folder.name.ifEmpty { context.getString(R.string.gstore_folder) }
val parent = folder.parentFile
val named = if (folder.name.equals("Steam", true) && parent != null && !volumeRoot(parent)) parent else folder
val name = named.name.ifEmpty { context.getString(R.string.gstore_folder) }
return clean(if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume))
}
private fun volumeRoot(dir: File): Boolean = dir.parent in setOf("/storage", "/mnt/media_rw", "/storage/emulated") || dir.parent == null
internal fun overlaps(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("$a/")
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
private fun storagePath(path: String): String = if (path.startsWith("/mnt/media_rw/")) "/storage/" + path.removePrefix("/mnt/media_rw/") else path
private fun canonical(file: File): String = storagePath(runCatching { file.canonicalPath }.getOrDefault(file.absolutePath))
private const val SCAN_DEPTH = 2
private const val SCAN_LIMIT = 4000
}