feat(stores): Steam store that downloads outside the Steam client

Steam joins the Stores list. Games download with the Rust engine into the
libraries the active Steam client offers and are registered so the client
sees them installed. Downloads show in the store downloads list with cancel;
uninstall uses the usual confirmation. The Steam session cannot start while
a Steam store download runs, and installs refuse while the session runs.
With no saved Steam sign-in the store only offers to open Steam.
This commit is contained in:
The412Banner committed 2026-11-07 06:11:08 +00:00
1 parent 2b87acff4b
commit 15b9700f03
56 files changed
+1365 -28

No files matched your search

@@ -61,6 +61,7 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.sync.Syncthing.init(this)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.steam.SteamBackend)
}
private fun prefetchAddonPacks() {
@@ -2956,6 +2956,10 @@ class FrontEndActivity : ComponentActivity() {
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
return false
}
if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
return false
}
refreshPhantomStatus()
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
showPhantomGate = true
@@ -629,6 +629,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
finish()
return
}
if (savedInstanceState == null && !SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
runtimeRemovalBlocked = true
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
finish()
return
}
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
@@ -87,7 +87,7 @@ object CloudSaves {
val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> ""
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.STEAM -> ""
} ?: return null
p.edit()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
@@ -148,7 +148,7 @@ object CloudSaves {
val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.STEAM -> null
}
return dir to (if (dir == null) "unresolved" else "ok")
}
@@ -173,7 +173,7 @@ object CloudSaves {
val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
}
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET -> null
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.STEAM -> null
}
private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -13,7 +13,7 @@ internal object LoginFlows {
Store.EPIC -> epicFlow()
Store.AMAZON -> amazonFlow()
Store.GAMEJOLT -> gameJoltFlow(browserUserAgent)
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
Store.ITCH, Store.XBOX, Store.BATTLENET, Store.STEAM -> null
}
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
@@ -7,7 +7,8 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
XBOX("xbox", "Xbox", "Xbox"),
ITCH("itch", "Itch.io", "Itch.io"),
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
BATTLENET("battlenet", "Battle.net", "Battle.net");
BATTLENET("battlenet", "Battle.net", "Battle.net"),
STEAM("steamstore", "Steam", "Steam");
val folder: String get() = if (this == ITCH) "itch" else shortLabel
@@ -90,7 +90,7 @@ object StoreAccounts {
fun signedInAs(context: Context, store: Store): String? {
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() }
if (store == Store.BATTLENET) return json.optString("display_name").takeIf { it.isNotBlank() }
if (store == Store.BATTLENET || store == Store.STEAM) return json.optString("display_name").takeIf { it.isNotBlank() }
if (json.optString("access_token", "").isEmpty()) return null
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
}
@@ -226,7 +226,7 @@ object StoreInstallRoot {
fun storeDir(root: File, store: Store): File = File(root, store.folder)
fun gameFolders(context: Context): List<File> = roots(context).flatMap { root ->
Store.entries.flatMap { store ->
Store.entries.filter { it != Store.STEAM }.flatMap { store ->
storeDir(root, store).listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()
}
}
@@ -246,7 +246,7 @@ object StoreInstallRoot {
fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true
fun unfinished(context: Context): List<Unfinished> = roots(context).flatMap { root ->
Store.entries.filter { it != Store.BATTLENET }.flatMap { store ->
Store.entries.filter { it != Store.BATTLENET && it != Store.STEAM }.flatMap { store ->
storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder ->
val sidecar = StoreGameSidecar.read(folder)
when {
@@ -55,7 +55,7 @@ object StoreSizes {
Store.EPIC -> EpicPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
Store.ITCH, Store.GAMEJOLT -> {}
Store.GOG, Store.XBOX, Store.BATTLENET -> {}
Store.GOG, Store.XBOX, Store.BATTLENET, Store.STEAM -> {}
}
}
}, pool).exceptionally { error ->
@@ -114,5 +114,6 @@ object StoreSizes {
Store.GOG, Store.XBOX, Store.BATTLENET -> 0L
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
Store.STEAM -> com.droiddeck.launcher.stores.steam.SteamStore.plannedBytes(context, item)
} }
}
@@ -85,6 +85,8 @@ object StoresState {
do {
seen = refreshRequests.get()
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
runCatching { com.droiddeck.launcher.stores.steam.SteamStore.syncAccount(app) }
runCatching { com.droiddeck.launcher.stores.steam.SteamStore.scanInstalled(app) }
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
@@ -238,6 +240,7 @@ object StoresState {
fun requestInstall(context: Context, item: CatalogItem) {
askForNotifications(context)
if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.requestInstall(context, item); return }
if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return }
if (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return }
if (isUnfinished(item)) { install(context, item); return }
@@ -256,6 +259,7 @@ object StoresState {
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
val app = context.applicationContext
if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.restore(app, item); return }
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
backends[item.store]?.install(app, item, targetRoot)
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.stores.steam
import android.content.Context
import android.os.Environment
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SteamLibraries
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/** The active Steam client's folders as the app sees them. Reads storage; call off the main thread. */
internal object SteamClient {
const val X86_64 = "x86_64"
class Target(
val library: SteamLibraryFolders.Library, val engineHost: File, val label: String,
val freeBytes: Long, val removable: Boolean, val folder: Boolean,
)
fun activeArch(context: Context): String = SessionPrefs.activeSteamClientArch(context)
private fun guestHome(arch: String) = if (arch == X86_64) "/root/.droiddeck-x64" else "/root"
fun guestRoot(arch: String) = "${guestHome(arch)}/.local/share/Steam"
private fun aliases(arch: String) = listOf(guestRoot(arch), "${guestHome(arch)}/.steam/steam", "${guestHome(arch)}/.steam/root")
fun root(context: Context, arch: String = activeArch(context)): File = SessionPrefs.steamRoot(context, arch)
fun registry(context: Context, arch: String = activeArch(context)): File =
File(LinuxRuntime.rootDir(context), guestHome(arch).removePrefix("/") + "/.steam/registry.vdf")
fun loginUsers(context: Context, arch: String = activeArch(context)): File = File(root(context, arch), "config/loginusers.vdf")
fun language(context: Context): String =
runCatching { SteamLibraryFolders.language(registry(context).readText()) }.getOrNull() ?: "english"
fun mounts(context: Context): List<SteamLibraryFolders.Mount> {
val out = ArrayList<SteamLibraryFolders.Mount>()
GameStorage.effective(context)?.let { card -> SecondaryLibrary.CARD_GUESTS.forEach { out += SteamLibraryFolders.Mount(it, File(card.path)) } }
SteamLibraries.list(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) }
AddedGames.roots(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) }
StoreInstallRoot.externalRoots(context).forEach { (host, guest) -> out += SteamLibraryFolders.Mount(guest, host) }
out += SteamLibraryFolders.Mount("/root/Storage", Environment.getExternalStorageDirectory())
return out
}
/** Every library the client lists in libraryfolders.vdf that maps to a folder of the app. */
fun libraries(context: Context, arch: String = activeArch(context)): List<SteamLibraryFolders.Library> {
val root = root(context, arch)
val text = runCatching { File(root, "steamapps/libraryfolders.vdf").readText() }.getOrNull().orEmpty()
return SteamLibraryFolders.resolve(
SteamLibraryFolders.parse(text), guestRoot(arch), aliases(arch), root, mounts(context), LinuxRuntime.rootDir(context),
)
}
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
/** The card and added libraries are written through the raw card view when Android allows it, as the session binds them. */
private fun engineView(context: Context): (File) -> File {
val bases = listOfNotNull(GameStorage.effective(context)?.let { File(it.path) }) + SteamLibraries.list(context).map { it.host }
val seen = HashMap<String, File>()
return { host ->
val path = host.absolutePath
val base = bases.filter { path == it.absolutePath || path.startsWith(it.absolutePath + "/") }.maxByOrNull { it.absolutePath.length }
if (base == null) host else {
val content = seen.getOrPut(base.absolutePath) { SecondaryLibrary.contentPath(base) }
if (content.absolutePath == base.absolutePath) host
else path.removePrefix(base.absolutePath).trimStart('/').let { if (it.isEmpty()) content else File(content, it) }
}
}
}
class EngineLibraries(val libraries: List<Pair<SteamLibraryFolders.Library, File>>) {
val json: String get() = JSONArray().apply {
for ((library, host) in libraries) put(JSONObject().put("host", host.absolutePath).put("guest", library.guest))
}.toString()
fun hostOf(library: SteamLibraryFolders.Library): File =
libraries.firstOrNull { it.first.guest == library.guest }?.second ?: library.host
}
fun engineLibraries(context: Context): EngineLibraries {
val view = engineView(context)
return EngineLibraries(libraries(context).filter { it.host.isDirectory }.map { it to view(it.host) })
}
fun targets(context: Context): List<Target> {
val arch = activeArch(context)
val card = GameStorage.effective(context)?.let { canonical(File(it.path)) }
val known = Library.steamLibraries(context, arch).associate { (host, label) ->
canonical(host) to if (label == "internal") context.getString(R.string.games_internal) else label
}
val engine = engineLibraries(context)
return engine.libraries.mapNotNull { (library, host) ->
if (!library.host.isDirectory || !library.host.canWrite()) return@mapNotNull null
val path = canonical(library.host)
val onCard = card != null && (path == card || path.startsWith("$card/"))
val label = library.label.ifBlank {
if (library.main) context.getString(R.string.stores_target_internal) else known[path] ?: File(library.guest).name
}
Target(library, host, label, StoreInstallRoot.availableBytes(host), removable = onCard, folder = !library.main && !onCard)
}
}
/** True while a session that can run the Steam client is up or starting. */
fun clientMayRun(): Boolean {
val up = SessionState.running || (SessionState.phase != SessionPhase.IDLE && SessionState.phase != SessionPhase.FAILED)
return up && SessionState.mode != SessionService.MODE_RUN
}
}
@@ -0,0 +1,91 @@
package com.droiddeck.launcher.stores.steam
import android.content.Context
import android.os.SystemClock
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoresNative
import org.json.JSONArray
import org.json.JSONObject
/** Blocking calls into the Rust engine; they reach the network, so never on the main thread. */
internal object SteamEngine {
private const val TAG = "SteamEngine"
const val MISSING = "engine_missing"
const val MISSING_TEXT = "Steam: the store engine is not available"
private const val RETRY_MS = 60_000L
private val lock = Any()
@Volatile private var signedIn = false
private var failed: JSONObject? = null
private var failedAt = 0L
fun failure(error: String): JSONObject = JSONObject().put("ok", false).put("error", error)
private fun call(op: String, block: () -> String): JSONObject {
if (!StoresNative.ensureLoaded()) return failure(MISSING)
val text = try {
block()
} catch (e: UnsatisfiedLinkError) {
Log.w(TAG, "$op: not in this engine build")
return failure(MISSING)
} catch (t: Throwable) {
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
return failure(t.javaClass.simpleName)
}
return runCatching { JSONObject(text) }.getOrElse { failure("$op: unreadable answer") }
}
fun signIn(context: Context): JSONObject {
synchronized(lock) {
if (signedIn) return JSONObject().put("ok", true)
failed?.takeIf { SystemClock.elapsedRealtime() - failedAt < RETRY_MS }?.let { return it }
val roots = JSONArray()
.put(SessionPrefs.steamRoot(context, "arm64").absolutePath)
.put(SessionPrefs.steamRoot(context, SteamClient.X86_64).absolutePath)
val registry = SteamClient.registry(context).absolutePath
val answer = call("signIn") { SteamNative.nativeSignIn(roots.toString(), registry, "") }
signedIn = answer.optBoolean("ok")
failed = if (signedIn) null else answer
failedAt = SystemClock.elapsedRealtime()
if (!signedIn) Log.w(TAG, "sign-in: ${answer.optString("error")}")
return answer
}
}
fun forget() {
synchronized(lock) {
failed = null
if (!signedIn) return
signedIn = false
try {
SteamNative.nativeSignOut()
} catch (t: Throwable) {
Log.w(TAG, "sign-out: ${t.javaClass.simpleName}")
}
}
}
private fun signedCall(context: Context, op: String, block: () -> String): JSONObject {
synchronized(lock) {
val signIn = signIn(context)
if (!signIn.optBoolean("ok")) return signIn
val answer = call(op, block)
val error = answer.optString("error").lowercase()
if (!answer.optBoolean("ok") && listOf("logon", "sign", "session", "connect").any { it in error }) signedIn = false
return answer
}
}
fun library(context: Context): JSONObject = signedCall(context, "library") { SteamNative.nativeLibrary() }
fun plan(context: Context, appId: Int, language: String): JSONObject =
signedCall(context, "plan") { SteamNative.nativePlan(appId, language) }
fun uninstall(appId: Int, steamRoot: String, host: String, guest: String, roots: String): JSONObject {
synchronized(lock) {
return call("uninstall") { SteamNative.nativeUninstall(appId, steamRoot, host, guest, roots) }
}
}
}
@@ -0,0 +1,145 @@
package com.droiddeck.launcher.stores.steam
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.download.StoreDownloadTier
import org.json.JSONObject
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/** Called by the engine on its own threads. */
interface SteamInstallListener {
fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?)
fun onComplete(ok: Boolean, result: String?)
}
internal class SteamInstallJob(
private val app: Context,
private val appId: Int,
private val libraryGuest: String,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val started = AtomicBoolean(false)
@Volatile private var discard = false
@Volatile private var installDir: String? = null
@Volatile private var libraryHost: File? = null
override fun run(handle: DownloadQueue.JobHandle): String? {
started.set(true)
try {
return install(handle)
} finally {
if (discard) SteamStore.discardPartial(app, appId, libraryGuest, libraryHost, installDir)
}
}
private fun install(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST)
if (SteamClient.clientMayRun()) throw IllegalStateException(app.getString(R.string.steam_store_close_steam))
val engine = SteamClient.engineLibraries(app)
val target = engine.libraries.firstOrNull { it.first.guest == libraryGuest }
?: throw IllegalStateException(app.getString(R.string.game_sync_err_steam_library))
libraryHost = target.second
val signIn = SteamEngine.signIn(app)
if (!signIn.optBoolean("ok")) {
SteamStore.signInFailed(app, signIn.optString("error"))
throw IllegalStateException(SteamStore.errorText(app, signIn))
}
val language = SteamClient.language(app)
val (plan, planned) = SteamStore.plan(app, appId, language)
if (plan == null) throw IllegalStateException(SteamStore.errorText(app, planned))
installDir = plan.installDir
if (plan.installBytes > 0) handle.diskSize(plan.installBytes)
if (cancelled.get()) return null
val tier = StoreDownloadTier.current(app)
val journal = File(app.filesDir, "${SteamStore.JOURNAL}/$appId").apply { mkdirs() }
handle.log("steam: $appId tier=${tier.id} window=${tier.networkWindow} process_workers=${tier.processWorkers}")
val done = CountDownLatch(1)
val succeeded = AtomicBoolean(false)
val answer = AtomicReference("")
val listener = object : SteamInstallListener {
private var stage: DownloadStage? = null
private var shown = -1L
override fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?) {
synchronized(this) {
val now = SteamLibraryFolders.stageOf(phase.orEmpty())
if (now != stage) {
stage = now
shown = -1L
}
if (doneBytes < shown) return
shown = doneBytes
if (now == DownloadStage.DOWNLOAD) handle.progress(doneBytes, totalBytes)
else {
handle.stage(now)
if (totalBytes > 0) handle.stageProgress(doneBytes, totalBytes, bytes = true)
}
}
}
override fun onComplete(ok: Boolean, result: String?) {
answer.set(result.orEmpty())
succeeded.set(ok)
done.countDown()
}
}
val native = try {
SteamNative.nativeStart(
appId, language, SteamClient.root(app).absolutePath, target.second.absolutePath, libraryGuest, engine.json,
journal.absolutePath, "", tier.networkWindow.coerceIn(1, 128), tier.processWorkers, listener,
)
} catch (e: UnsatisfiedLinkError) {
throw IllegalStateException(SteamEngine.MISSING_TEXT)
}
if (native == 0L && done.count > 0L) throw IllegalStateException(SteamStore.errorText(app, parse(answer.get())))
if (native != 0L) {
try {
var forwarded = false
while (true) {
val finished = try {
done.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)
} catch (e: InterruptedException) {
cancelled.set(true)
false
}
if (finished) break
if (!forwarded && cancelled.get()) {
runCatching { SteamNative.nativeCancel(native) }
forwarded = true
}
}
} finally {
runCatching { SteamNative.nativeRelease(native) }
}
}
val result = parse(answer.get())
if (succeeded.get() && result.optBoolean("ok", true)) {
journal.deleteRecursively()
SteamStore.scanInstalled(app)
return File(target.first.host, "steamapps/common/${plan.installDir}").path
}
if (cancelled.get() || result.optString("error") == "cancelled") return null
throw IllegalStateException(SteamStore.errorText(app, result))
}
private fun parse(text: String): JSONObject =
runCatching { JSONObject(text) }.getOrElse { SteamEngine.failure(text.ifBlank { "install failed" }) }
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (!deleteFiles) return
discard = true
if (!started.get()) SteamStore.discardPartial(app, appId, libraryGuest, null, null)
}
private companion object {
const val CANCEL_POLL_MS = 250L
}
}
@@ -0,0 +1,150 @@
package com.droiddeck.launcher.stores.steam
import com.droiddeck.launcher.storage.SteamStorage
import com.droiddeck.launcher.stores.download.DownloadStage
import java.io.File
internal object SteamLibraryFolders {
data class Folder(val path: String, val label: String)
class Mount(guest: String, val host: File) {
val guest: String = guest.trimEnd('/')
}
data class Library(val guest: String, val host: File, val label: String, val main: Boolean)
data class Installed(val appId: Int, val name: String, val installDir: String?, val library: Library, val sizeOnDisk: Long)
/** Guest folders that exist only as binds of the session; without their bind they are empty mount points in the rootfs. */
val BIND_ONLY = listOf("/mnt", "/media", "/storage", "/sdcard", "/root/Storage", "/root/ROMs", "/root/Games")
private val TOKEN = Regex("\"((?:\\\\.|[^\"\\\\])*)\"|[{}]|//[^\n]*")
private val ACF = Regex("appmanifest_\\d+\\.acf")
private val SIZE_ON_DISK = Regex("^\\s*\"SizeOnDisk\"\\s*\"(\\d+)\"", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
private fun walk(text: String, pair: (blocks: List<String>, key: String, value: String) -> Unit, closed: (blocks: List<String>) -> Unit = {}) {
val blocks = ArrayList<String>()
var key: String? = null
for (m in TOKEN.findAll(text)) {
val token = m.value
when {
token.startsWith("//") -> {}
token == "{" -> { blocks.add(key.orEmpty()); key = null }
token == "}" -> { if (blocks.isNotEmpty()) { closed(blocks); blocks.removeAt(blocks.lastIndex) }; key = null }
key == null -> key = unescape(m.groupValues[1])
else -> { pair(blocks, key, unescape(m.groupValues[1])); key = null }
}
}
}
private fun unescape(s: String): String {
if ('\\' !in s) return s
val out = StringBuilder(s.length)
var i = 0
while (i < s.length) {
if (s[i] == '\\' && i + 1 < s.length) { out.append(s[i + 1]); i += 2 } else { out.append(s[i]); i++ }
}
return out.toString()
}
private fun inRoot(blocks: List<String>) = blocks.firstOrNull()?.equals("libraryfolders", ignoreCase = true) == true
fun parse(text: String): List<Folder> {
val out = ArrayList<Folder>()
var path: String? = null
var label = ""
walk(text, pair = { blocks, key, value ->
if (!inRoot(blocks)) return@walk
if (blocks.size == 1 && key.isNotEmpty() && key.all(Char::isDigit)) out += Folder(value, "")
if (blocks.size == 2) when (key.lowercase()) {
"path" -> path = value
"label" -> label = value
}
}, closed = { blocks ->
if (blocks.size == 2 && inRoot(blocks)) path?.let { out += Folder(it, label) }
if (blocks.size == 2) { path = null; label = "" }
})
return out
}
fun normalize(path: String): String? {
val p = path.trim().replace(Regex("/+"), "/").trimEnd('/')
if (!p.startsWith("/") || p.split('/').any { it == ".." || it == "." }) return null
return p
}
private fun under(path: String, prefix: String) = path == prefix || path.startsWith("$prefix/")
fun hostFor(guest: String, mounts: List<Mount>, rootfs: File): File? {
val path = normalize(guest) ?: return null
mounts.filter { it.guest.isNotEmpty() && under(path, it.guest) }.maxByOrNull { it.guest.length }?.let { m ->
val rest = path.removePrefix(m.guest).trimStart('/')
return if (rest.isEmpty()) m.host else File(m.host, rest)
}
if (BIND_ONLY.any { under(path, it) } || !under(path, "/root")) return null
return File(rootfs, path.removePrefix("/"))
}
fun resolve(folders: List<Folder>, mainGuest: String, aliases: Collection<String>, mainHost: File, mounts: List<Mount>, rootfs: File): List<Library> {
val mains = (aliases + mainGuest).mapNotNull(::normalize).toSet()
val listed = if (folders.any { normalize(it.path) in mains }) folders else listOf(Folder(mainGuest, "")) + folders
val out = ArrayList<Library>()
for (f in listed) {
val guest = normalize(f.path) ?: continue
val main = guest in mains
val host = if (main) mainHost else hostFor(guest, mounts, rootfs) ?: continue
if (out.any { it.host.path == host.path || (main && it.main) }) continue
out += Library(guest, host, f.label.trim(), main)
}
return out.sortedByDescending { it.main }
}
fun installed(libraries: List<Library>, read: (File) -> String? = { runCatching { it.readText() }.getOrNull() }): Map<Int, Installed> {
val out = LinkedHashMap<Int, Installed>()
for (library in libraries) {
val apps = File(library.host, "steamapps")
val names = apps.list() ?: continue
for (name in names.sorted()) {
if (!ACF.matches(name)) continue
val file = File(apps, name)
val text = read(file) ?: continue
val manifest = SteamStorage.parseManifest(file, text) ?: continue
if (!manifest.installed || SteamStorage.isTool(manifest) || manifest.appId in out) continue
val size = SIZE_ON_DISK.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
out[manifest.appId] = Installed(manifest.appId, manifest.name, manifest.installDir, library, size)
}
}
return out
}
/** The account the client signs in with by itself: remembered, the most recent one first. */
fun savedAccount(loginUsers: String): String? {
val users = LinkedHashMap<String, HashMap<String, String>>()
walk(loginUsers, pair = { blocks, key, value ->
if (blocks.size == 2 && blocks[0].equals("users", ignoreCase = true)) users.getOrPut(blocks[1]) { HashMap() }[key.lowercase()] = value
})
val remembered = users.values.filter { it["rememberpassword"] == "1" }
val user = remembered.firstOrNull { it["mostrecent"] == "1" }
?: remembered.maxByOrNull { it["timestamp"]?.toLongOrNull() ?: 0L }
?: return null
return user["personaname"]?.takeIf { it.isNotBlank() } ?: user["accountname"]?.takeIf { it.isNotBlank() }
}
fun language(registry: String): String? {
var found: String? = null
walk(registry, pair = { blocks, key, value ->
if (found == null && key.equals("language", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value
})
return found
}
fun stageOf(phase: String): DownloadStage {
val p = phase.lowercase()
return when {
"verif" in p || "validat" in p -> DownloadStage.VERIFY
listOf("install", "regist", "final", "commit", "acf", "apply").any { it in p } -> DownloadStage.INSTALL
listOf("manifest", "plan", "prepar", "check", "scan", "clean", "alloc", "connect", "logon", "login", "sign").any { it in p } -> DownloadStage.MANIFEST
else -> DownloadStage.DOWNLOAD
}
}
}
@@ -0,0 +1,12 @@
package com.droiddeck.launcher.stores.steam
object SteamNative {
@JvmStatic external fun nativeSignIn(steamRootsJson: String, registryVdfPath: String, caBundlePath: String): String
@JvmStatic external fun nativeSignOut()
@JvmStatic external fun nativeLibrary(): String
@JvmStatic external fun nativePlan(appId: Int, language: String): String
@JvmStatic external fun nativeStart(appId: Int, language: String, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String, journalDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Any): Long
@JvmStatic external fun nativeCancel(handle: Long)
@JvmStatic external fun nativeRelease(handle: Long)
@JvmStatic external fun nativeUninstall(appId: Int, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String): String
}
@@ -0,0 +1,346 @@
package com.droiddeck.launcher.stores.steam
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.storage.SteamStorage
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreAccounts
import com.droiddeck.launcher.stores.StoreBackend
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreShelves
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.download.SavedQueue
import com.droiddeck.launcher.stores.formatBytes
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
/** Games land in the active client's own libraries, registered as the client does, and only while no session can run the client. */
internal object SteamStore {
private const val TAG = "SteamStore"
private const val PREFS = "steam-store"
internal const val JOURNAL = "steam-store/journal"
private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
private const val LIBRARY = "library"
private const val LIBRARY_LABEL = "libraryLabel"
private val SIGNED_OUT = setOf("no_saved_login", "remember_me_off", "decrypt_failed")
var installed by mutableStateOf<Map<Int, SteamLibraryFolders.Installed>>(emptyMap())
private set
var picking by mutableStateOf<CatalogItem?>(null)
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String) {
companion object {
fun of(json: JSONObject): Plan? {
if (!json.optBoolean("ok")) return null
val dir = json.optString("installDir").takeIf { SteamStore.validDir(it) } ?: return null
return Plan(dir, json.optLong("downloadBytes"), json.optLong("installBytes"), json.optString("buildId"))
}
}
}
private val plans = ConcurrentHashMap<Int, Plan>()
private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "steam-store") }
@Volatile private var rejectedThisRun: String? = null
fun key(appId: Int): String = "${Store.STEAM.id}:$appId"
private fun validDir(dir: String) = dir.isNotBlank() && dir != "." && dir != ".." && '/' !in dir && '\\' !in dir
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun toast(context: Context, @StringRes text: Int) {
val app = context.applicationContext
StoresState.post { Toast.makeText(app, text, Toast.LENGTH_LONG).show() }
}
internal fun isSignInError(error: String) = error in SIGNED_OUT || error.startsWith("logon_failed")
internal fun errorText(context: Context, answer: JSONObject): String {
val error = answer.optString("error")
return when {
error == SteamEngine.MISSING -> SteamEngine.MISSING_TEXT
isSignInError(error) -> context.getString(R.string.stores_login_title, Store.STEAM.label)
error.isBlank() -> "Steam: install failed"
else -> error
}
}
private fun fingerprint(context: Context): String {
val users = SteamClient.loginUsers(context)
val registry = SteamClient.registry(context)
return "${SteamClient.activeArch(context)}:${users.lastModified()}:${users.length()}:${registry.lastModified()}:${registry.length()}"
}
private fun savedAccount(context: Context): String? {
val print = fingerprint(context)
if (print == rejectedThisRun || print == prefs(context).getString("rejected", null)) return null
return runCatching { SteamLibraryFolders.savedAccount(SteamClient.loginUsers(context).readText()) }.getOrNull()
}
/** Mirrors the client's saved sign-in into the store account; reads storage. */
fun syncAccount(context: Context): Boolean {
val name = savedAccount(context)
if (name == StoreAccounts.signedInAs(context, Store.STEAM)) return false
if (name == null) StoreAccounts.clear(context, Store.STEAM)
else StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", name))
SteamEngine.forget()
StoresState.post {
StoresState.library.remove(Store.STEAM)
StoresState.problems.remove(Store.STEAM)
}
Log.i(TAG, if (name == null) "no saved Steam sign-in" else "Steam sign-in found")
return true
}
internal fun signInFailed(context: Context, error: String) {
if (error == SteamEngine.MISSING) return
val print = fingerprint(context)
rejectedThisRun = print
if (error in SIGNED_OUT) prefs(context).edit().putString("rejected", print).apply()
StoreAccounts.clear(context, Store.STEAM)
StoresState.logLine("Steam: the saved sign-in was not accepted ($error)")
StoresState.post {
StoresState.accounts.remove(Store.STEAM)
StoresState.library.remove(Store.STEAM)
}
}
fun poll(context: Context) {
val app = context.applicationContext
work.execute {
val changed = runCatching { syncAccount(app) }.getOrDefault(false)
runCatching { scanInstalled(app) }
if (changed) StoresState.notifyLibraryChanged(app)
}
}
private class Read(val modified: Long, val length: Long, val text: String)
private val manifests = ConcurrentHashMap<String, Read>()
private fun readManifest(file: File): String? {
val modified = file.lastModified()
val length = file.length()
manifests[file.path]?.takeIf { it.modified == modified && it.length == length }?.let { return it.text }
val text = runCatching { file.readText() }.getOrNull() ?: return null
manifests[file.path] = Read(modified, length, text)
return text
}
/** Owned games count as installed when an appmanifest with StateFlags 4 is in one of the active client's libraries. */
fun scanInstalled(context: Context) {
val found = SteamLibraryFolders.installed(SteamClient.libraries(context), ::readManifest)
StoresState.post {
if (found != installed) installed = found
for ((id, game) in found) if (game.sizeOnDisk > 0 && StoreSizes.onDisk[key(id)] != game.sizeOnDisk) StoreSizes.onDisk[key(id)] = game.sizeOnDisk
}
}
fun downloading(): Boolean = StoresState.latestDownloads.any {
it.store == Store.STEAM && (it.state == DownloadState.RUNNING || it.state == DownloadState.QUEUED)
}
/** A Steam store download holds every session that could start the Steam client. */
fun blocksSession(intent: Intent?): Boolean {
val mode = intent?.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
return mode != SessionService.MODE_RUN && downloading()
}
internal fun syncLibrary(context: Context, force: Boolean) {
val app = context.applicationContext
if (force) plans.clear()
work.execute {
val answer = SteamEngine.library(app)
if (!answer.optBoolean("ok")) {
val error = answer.optString("error")
if (isSignInError(error)) signInFailed(app, error)
else StoresState.post {
StoresState.problems[Store.STEAM] = errorText(app, answer)
StoresState.library[Store.STEAM] = emptyList()
}
return@execute
}
val art = runCatching { Library.steamLibraryArt(app).toMap() }.getOrDefault(emptyMap())
val items = items(answer.optJSONArray("games"), art)
runCatching { scanInstalled(app) }
StoresState.logLine("Steam: library has ${items.size} games")
StoresState.post {
StoresState.problems.remove(Store.STEAM)
StoresState.library[Store.STEAM] = items
}
}
}
private fun items(games: JSONArray?, art: Map<Int, File>): List<CatalogItem> {
val out = ArrayList<CatalogItem>()
for (i in 0 until (games?.length() ?: 0)) {
val game = games?.optJSONObject(i) ?: continue
val id = game.optInt("appId").takeIf { it > 0 } ?: continue
val type = game.optString("type").lowercase()
if (type.isNotEmpty() && type != "game") continue
val name = game.optString("name").takeIf { it.isNotBlank() } ?: continue
out += CatalogItem(
Store.STEAM, id.toString(), name,
imageUrl = "$CDN$id/header.jpg",
tallImageUrl = art[id]?.let { Uri.fromFile(it).toString() } ?: "$CDN$id/library_600x900.jpg",
isFree = game.optBoolean("free"),
storeUrl = "https://store.steampowered.com/app/$id/",
owned = true,
)
}
return out.distinctBy { it.id }.sortedBy { it.title.lowercase() }
}
internal fun shelves(context: Context): StoreShelves {
val art = runCatching { Library.steamLibraryArt(context) }.getOrDefault(emptyList()).map { Uri.fromFile(it.second).toString() }
return StoreShelves(art = art)
}
/** Reaches the network; call off the main thread. */
internal fun plan(context: Context, appId: Int, language: String = SteamClient.language(context)): Pair<Plan?, JSONObject> {
plans[appId]?.let { return it to JSONObject().put("ok", true) }
val answer = SteamEngine.plan(context, appId, language)
val plan = Plan.of(answer)
val error = answer.optString("error")
if (plan != null) plans[appId] = plan
else if (isSignInError(error)) signInFailed(context, error)
return plan to answer
}
internal fun plannedBytes(context: Context, item: CatalogItem): Long =
item.id.toIntOrNull()?.let { plan(context, it).first?.installBytes } ?: 0L
fun requestInstall(context: Context, item: CatalogItem) {
if (SteamClient.clientMayRun()) {
toast(context, R.string.steam_store_close_steam)
return
}
picking = item
}
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
val app = context.applicationContext
val appId = item.id.toIntOrNull() ?: return
if (SteamClient.clientMayRun()) {
toast(app, R.string.steam_store_close_steam)
return
}
val plan = plans[appId]
val needed = plan?.installBytes ?: 0L
val tagged = item.copy(extra = item.extra + mapOf(LIBRARY to target.library.guest, LIBRARY_LABEL to target.label))
val entry = DownloadEntry(
Store.STEAM, item.id, item.title, cover = item.imageUrl,
bytesTotal = plan?.downloadBytes ?: 0L, location = target.label,
)
SavedQueue.remember(app, tagged, target.library.host)
if (StoreInstallRoot.insufficientSpace(needed, target.freeBytes)) {
val error = app.getString(R.string.stores_storage_insufficient, formatBytes(needed), formatBytes(target.freeBytes))
DownloadQueue.recordFailed(app, entry, error) { requestInstall(app, item) }
return
}
DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, target.library.guest) }
}
internal fun restore(context: Context, item: CatalogItem) {
val app = context.applicationContext
val appId = item.id.toIntOrNull() ?: return
val guest = item.extra[LIBRARY] ?: return
SavedQueue.remember(app, item, null)
val entry = DownloadEntry(Store.STEAM, item.id, item.title, cover = item.imageUrl, location = item.extra[LIBRARY_LABEL].orEmpty())
DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, guest) }
}
fun uninstall(context: Context, appId: Int, onDone: () -> Unit = {}) {
val app = context.applicationContext
if (SteamClient.clientMayRun()) {
toast(app, R.string.steam_store_close_steam)
return
}
val key = key(appId)
if (key in StoresState.uninstalling) return
StoresState.uninstalling[key] = 0f
Thread({
val answer = runCatching {
val game = SteamLibraryFolders.installed(SteamClient.libraries(app))[appId]
if (game == null) JSONObject().put("ok", true)
else {
val engine = SteamClient.engineLibraries(app)
SteamEngine.uninstall(appId, SteamClient.root(app).absolutePath, engine.hostOf(game.library).absolutePath, game.library.guest, engine.json)
}
}.getOrElse { SteamEngine.failure(it.javaClass.simpleName) }
val ok = answer.optBoolean("ok")
StoresState.logLine(if (ok) "Steam: uninstalled $appId" else "Steam: uninstall of $appId failed: ${answer.optString("error")}")
runCatching { scanInstalled(app) }
StoresState.post {
StoresState.uninstalling.remove(key)
if (ok) StoreSizes.onDisk.remove(key)
else Toast.makeText(app, errorText(app, answer), Toast.LENGTH_LONG).show()
onDone()
}
}, "steam-uninstall").start()
}
/** Removes what a cancelled download left; a finished install stays. */
internal fun discardPartial(context: Context, appId: Int, guest: String, host: File?, installDir: String?) {
File(context.filesDir, "$JOURNAL/$appId").deleteRecursively()
val library = host ?: runCatching {
SteamClient.engineLibraries(context).libraries.firstOrNull { it.first.guest == guest }?.second
}.getOrNull() ?: return
val apps = File(library, "steamapps")
val acf = File(apps, "appmanifest_$appId.acf")
val manifest = acf.takeIf { it.isFile }?.let { f -> runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull() }
if (manifest?.installed == true) return
val dir = (installDir ?: manifest?.installDir ?: plans[appId]?.installDir)?.takeIf { validDir(it) }
if (dir != null) StoreInstalls.deleteTree(File(apps, "common/$dir"))
StoreInstalls.deleteTree(File(apps, "downloading/$appId"))
if (manifest != null) acf.delete()
StoresState.logLine("Steam: removed the unfinished download of $appId")
}
}
internal object SteamBackend : StoreBackend {
override val store: Store = Store.STEAM
override fun signIn(context: Context) {
StoresState.logLine("Steam: sign in from the Steam client")
}
override fun signOut(context: Context) = SteamEngine.forget()
override fun syncLibrary(context: Context, force: Boolean) = SteamStore.syncLibrary(context, force)
override fun loadShelves(context: Context, force: Boolean) {
val app = context.applicationContext
Thread({
val shelves = SteamStore.shelves(app)
StoresState.post { StoresState.shelves[store] = shelves }
}, "steam-shelves").start()
}
override fun search(context: Context, query: String): List<CatalogItem> =
StoresState.library[store].orEmpty().filter { it.title.contains(query, ignoreCase = true) }
override fun install(context: Context, item: CatalogItem, root: File) = SteamStore.restore(context, item)
override fun uninstall(context: Context, game: InstalledStoreGame) {}
}
@@ -727,6 +727,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
StepsLayer(screenAt)
appToChooseDisplay?.let { app ->
@@ -103,6 +103,7 @@ import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.gamejolt.GameJoltApi
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
import com.droiddeck.launcher.stores.steam.SteamStore
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
@@ -122,6 +123,7 @@ import androidx.compose.runtime.getValue
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
appId != null -> games.firstOrNull { it.appId == appId }
store == Store.STEAM && storeId != null -> games.firstOrNull { Library.fromSteamClient(it) && it.appId.toString() == storeId }
store != null && storeId != null -> games.firstOrNull { it.source == store.id && it.storeId == storeId }
else -> null
}
@@ -225,7 +227,7 @@ internal fun GameDetail(
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
if (installed != null && installed.sidecar.store == Store.GAMEJOLT) GameJoltCheckButton(installed)
RemoveButton(title, game, installed, a)
if (store == Store.STEAM) SteamRemoveButton(title, id?.toIntOrNull(), a) else RemoveButton(title, game, installed, a)
}
}
}
@@ -717,6 +719,43 @@ private fun RemoveButton(title: String, game: Library.SteamGame?, installed: Ins
)
}
@Composable
private fun SteamRemoveButton(title: String, appId: Int?, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val game = appId?.let { SteamStore.installed[it] } ?: return
val key = SteamStore.key(game.appId)
if (StoresState.uninstalling[key] != null) {
val uninstalling = stringResource(R.string.stores_uninstalling)
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(40.dp).glass(CircleShape).semantics { contentDescription = uninstalling }) {
CircularProgressIndicator(strokeWidth = 2.dp, color = colors.error, modifier = Modifier.size(20.dp))
}
return
}
val heading = stringResource(R.string.stores_uninstall_title, title)
val body = if (game.sizeOnDisk > 0) stringResource(R.string.stores_uninstall_body_size, formatBytes(game.sizeOnDisk)) else stringResource(R.string.games_uninstall_body)
val keep = stringResource(R.string.stores_notification_keep)
val remove = stringResource(R.string.stores_uninstall)
val busy = StoresState.download(key)?.isActive == true
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
IconAction(Icons.Outlined.Delete, remove, "game:remove", danger = true, enabled = !busy, frosted = true) {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot() ?: return@IconAction
var confirmed = false
Steps.ask(StepAsk(anchor = at, side = StepSide.Left, accent = colors.error, items = 3, pillCorner = 12.dp, maxWidth = 340.dp,
onDismiss = { if (confirmed) SteamStore.uninstall(ctx, game.appId) { StoresState.refresh(ctx); a.onLibraryChanged() } },
handle = { Icon(Icons.Outlined.Delete, null, tint = colors.error, modifier = Modifier.size(18.dp)) }) {
StepTitle(heading)
Text(body, fontSize = 13.sp, lineHeight = 18.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp))
Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) {
StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() }
StepChoice(remove, danger = true, enabled = open) { confirmed = true; Steps.fold() }
}
})
}
}
}
@Composable
private fun InstallButton(label: String, modifier: Modifier = Modifier, onInstall: () -> Unit) {
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
@@ -136,7 +136,7 @@ internal fun libraryEntries(
out += LibraryEntry(GameRef.key(g), g.source, g.name, g, item,
installed = g.library != Library.XBOX_CLOUD || storeKey in installedStore)
}
for (store in Store.entries) for (item in owned[store].orEmpty()) {
for (store in Store.entries) if (store != Store.STEAM) for (item in owned[store].orEmpty()) {
if (!claimed.add(item.key)) continue
out += LibraryEntry(GameRef.key(item), store.id, item.title, null, item, installed = item.key in installedStore)
}
@@ -215,7 +215,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
LaunchedEffect(Unit) { StoresState.refresh(ctx) }
remember { LibraryDisplay.load(ctx) }
val stores = s.gameStoresEnabled && !s.shortcutPicker
val signedIn = Store.entries.filter { StoresState.isSignedIn(it) }
val signedIn = Store.entries.filter { it != Store.STEAM && StoresState.isSignedIn(it) }
LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } }
val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap()
val installedStore = StoresState.installed.map { it.key }.toSet()
@@ -33,14 +33,14 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
Store.ITCH.id -> SourceColours(Color(0xFF3A1A1E), Color(0xFFFFB3B3), Color(0xFFFF5C5C))
Store.GAMEJOLT.id -> SourceColours(Color(0xFF232E00), Color(0xFFE3FF66), Color(0xFFCCFF00))
Store.BATTLENET.id -> SourceColours(Color(0xFF0A2440), Color(0xFF9DD1FF), Color(0xFF148EFF))
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
Library.SOURCE_STEAM, Store.STEAM.id -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
}
@Composable
internal fun sourceLabel(source: String): String = when (source) {
Library.SOURCE_STEAM -> stringResource(R.string.source_steam)
Library.SOURCE_STEAM, Store.STEAM.id -> stringResource(R.string.source_steam)
Store.GOG.id -> Store.GOG.label
Store.EPIC.id -> Store.EPIC.label
Store.AMAZON.id -> Store.AMAZON.label
@@ -27,6 +27,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -46,7 +47,10 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreSizes
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.steam.SteamClient
import com.droiddeck.launcher.stores.steam.SteamStore
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.gog.GogDownloadManager
import kotlinx.coroutines.Dispatchers
@@ -133,6 +137,61 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
}
}
@Composable
internal fun SteamInstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val targets by produceState<List<SteamClient.Target>?>(null, item.key) {
value = withContext(Dispatchers.IO) { runCatching { SteamClient.targets(ctx) }.getOrDefault(emptyList()) }
}
val needed by produceState(StoreSizes.size(item), item.key) {
val bytes = withContext(Dispatchers.IO) { runCatching { SteamStore.plannedBytes(ctx, item) }.getOrDefault(0L) }
if (bytes > 0L) value = bytes
}
val list = targets
val focus = remember(list?.size) { List(list?.size ?: 0) { FocusRequester() } }
LaunchedEffect(focus) { if (focus.isNotEmpty()) focusWithinFrames({ false }) { focus[0] } }
AppDialog(shown, close, "steamInstallWhere", wide = false, maxWidth = 440.dp) {
Rise(0) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
Text(
stringResource(R.string.stores_install_title, item.title), fontSize = 15.sp, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
)
Text(
stringResource(R.string.common_cancel), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
modifier = Modifier.clip(Shape12).focusGlide().clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp),
)
}
}
Rise(1) {
when {
list == null -> androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
list.isEmpty() -> Note(stringResource(R.string.game_sync_err_steam_library))
else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
list.forEachIndexed { i, t ->
val isLow = StoreInstallRoot.insufficientSpace(needed, t.freeBytes)
val freeText = when {
t.freeBytes < 0L -> stringResource(R.string.stores_target_free_unknown)
isLow -> stringResource(R.string.stores_storage_low, formatBytes(t.freeBytes), formatBytes(needed))
else -> stringResource(R.string.stores_target_free, formatBytes(t.freeBytes))
}
TargetRow(
label = t.label, free = freeText, removable = t.removable, folder = t.folder, focus = focus[i],
modifier = Modifier.fillMaxWidth(), warning = isLow,
) {
SteamStore.install(ctx, item, t)
close()
}
}
}
}
}
}
}
@Composable
private fun TargetRow(label: String, free: String, removable: Boolean, folder: Boolean, focus: FocusRequester, modifier: Modifier, warning: Boolean = false, onPick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -216,6 +216,12 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
delay(5_000)
}
}
if (chip == Store.STEAM.id) {
while (true) {
if (lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) com.droiddeck.launcher.stores.steam.SteamStore.poll(ctx)
delay(5_000)
}
}
if (chip == Store.EPIC.id) {
EpicClient.ensure(ctx)
while (true) {
@@ -382,7 +388,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
!k.accountsLoaded -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) {
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
}
!k.signedIn -> Box(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { SignInCard(st, viewportH - 20.dp) }
!k.signedIn -> Box(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { SignInCard(st, viewportH - 20.dp, onSignIn = if (st == Store.STEAM) a.onPlay else null) }
else -> Storefront(st, query, s, a, grids.getOrPut(k) { LazyGridState() }, clearSearchFocus = openGame != null, onQuery = { query = it }, onOpen = { open(it) })
}
}
@@ -736,7 +742,7 @@ internal fun CountPill(count: Int) {
@Composable
private fun SignInCard(store: Store, height: Dp) {
private fun SignInCard(store: Store, height: Dp, onSignIn: (() -> Unit)? = null) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -785,21 +791,23 @@ private fun SignInCard(store: Store, height: Dp) {
)
}
Spacer(Modifier.height(6.dp))
Rise(3) { SignInButton(store, large = true) }
Rise(3) { SignInButton(store, large = true, onSignIn = onSignIn) }
}
}
}
@Composable
private fun SignInButton(store: Store, large: Boolean = false) {
private fun SignInButton(store: Store, large: Boolean = false, onSignIn: (() -> Unit)? = null) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val placed = remember { arrayOfNulls<androidx.compose.ui.layout.LayoutCoordinates>(1) }
var askKey by remember { mutableStateOf(false) }
if (askKey) ItchKeyDialog { askKey = false }
Box(Modifier.onGloballyPositioned { placed[0] = it }) {
PrimaryButton(stringResource(R.string.stores_signin), main = true, large = large, icon = if (large) Icons.AutoMirrored.Filled.Login else null) {
if (store == Store.ITCH) askKey = true
val label = if (onSignIn != null) stringResource(R.string.stores_login_title, store.label) else stringResource(R.string.stores_signin)
PrimaryButton(label, main = true, large = large, icon = if (large) Icons.AutoMirrored.Filled.Login else null) {
if (onSignIn != null) onSignIn()
else if (store == Store.ITCH) askKey = true
else {
val at = placed[0]?.takeIf { it.isAttached }?.boundsInRoot()
if (at == null || Motion.scale == 0f || StoresMotion.signIn != null) StoresState.signIn(ctx, store)
@@ -822,7 +830,11 @@ private fun Storefront(
val library = StoresState.library[store] ?: emptyList()
val shelves = StoresState.shelves[store]
val found = StoresState.found[store] ?: emptyList()
val installedKeys = remember(StoresState.installed) { StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet() }
val steamInstalled = if (store == Store.STEAM) com.droiddeck.launcher.stores.steam.SteamStore.installed else emptyMap()
val installedKeys = remember(StoresState.installed, steamInstalled) {
if (store == Store.STEAM) steamInstalled.keys.mapTo(HashSet()) { it.toString() }
else StoresState.installed.filter { it.sidecar.store == store }.map { it.sidecar.id }.toSet()
}
val q = query.trim().lowercase()
val foundKeys = remember(found) { found.map { it.key }.toSet() }
fun shown(i: CatalogItem) = s.storesShowMature || !i.mature || i.accessible
@@ -832,9 +844,11 @@ private fun Storefront(
LaunchedEffect(gameJolt, s.storesShowMature) { if (gameJolt) GameJoltBrowseState.sync(ctx, s.storesShowMature) }
val browsing = q.isEmpty() && ((store == Store.ITCH && ItchBrowseState.active) || gameJolt)
val browseItems = if (!browsing) emptyList() else if (gameJolt) GameJoltBrowseState.items else ItchBrowseState.items
val catalog = store == Store.BATTLENET && q.isEmpty()
val steam = store == Store.STEAM
val catalog = (store == Store.BATTLENET || steam) && q.isEmpty()
val visible = remember(found, library, shelves, q, s.storesShowMature, browsing, browseItems, catalog) {
if (catalog) shelf(shelves?.trending) ?: emptyList()
if (catalog && steam) library.filter(::shown)
else if (catalog) shelf(shelves?.trending) ?: emptyList()
else if (browsing) {
val owned = library.associateBy { it.id }
browseItems.map { owned[it.id] ?: it }.filter(::shown)
@@ -847,7 +861,8 @@ private fun Storefront(
browsing && gameJolt && GameJoltBrowseState.failed -> R.string.stores_gamejolt_browse_failed
browsing && !gameJolt && ItchBrowseState.loading -> R.string.stores_shelves_loading
browsing && !gameJolt && ItchBrowseState.failed -> R.string.stores_itch_browse_failed
catalog && shelves == null -> R.string.stores_shelves_loading
catalog && steam && !StoresState.library.containsKey(store) -> R.string.stores_shelves_loading
catalog && !steam && shelves == null -> R.string.stores_shelves_loading
else -> R.string.stores_nothing_matches
})
var firstPlaced = false
@@ -863,7 +878,7 @@ private fun Storefront(
val barLine = StoresState.status[store]?.takeIf { bareTab && syncCount(it) != null }
val itchBar = store == Store.ITCH && q.isEmpty()
val gameJoltBar = gameJolt && q.isEmpty()
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar || gameJoltBar) 1 else 0) + (if (catalog) 1 else 0)
val headerItems = 2 + (if (barLine != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + (if (itchBar || gameJoltBar) 1 else 0) + (if (catalog && !steam) 1 else 0)
val card: @Composable (CatalogItem) -> Unit = { item ->
val first = if (searching) item.key == visible.firstOrNull()?.key else !firstPlaced
firstPlaced = true
@@ -913,7 +928,7 @@ private fun Storefront(
StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } }
if (itchBar) item(key = "itch-browse-bar", span = { GridItemSpan(maxLineSpan) }) { ItchBrowseBar() }
if (gameJoltBar) item(key = "gamejolt-browse-bar", span = { GridItemSpan(maxLineSpan) }) { GameJoltBrowseBar(s.storesShowMature) }
if (catalog) item(key = "catalog-label", span = { GridItemSpan(maxLineSpan) }) {
if (catalog && !steam) item(key = "catalog-label", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.padding(top = 10.dp)) { SectionLabel(stringResource(R.string.bnet_store)) }
}
if (searching) {
@@ -959,7 +974,7 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS
)
}
Actions {
SmallTextButton(stringResource(R.string.stores_owned_in_library), key = "owned-in-library") {
if (store != Store.STEAM) SmallTextButton(stringResource(R.string.stores_owned_in_library), key = "owned-in-library") {
LibraryView.showOwned(ctx, store)
show("games")
}
@@ -967,7 +982,7 @@ private fun ProfileStrip(store: Store, owned: Int, loaded: Boolean, s: FrontEndS
if (store == Store.XBOX) SmallTextButton(stringResource(R.string.stores_xbox_cloud_settings), key = "xbox-cloud-settings") {
ctx.startActivity(android.content.Intent(ctx, com.droiddeck.launcher.stores.xbox.XboxCloudSettingsActivity::class.java))
}
SignOutButton(store, name)
if (store != Store.STEAM) SignOutButton(store, name)
}
}
if (store == Store.EPIC) EpicLauncherRow(s, a)
@@ -1157,6 +1172,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
Store.ITCH -> Color(0xFFFF5C5C) to Color(0xFFD93B3B)
Store.GAMEJOLT -> Color(0xFFCCFF00) to Color(0xFFA3CC00)
Store.BATTLENET -> Color(0xFF148EFF) to Color(0xFF0B6BD3)
Store.STEAM -> Color(0xFF1A9FFF) to Color(0xFF0F6FC0)
null -> return base
}
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
+2
View File
@@ -3850,4 +3850,6 @@
<string name="wow_chat_listening">جارٍ الاستماع…</string>
<string name="wow_chat_voice_unavailable">الكتابة بالصوت غير متاحة على هذا الجهاز.</string>
<string name="wow_chat_mic_denied">يلزم الوصول إلى الميكروفون للكتابة بالصوت.</string>
<string name="steam_store_close_steam">أغلق Steam أولاً</string>
<string name="steam_store_session_wait">أوقف تنزيل Steam مؤقتًا أولاً</string>
</resources>
@@ -3706,4 +3706,6 @@
<string name="wow_chat_listening">Escuchando…</string>
<string name="wow_chat_voice_unavailable">El dictado por voz no está disponible en este dispositivo.</string>
<string name="wow_chat_mic_denied">Se necesita acceso al micrófono para el dictado por voz.</string>
<string name="steam_store_close_steam">Cierra Steam primero</string>
<string name="steam_store_session_wait">Pausa primero la descarga de Steam</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Слушане…</string>
<string name="wow_chat_voice_unavailable">Гласовото въвеждане не е налично на това устройство.</string>
<string name="wow_chat_mic_denied">За гласово въвеждане е нужен достъп до микрофона.</string>
<string name="steam_store_close_steam">Първо затворете Steam</string>
<string name="steam_store_session_wait">Първо поставете на пауза изтеглянето от Steam</string>
</resources>
+2
View File
@@ -3772,4 +3772,6 @@
<string name="wow_chat_listening">Poslouchám…</string>
<string name="wow_chat_voice_unavailable">Hlasové psaní není na tomto zařízení k dispozici.</string>
<string name="wow_chat_mic_denied">Pro hlasové psaní je potřeba přístup k mikrofonu.</string>
<string name="steam_store_close_steam">Nejprve zavřete Steam</string>
<string name="steam_store_session_wait">Nejprve pozastavte stahování ze Steamu</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Lytter…</string>
<string name="wow_chat_voice_unavailable">Stemmeindtastning er ikke tilgængelig på denne enhed.</string>
<string name="wow_chat_mic_denied">Mikrofonadgang er nødvendig for stemmeindtastning.</string>
<string name="steam_store_close_steam">Luk Steam først</string>
<string name="steam_store_session_wait">Sæt Steam-downloaden på pause først</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Hört zu…</string>
<string name="wow_chat_voice_unavailable">Spracheingabe ist auf diesem Gerät nicht verfügbar.</string>
<string name="wow_chat_mic_denied">Für die Spracheingabe wird Mikrofonzugriff benötigt.</string>
<string name="steam_store_close_steam">Schließe zuerst Steam</string>
<string name="steam_store_session_wait">Pausiere zuerst den Steam-Download</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Ακρόαση…</string>
<string name="wow_chat_voice_unavailable">Η φωνητική πληκτρολόγηση δεν είναι διαθέσιμη σε αυτή τη συσκευή.</string>
<string name="wow_chat_mic_denied">Απαιτείται πρόσβαση στο μικρόφωνο για φωνητική πληκτρολόγηση.</string>
<string name="steam_store_close_steam">Κλείστε πρώτα το Steam</string>
<string name="steam_store_session_wait">Θέστε πρώτα σε παύση τη λήψη του Steam</string>
</resources>
+2
View File
@@ -3733,4 +3733,6 @@
<string name="wow_chat_listening">Escuchando…</string>
<string name="wow_chat_voice_unavailable">El dictado por voz no está disponible en este dispositivo.</string>
<string name="wow_chat_mic_denied">Se necesita acceso al micrófono para el dictado por voz.</string>
<string name="steam_store_close_steam">Cierra Steam primero</string>
<string name="steam_store_session_wait">Pausa primero la descarga de Steam</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Kuunnellaan…</string>
<string name="wow_chat_voice_unavailable">Puhekirjoitus ei ole käytettävissä tällä laitteella.</string>
<string name="wow_chat_mic_denied">Puhekirjoitus vaatii mikrofonin käyttöoikeuden.</string>
<string name="steam_store_close_steam">Sulje Steam ensin</string>
<string name="steam_store_session_wait">Keskeytä Steam-lataus ensin</string>
</resources>
+2
View File
@@ -3733,4 +3733,6 @@
<string name="wow_chat_listening">Écoute…</string>
<string name="wow_chat_voice_unavailable">La saisie vocale n\'est pas disponible sur cet appareil.</string>
<string name="wow_chat_mic_denied">L\'accès au micro est nécessaire pour la saisie vocale.</string>
<string name="steam_store_close_steam">Fermez d\'abord Steam</string>
<string name="steam_store_session_wait">Mettez d\'abord en pause le téléchargement Steam</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">सुन रहा है…</string>
<string name="wow_chat_voice_unavailable">इस डिवाइस पर आवाज़ से टाइपिंग उपलब्ध नहीं है।</string>
<string name="wow_chat_mic_denied">आवाज़ से टाइपिंग के लिए माइक्रोफ़ोन की अनुमति चाहिए।</string>
<string name="steam_store_close_steam">पहले Steam बंद करें</string>
<string name="steam_store_session_wait">पहले Steam डाउनलोड रोकें</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Figyelés…</string>
<string name="wow_chat_voice_unavailable">A hangalapú gépelés nem érhető el ezen az eszközön.</string>
<string name="wow_chat_mic_denied">A hangalapú gépeléshez mikrofon-hozzáférés szükséges.</string>
<string name="steam_store_close_steam">Előbb zárd be a Steamet</string>
<string name="steam_store_session_wait">Előbb szüneteltesd a Steam-letöltést</string>
</resources>
+2
View File
@@ -3664,4 +3664,6 @@
<string name="wow_chat_listening">Mendengarkan…</string>
<string name="wow_chat_voice_unavailable">Ketik dengan suara tidak tersedia di perangkat ini.</string>
<string name="wow_chat_mic_denied">Akses mikrofon diperlukan untuk mengetik dengan suara.</string>
<string name="steam_store_close_steam">Tutup Steam terlebih dahulu</string>
<string name="steam_store_session_wait">Jeda unduhan Steam terlebih dahulu</string>
</resources>
+2
View File
@@ -3733,4 +3733,6 @@
<string name="wow_chat_listening">In ascolto…</string>
<string name="wow_chat_voice_unavailable">La digitazione vocale non è disponibile su questo dispositivo.</string>
<string name="wow_chat_mic_denied">Per la digitazione vocale serve l\'accesso al microfono.</string>
<string name="steam_store_close_steam">Chiudi prima Steam</string>
<string name="steam_store_session_wait">Metti prima in pausa il download di Steam</string>
</resources>
+2
View File
@@ -3664,4 +3664,6 @@
<string name="wow_chat_listening">聞き取り中…</string>
<string name="wow_chat_voice_unavailable">このデバイスでは音声入力を使用できません。</string>
<string name="wow_chat_mic_denied">音声入力にはマイクへのアクセスが必要です。</string>
<string name="steam_store_close_steam">先に Steam を閉じてください</string>
<string name="steam_store_session_wait">先に Steam のダウンロードを一時停止してください</string>
</resources>
+2
View File
@@ -3664,4 +3664,6 @@
<string name="wow_chat_listening">듣는 중…</string>
<string name="wow_chat_voice_unavailable">이 기기에서는 음성 입력을 사용할 수 없습니다.</string>
<string name="wow_chat_mic_denied">음성 입력을 하려면 마이크 접근 권한이 필요합니다.</string>
<string name="steam_store_close_steam">먼저 Steam을 닫으세요</string>
<string name="steam_store_session_wait">먼저 Steam 다운로드를 일시 중지하세요</string>
</resources>
+2
View File
@@ -3664,4 +3664,6 @@
<string name="wow_chat_listening">Mendengar…</string>
<string name="wow_chat_voice_unavailable">Taip dengan suara tidak tersedia pada peranti ini.</string>
<string name="wow_chat_mic_denied">Akses mikrofon diperlukan untuk menaip dengan suara.</string>
<string name="steam_store_close_steam">Tutup Steam dahulu</string>
<string name="steam_store_session_wait">Jeda muat turun Steam dahulu</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Lytter…</string>
<string name="wow_chat_voice_unavailable">Taleinntasting er ikke tilgjengelig på denne enheten.</string>
<string name="wow_chat_mic_denied">Mikrofontilgang trengs for taleinntasting.</string>
<string name="steam_store_close_steam">Lukk Steam først</string>
<string name="steam_store_session_wait">Sett Steam-nedlastingen på pause først</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Luisteren…</string>
<string name="wow_chat_voice_unavailable">Spraakinvoer is niet beschikbaar op dit apparaat.</string>
<string name="wow_chat_mic_denied">Voor spraakinvoer is toegang tot de microfoon nodig.</string>
<string name="steam_store_close_steam">Sluit eerst Steam</string>
<string name="steam_store_session_wait">Pauzeer eerst de Steam-download</string>
</resources>
+2
View File
@@ -3772,4 +3772,6 @@
<string name="wow_chat_listening">Słucham…</string>
<string name="wow_chat_voice_unavailable">Pisanie głosowe nie jest dostępne na tym urządzeniu.</string>
<string name="wow_chat_mic_denied">Pisanie głosowe wymaga dostępu do mikrofonu.</string>
<string name="steam_store_close_steam">Najpierw zamknij Steam</string>
<string name="steam_store_session_wait">Najpierw wstrzymaj pobieranie ze Steam</string>
</resources>
@@ -3733,4 +3733,6 @@
<string name="wow_chat_listening">A ouvir…</string>
<string name="wow_chat_voice_unavailable">A escrita por voz não está disponível neste dispositivo.</string>
<string name="wow_chat_mic_denied">É necessário acesso ao microfone para a escrita por voz.</string>
<string name="steam_store_close_steam">Feche primeiro o Steam</string>
<string name="steam_store_session_wait">Coloque primeiro em pausa a transferência do Steam</string>
</resources>
+2
View File
@@ -3733,4 +3733,6 @@
<string name="wow_chat_listening">Ouvindo…</string>
<string name="wow_chat_voice_unavailable">A digitação por voz não está disponível neste dispositivo.</string>
<string name="wow_chat_mic_denied">É preciso acesso ao microfone para a digitação por voz.</string>
<string name="steam_store_close_steam">Feche o Steam primeiro</string>
<string name="steam_store_session_wait">Pause o download do Steam primeiro</string>
</resources>
+2
View File
@@ -3733,4 +3733,6 @@
<string name="wow_chat_listening">Se ascultă…</string>
<string name="wow_chat_voice_unavailable">Tastarea vocală nu este disponibilă pe acest dispozitiv.</string>
<string name="wow_chat_mic_denied">Pentru tastarea vocală este necesar accesul la microfon.</string>
<string name="steam_store_close_steam">Închide mai întâi Steam</string>
<string name="steam_store_session_wait">Pune mai întâi pe pauză descărcarea Steam</string>
</resources>
+2
View File
@@ -3855,4 +3855,6 @@
<string name="wow_chat_listening">Слушаю…</string>
<string name="wow_chat_voice_unavailable">Голосовой ввод недоступен на этом устройстве.</string>
<string name="wow_chat_mic_denied">Для голосового ввода нужен доступ к микрофону.</string>
<string name="steam_store_close_steam">Сначала закройте Steam</string>
<string name="steam_store_session_wait">Сначала приостановите загрузку Steam</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Lyssnar…</string>
<string name="wow_chat_voice_unavailable">Röstinmatning är inte tillgänglig på den här enheten.</string>
<string name="wow_chat_mic_denied">Mikrofonåtkomst krävs för röstinmatning.</string>
<string name="steam_store_close_steam">Stäng Steam först</string>
<string name="steam_store_session_wait">Pausa Steam-nedladdningen först</string>
</resources>
+2
View File
@@ -3664,4 +3664,6 @@
<string name="wow_chat_listening">กำลังฟัง…</string>
<string name="wow_chat_voice_unavailable">อุปกรณ์นี้ไม่รองรับการพิมพ์ด้วยเสียง</string>
<string name="wow_chat_mic_denied">ต้องอนุญาตให้เข้าถึงไมโครโฟนเพื่อพิมพ์ด้วยเสียง</string>
<string name="steam_store_close_steam">ปิด Steam ก่อน</string>
<string name="steam_store_session_wait">หยุดการดาวน์โหลด Steam ชั่วคราวก่อน</string>
</resources>
+2
View File
@@ -3694,4 +3694,6 @@
<string name="wow_chat_listening">Dinleniyor…</string>
<string name="wow_chat_voice_unavailable">Sesle yazma bu cihazda kullanılamıyor.</string>
<string name="wow_chat_mic_denied">Sesle yazma için mikrofon erişimi gerekiyor.</string>
<string name="steam_store_close_steam">Önce Steam\'i kapatın</string>
<string name="steam_store_session_wait">Önce Steam indirmesini duraklatın</string>
</resources>
+2
View File
@@ -3772,4 +3772,6 @@
<string name="wow_chat_listening">Слухаю…</string>
<string name="wow_chat_voice_unavailable">Голосове введення недоступне на цьому пристрої.</string>
<string name="wow_chat_mic_denied">Для голосового введення потрібен доступ до мікрофона.</string>
<string name="steam_store_close_steam">Спочатку закрийте Steam</string>
<string name="steam_store_session_wait">Спочатку призупиніть завантаження Steam</string>
</resources>
+2
View File
@@ -3664,4 +3664,6 @@
<string name="wow_chat_listening">Đang nghe…</string>
<string name="wow_chat_voice_unavailable">Thiết bị này không hỗ trợ nhập bằng giọng nói.</string>
<string name="wow_chat_mic_denied">Cần quyền truy cập micrô để nhập bằng giọng nói.</string>
<string name="steam_store_close_steam">Hãy đóng Steam trước</string>
<string name="steam_store_session_wait">Hãy tạm dừng tải xuống Steam trước</string>
</resources>
@@ -3668,4 +3668,6 @@
<string name="wow_chat_listening">正在聆听…</string>
<string name="wow_chat_voice_unavailable">此设备不支持语音输入。</string>
<string name="wow_chat_mic_denied">语音输入需要麦克风权限。</string>
<string name="steam_store_close_steam">请先关闭 Steam</string>
<string name="steam_store_session_wait">请先暂停 Steam 下载</string>
</resources>
@@ -3667,4 +3667,6 @@
<string name="wow_chat_listening">正在聆聽…</string>
<string name="wow_chat_voice_unavailable">此裝置不支援語音輸入。</string>
<string name="wow_chat_mic_denied">語音輸入需要咪高峰權限。</string>
<string name="steam_store_close_steam">請先關閉 Steam</string>
<string name="steam_store_session_wait">請先暫停 Steam 下載</string>
</resources>
@@ -3667,4 +3667,6 @@
<string name="wow_chat_listening">正在聆聽…</string>
<string name="wow_chat_voice_unavailable">此裝置不支援語音輸入。</string>
<string name="wow_chat_mic_denied">語音輸入需要麥克風權限。</string>
<string name="steam_store_close_steam">請先關閉 Steam</string>
<string name="steam_store_session_wait">請先暫停 Steam 下載</string>
</resources>
+2
View File
@@ -3852,4 +3852,6 @@
<string name="wow_chat_listening">Listening…</string>
<string name="wow_chat_voice_unavailable">Voice typing is not available on this device.</string>
<string name="wow_chat_mic_denied">Microphone access is needed for voice typing.</string>
<string name="steam_store_close_steam">Close Steam first</string>
<string name="steam_store_session_wait">Pause the Steam download first</string>
</resources>
@@ -0,0 +1,274 @@
package com.droiddeck.launcher.stores.steam
import com.droiddeck.launcher.stores.download.DownloadStage
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SteamLibraryFoldersTest {
private val rootfs = File("/data/user/0/com.droiddeck.launcher/files/rootfs")
private val card = File("/storage/1A2B-3C4D/Android/data/com.droiddeck.launcher/files/steam")
private val lib = File("/storage/1A2B-3C4D/SteamLibrary")
private val games = File("/storage/1A2B-3C4D/Games")
private val armRoot = File(rootfs, "root/.local/share/Steam")
private val x64Root = File(rootfs, "root/.droiddeck-x64/.local/share/Steam")
private val armAliases = listOf("/root/.local/share/Steam", "/root/.steam/steam", "/root/.steam/root")
private val mounts = listOf(
SteamLibraryFolders.Mount("/mnt/droiddeck-sd", card),
SteamLibraryFolders.Mount("/mnt/droiddeck-lib/1", lib),
SteamLibraryFolders.Mount("/root/Games/Card/", games),
SteamLibraryFolders.Mount("/root/Storage", File("/storage/emulated/0")),
)
private val vdf = """
"libraryfolders"
{
"contentstatsid" "-4785"
"0"
{
"path" "/root/.local/share/Steam"
"label" "Internal Storage"
"contentid" "123"
"totalsize" "0"
"apps"
{
"228980" "0"
}
}
"1"
{
"path" "/mnt/droiddeck-sd"
"label" "SD card"
"apps"
{
"291550" "1500000000"
}
}
"2"
{
"path" "/mnt/droiddeck-lib/1"
"label" "Steam \"Lib\""
}
"3"
{
"path" "/root/Games/Card"
"label" ""
}
"4"
{
"path" "/root/.droiddeck-x64/shared/x86-64"
"label" "x86-64 client games"
}
"5"
{
"path" "/mnt/droiddeck-lib/9"
"label" "Removed"
}
"6"
{
"path" "/root/Games/Gone"
"label" "Gone"
}
}
""".trimIndent()
@Test fun readsEveryFolderWithItsLabel() {
val folders = SteamLibraryFolders.parse(vdf)
assertEquals(
listOf("/root/.local/share/Steam", "/mnt/droiddeck-sd", "/mnt/droiddeck-lib/1", "/root/Games/Card",
"/root/.droiddeck-x64/shared/x86-64", "/mnt/droiddeck-lib/9", "/root/Games/Gone"),
folders.map { it.path },
)
assertEquals("Internal Storage", folders[0].label)
assertEquals("Steam \"Lib\"", folders[2].label)
assertEquals("", folders[3].label)
}
@Test fun readsTheOldFormatAndEscapedPaths() {
val old = """
"LibraryFolders"
{
"TimeNextStatsReport" "1700000000"
"ContentStatsID" "-1"
"1" "/mnt/droiddeck-sd"
"2" "/root/odd\\name"
}
""".trimIndent()
assertEquals(
listOf(SteamLibraryFolders.Folder("/mnt/droiddeck-sd", ""), SteamLibraryFolders.Folder("/root/odd\\name", "")),
SteamLibraryFolders.parse(old),
)
assertTrue(SteamLibraryFolders.parse("").isEmpty())
}
@Test fun arm64LibrariesMapFromGuestToHost() {
val libraries = SteamLibraryFolders.resolve(
SteamLibraryFolders.parse(vdf), "/root/.local/share/Steam", armAliases, armRoot, mounts, rootfs,
)
assertEquals(
listOf(armRoot, card, lib, games, File(rootfs, "root/.droiddeck-x64/shared/x86-64")),
libraries.map { it.host },
)
assertEquals(listOf(true, false, false, false, false), libraries.map { it.main })
assertEquals("/mnt/droiddeck-sd", libraries[1].guest)
assertEquals("SD card", libraries[1].label)
}
@Test fun x64LibrariesSitInsideTheCardAndAddedLibraries() {
val text = """
"libraryfolders"
{
"0" { "path" "/root/.droiddeck-x64/.local/share/Steam" "label" "Internal Storage" }
"1" { "path" "/mnt/droiddeck-sd/x86-64" "label" "SD card" }
"2" { "path" "/mnt/droiddeck-lib/1/x86-64/" "label" "Lib" }
"3" { "path" "/root/.droiddeck-x64/shared/arm64" "label" "ARM64 client games" }
}
""".trimIndent()
val libraries = SteamLibraryFolders.resolve(
SteamLibraryFolders.parse(text), "/root/.droiddeck-x64/.local/share/Steam",
listOf("/root/.droiddeck-x64/.local/share/Steam", "/root/.droiddeck-x64/.steam/steam"), x64Root, mounts, rootfs,
)
assertEquals(
listOf(x64Root, File(card, "x86-64"), File(lib, "x86-64"), File(rootfs, "root/.droiddeck-x64/shared/arm64")),
libraries.map { it.host },
)
assertEquals("/mnt/droiddeck-lib/1/x86-64", libraries[2].guest)
}
@Test fun aGuestPathWithoutItsBindIsNotAnInstallTarget() {
assertNull(SteamLibraryFolders.hostFor("/mnt/droiddeck-sd", emptyList(), rootfs))
assertNull(SteamLibraryFolders.hostFor("/root/Games/Gone", mounts, rootfs))
assertNull(SteamLibraryFolders.hostFor("/root/Storage/Steam", emptyList(), rootfs))
assertNull(SteamLibraryFolders.hostFor("/opt/steam", mounts, rootfs))
assertNull(SteamLibraryFolders.hostFor("/root/../etc", mounts, rootfs))
assertNull(SteamLibraryFolders.hostFor("relative/path", mounts, rootfs))
assertEquals(File("/storage/emulated/0/Steam"), SteamLibraryFolders.hostFor("/root/Storage/Steam", mounts, rootfs))
assertEquals(File(card, "x86-64"), SteamLibraryFolders.hostFor("/mnt/droiddeck-sd//x86-64/", mounts, rootfs))
}
@Test fun aliasesAreTheMainLibraryAndAMissingMainIsAddedFirst() {
val aliased = SteamLibraryFolders.resolve(
listOf(SteamLibraryFolders.Folder("/root/.steam/steam", "Internal Storage"), SteamLibraryFolders.Folder("/mnt/droiddeck-sd", "SD card")),
"/root/.local/share/Steam", armAliases, armRoot, mounts, rootfs,
)
assertEquals(listOf(armRoot, card), aliased.map { it.host })
assertEquals("/root/.steam/steam", aliased[0].guest)
val missing = SteamLibraryFolders.resolve(
listOf(SteamLibraryFolders.Folder("/mnt/droiddeck-sd", "SD card"), SteamLibraryFolders.Folder("/mnt/droiddeck-sd/", "Again")),
"/root/.local/share/Steam", armAliases, armRoot, mounts, rootfs,
)
assertEquals(listOf(armRoot, card), missing.map { it.host })
assertEquals("/root/.local/share/Steam", missing[0].guest)
assertEquals("", missing[0].label)
}
private fun acf(library: File, appId: Int, name: String, flags: Int, dir: String = name, size: Long = 0L) {
val apps = File(library, "steamapps").apply { mkdirs() }
File(apps, "appmanifest_$appId.acf").writeText(
"""
"AppState"
{
"appid" "$appId"
"name" "$name"
"StateFlags" "$flags"
"installdir" "$dir"
"SizeOnDisk" "$size"
}
""".trimIndent(),
)
}
@Test fun onlyFullyInstalledGamesCountAsInstalled() {
val base = Files.createTempDirectory("steam-libs").toFile()
try {
val first = SteamLibraryFolders.Library("/root/.local/share/Steam", File(base, "internal"), "Internal Storage", true)
val second = SteamLibraryFolders.Library("/mnt/droiddeck-sd", File(base, "card"), "SD card", false)
val missing = SteamLibraryFolders.Library("/mnt/droiddeck-lib/1", File(base, "gone"), "Gone", false)
acf(first.host, 291550, "Brawlhalla", 4, size = 1_500_000_000L)
acf(first.host, 620, "Portal 2", 1026)
acf(first.host, 1628350, "Steam Linux Runtime 3.0 (sniper)", 4, dir = "SteamLinuxRuntime_sniper")
acf(second.host, 291550, "Brawlhalla copy", 4)
acf(second.host, 413150, "Stardew Valley", 6)
File(second.host, "steamapps/appmanifest_400.acf.tmp").writeText("\"AppState\" { \"appid\" \"400\" \"StateFlags\" \"4\" }")
File(second.host, "steamapps/libraryfolder.vdf").writeText("\"libraryfolder\" { }")
val found = SteamLibraryFolders.installed(listOf(first, second, missing))
assertEquals(setOf(291550, 413150), found.keys)
assertEquals("Brawlhalla", found.getValue(291550).name)
assertEquals(first, found.getValue(291550).library)
assertEquals(1_500_000_000L, found.getValue(291550).sizeOnDisk)
assertEquals(second, found.getValue(413150).library)
assertEquals("Stardew Valley", found.getValue(413150).installDir)
} finally {
base.deleteRecursively()
}
}
@Test fun theClientsRememberedAccountIsTheSavedSignIn() {
val users = """
"users"
{
"76561190000000001"
{
"AccountName" "old"
"PersonaName" "Old One"
"RememberPassword" "1"
"MostRecent" "0"
"Timestamp" "1600000000"
}
"76561190000000002"
{
"AccountName" "player"
"PersonaName" "Player"
"RememberPassword" "1"
"MostRecent" "1"
"Timestamp" "1700000000"
}
}
""".trimIndent()
assertEquals("Player", SteamLibraryFolders.savedAccount(users))
assertEquals("Old One", SteamLibraryFolders.savedAccount(users.replace("\"MostRecent\"\t\t\"1\"", "\"MostRecent\"\t\t\"0\"").replace("\"1700000000\"", "\"1500000000\"")))
assertEquals("player", SteamLibraryFolders.savedAccount(users.replace("\"PersonaName\"\t\t\"Player\"", "\"PersonaName\"\t\t\"\"").replace("\"Old One\"", "\"\"").replace("\"1600000000\"", "\"1\"")))
assertNull(SteamLibraryFolders.savedAccount(users.replace("\"RememberPassword\"\t\t\"1\"", "\"RememberPassword\"\t\t\"0\"")))
assertNull(SteamLibraryFolders.savedAccount(""))
}
@Test fun theClientLanguageComesFromTheRegistry() {
val registry = """
"Registry"
{
"HKCU"
{
"Software"
{
"Valve"
{
"Steam"
{
"AutoLoginUser" "player"
"language" "german"
}
}
}
}
}
""".trimIndent()
assertEquals("german", SteamLibraryFolders.language(registry))
assertNull(SteamLibraryFolders.language("\"Registry\" { \"HKCU\" { } }"))
}
@Test fun enginePhasesShowAsDownloadStages() {
assertEquals(DownloadStage.DOWNLOAD, SteamLibraryFolders.stageOf("download"))
assertEquals(DownloadStage.DOWNLOAD, SteamLibraryFolders.stageOf("Downloading"))
assertEquals(DownloadStage.DOWNLOAD, SteamLibraryFolders.stageOf(""))
assertEquals(DownloadStage.VERIFY, SteamLibraryFolders.stageOf("verify"))
assertEquals(DownloadStage.MANIFEST, SteamLibraryFolders.stageOf("manifests"))
assertEquals(DownloadStage.MANIFEST, SteamLibraryFolders.stageOf("cleanup"))
assertEquals(DownloadStage.INSTALL, SteamLibraryFolders.stageOf("register"))
assertEquals(DownloadStage.INSTALL, SteamLibraryFolders.stageOf("finalize"))
}
}