Stores: installs go to internal storage by default, a card is offered at Install time

The default root for all three stores is the app's own storage, whatever
the session's Game storage says. With a card in the device, Install asks
where first - internal or the card, free space per target, pad-focusable,
last pick only as the dialog's default. A card that is not the Steam
library is bound at its own fixed place, so a game's guest path and appid
hold from one session to the next; a library card keeps the library's
bind and the installs already registered there keep their appid. Every
root is scanned and uninstall works for either.

The Downloads row carries the game's art as a small thumbnail and names
where the game is going; the game page names where it went. Epic installs
on a card keep their in-flight chunks in the app's cache (the Java pool
and the assembly; the engine's own cache stays beside the game until its
contract takes a cache path), cleaned on cancel and uninstall.
This commit is contained in:
The412Banner committed 2026-10-08 19:24:12 -04:00
1 parent 2d70341214
commit 6ca3052eb7
20 files changed
+358 -57

No files matched your search

@@ -76,6 +76,9 @@ object AddedGames {
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { roms ->
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
}
// A store root on a card has a bind of its own, before the library rule: the same folder
// keeps the same guest path (and appid) whether or not that card is also the Steam library.
StoreInstallRoot.externalGuestPath(context, host)?.let { return it }
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
}
@@ -78,6 +78,13 @@ object SessionPrefs {
const val STORES_OPEN_LIBRARY = "library"
const val STORES_OPEN_STORE = "store"
/** The install root picked last time the Stores asked where (a StoreInstallRoot target's path); only the dialog's default, never a silent choice. */
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
fun setStoresInstallTarget(context: Context, path: String) {
prefs(context).edit().putString("storesInstallTarget", path).apply()
}
/** How many store downloads run at once, 1..3; one by default (a single download already fills the link). */
fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3)
@@ -894,6 +894,15 @@ class SessionService : Service() {
Log.w(TAG, "added games: ${root.host} is not a readable folder this session")
}
}
// Store games installed on a card: each card's Games root at its own fixed place, so the
// shortcuts point somewhere whether or not the card is also the Steam library.
for ((host, guest) in com.droiddeck.launcher.stores.StoreInstallRoot.externalRoots(this)) {
if (host.isDirectory && host.canRead()) {
File(LinuxRuntime.rootDir(this), guest.removePrefix("/")).mkdirs()
binds.add(host.path + ":" + guest)
Log.i(TAG, "store games: $host -> $guest")
}
}
// Folders of added scripts outside internal storage, where their links point.
binds.addAll(com.droiddeck.launcher.runtime.UserApps.binds(this))
val roms = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }?.let { File(it) }
@@ -1,34 +1,96 @@
package com.droiddeck.launcher.stores
import android.content.Context
import android.os.StatFs
import android.os.storage.StorageManager
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import java.io.File
import java.util.zip.CRC32
/**
* Where store games are installed: `<Games storage>/Games/<Store>/<title>`.
* Where store games are installed: `<root>/<Store>/<title>`.
*
* The Games storage is the second Steam library when one is chosen (an SD card's app folder,
* bound into the session at /mnt/droiddeck-sd), else the runtime's own tree, where the folder
* sits at /root/Games/Stores - beside the user's added folders, which are bound under /root/Games
* one by one. Both roots are always scanned, so a game installed on the card before the setting
* changed stays in the library; new installs go to [installRoot].
* The default root is the app's own internal storage - the runtime's tree, where the folder sits at
* /root/Games/Stores and needs no bind - whatever the session's Game storage setting says. An SD
* card the app may write (its app folder, `GameStorage.options`) is offered as a second root at
* Install time and never chosen silently. Every root is scanned, so a game stays in the library
* wherever it went. A card that is the Steam library is already bound (`/mnt/droiddeck-sd`); any
* other card's root is bound at a fixed place of its own (`/mnt/droiddeck-stores/<volume>`), so a
* shortcut's path - and with it its appid - stays the same from one session to the next.
*/
object StoreInstallRoot {
private const val INTERNAL = "root/Games/Stores"
private const val ON_LIBRARY = "Games"
private const val ON_VOLUME = "Games"
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
/** The folder a new install goes under (before the store's own folder). */
fun installRoot(context: Context): File =
GameStorage.effective(context)?.let { File(it.path, ON_LIBRARY) } ?: File(LinuxRuntime.rootDir(context), INTERNAL)
/** Every root that may hold store games, the current install root first. */
fun roots(context: Context): List<File> {
val internal = File(LinuxRuntime.rootDir(context), INTERNAL)
val library = GameStorage.effective(context)?.let { File(it.path, ON_LIBRARY) }
return listOfNotNull(library, internal).distinctBy { it.absolutePath }
/** One place a game can be installed: the folder, its name for the dialog, and whether it is a card. */
class Target(val root: File, val label: String, val removable: Boolean) {
val freeBytes: Long get() = try { StatFs((if (root.isDirectory) root else root.parentFile ?: root).path).availableBytes } catch (e: Exception) { 0L }
}
/** The internal root: always there, always the default. */
fun internalRoot(context: Context): File = File(LinuxRuntime.rootDir(context), INTERNAL)
/** The roots a game can go to right now: internal first, then every writable card. */
fun targets(context: Context): List<Target> {
val internal = Target(internalRoot(context), context.getString(com.droiddeck.launcher.R.string.games_internal), removable = false)
val cards = GameStorage.options(context).map { Target(File(it.path, ON_VOLUME), it.name, removable = true) }
return listOf(internal) + cards
}
/** The default root, when nothing asks: internal storage. */
fun installRoot(context: Context): File = internalRoot(context)
/** Every root that may hold store games: the internal one, every card's, and the Steam library's (older installs). */
fun roots(context: Context): List<File> {
val cards = GameStorage.options(context).map { File(it.path, ON_VOLUME) }
val library = GameStorage.effective(context)?.let { File(it.path, ON_VOLUME) }
return (listOf(internalRoot(context)) + cards + listOfNotNull(library)).distinctBy { it.absolutePath }
}
/**
* The card roots that need a bind of their own, with where the session sees them. A root under
* the Steam library is left out: the library's bind already covers it, and the games there keep
* the guest path (and appid) they were registered with.
*/
fun externalRoots(context: Context): List<Pair<File, String>> {
val library = GameStorage.effective(context)?.path
return roots(context)
.filter { !isInternal(context, it) && (library == null || !it.absolutePath.startsWith("$library/")) }
.map { it to guestFor(context, it) }
}
/** A card root's guest path, keyed on the volume (its UUID, else a hash of the path), so it is the same across sessions. */
private fun guestFor(context: Context, root: File): String {
val sm = context.getSystemService(StorageManager::class.java)
val uuid = runCatching { sm?.getStorageVolume(root)?.uuid }.getOrNull()?.takeIf { it.isNotBlank() }?.replace(Regex("[^A-Za-z0-9-]"), "")
val key = uuid ?: "%08x".format(CRC32().apply { update(root.absolutePath.toByteArray()) }.value)
return "$GUEST_EXTERNAL/$key"
}
fun isInternal(context: Context, root: File): Boolean = root.absolutePath == internalRoot(context).absolutePath
/** Where a host path under a card root appears inside the session, or null when it is not under one. */
fun externalGuestPath(context: Context, host: File): String? {
val path = host.absolutePath
for ((root, guest) in externalRoots(context)) {
val dir = root.absolutePath
if (path == dir) return guest
if (path.startsWith("$dir/")) return guest + "/" + path.removePrefix("$dir/")
}
return null
}
/** The target a game folder sits under, for the page and the Downloads row; internal when unknown. */
fun labelFor(context: Context, folder: File): String {
val path = folder.absolutePath
for (t in targets(context)) if (path.startsWith(t.root.absolutePath + "/")) return t.label
return context.getString(com.droiddeck.launcher.R.string.games_internal)
}
fun isRemovable(context: Context, folder: File): Boolean = !folder.absolutePath.startsWith(internalRoot(context).absolutePath + "/")
fun storeDir(root: File, store: Store): File = File(root, store.shortLabel)
/** The game folders under every root, by store: what AddedGames scans in addition to the user's folders. */
@@ -38,18 +100,25 @@ object StoreInstallRoot {
}
}
/** The folder a game installs into; an existing folder with this game's sidecar wins over a fresh name. */
fun folderFor(context: Context, store: Store, id: String, title: String): File {
for (root in roots(context)) {
val dir = storeDir(root, store)
/**
* The folder a game installs into under [root]; a folder with this game's sidecar anywhere wins
* over a fresh name, so a repair or an update lands on the existing install.
*/
fun folderFor(context: Context, store: Store, id: String, title: String, root: File = installRoot(context)): File {
for (r in roots(context)) {
val dir = storeDir(r, store)
dir.listFiles { f -> f.isDirectory }?.forEach { folder ->
val sidecar = StoreGameSidecar.read(folder)
if (sidecar != null && sidecar.store == store && sidecar.id == id) return folder
}
}
return File(storeDir(installRoot(context), store), folderName(title, id))
return File(storeDir(root, store), folderName(title, id))
}
/** A scratch folder in the app's cache for an install's in-flight pieces, when the install itself is on a card. */
fun scratchDir(context: Context, store: Store, id: String): File =
File(File(File(context.cacheDir, "stores"), store.id), id.replace(Regex("[^A-Za-z0-9._-]"), "_"))
/**
* A folder name from a store title: letters, digits and a few safe marks, single spaces, at most
* 60 characters; the store id when nothing printable is left. The name is the shortcut's folder
@@ -54,6 +54,8 @@ object StoreInstalls {
val app = context.applicationContext
val appId = AddedGames.scan(app).firstOrNull { it.folder.absolutePath == game.folder.absolutePath }?.appId
deleteTree(game.folder)
// The scratch cache an install on a card may have left in the app's cache.
deleteTree(StoreInstallRoot.scratchDir(app, game.sidecar.store, game.sidecar.id))
register(app)
if (appId != null) SteamLiveShortcuts.remove(app, appId)
StoresState.logLine("uninstalled \"${game.sidecar.title}\"")
@@ -115,8 +115,24 @@ object StoresState {
}, "stores-signout").start()
}
fun install(context: Context, item: CatalogItem) {
backends[item.store]?.install(context.applicationContext, item) ?: logLine("${item.store.label}: this build cannot install yet")
/** An install waiting for the user to say where: the page shows the choice while this is set. */
var pendingInstall by mutableStateOf<CatalogItem?>(null)
/**
* The way a page starts an install: with a card in the device the user is asked where (the
* dialog's default is last time's pick, never a silent choice); with none it goes to internal
* storage at once.
*/
fun requestInstall(context: Context, item: CatalogItem) {
val targets = StoreInstallRoot.targets(context)
if (targets.size > 1) pendingInstall = item else install(context, item, targets.first().root)
}
/** Starts an install into [root] (the internal root when null). */
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
val app = context.applicationContext
val target = root ?: StoreInstallRoot.installRoot(app)
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
}
/** Removes the game's folder and its shortcut, then [onDone] on the main thread. */
@@ -160,7 +176,8 @@ interface StoreBackend {
fun signOut(context: Context)
fun syncLibrary(context: Context, force: Boolean)
fun loadShelves(context: Context, force: Boolean)
fun install(context: Context, item: CatalogItem)
/** Queues an install of [item] under [root] (a StoreInstallRoot target). */
fun install(context: Context, item: CatalogItem, root: java.io.File)
/** The store's own records of the install, before the folder goes (the queue row, cached ids). */
fun uninstall(context: Context, game: InstalledStoreGame)
}
@@ -76,19 +76,19 @@ object AmazonBackend : StoreBackend {
if (!StoresState.library.containsKey(store)) syncLibrary(context, force)
}
override fun install(context: Context, item: CatalogItem) {
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
val entitlementId = item.extra["entitlementId"] ?: ""
if (entitlementId.isEmpty()) { StoresState.logLine("Amazon: \"${item.title}\" has no entitlement to download with"); return }
val game = AmazonGame().apply { productId = item.id; this.entitlementId = entitlementId; title = item.title; productSku = item.extra["sku"] ?: ""; heroUrl = item.imageUrl ?: ""; artUrl = item.tallImageUrl ?: "" }
DownloadQueue.enqueue(app, DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes)) { InstallJob(app, game, item) }
val folder = StoreInstallRoot.folderFor(app, Store.AMAZON, game.productId, game.title, root)
DownloadQueue.enqueue(app, DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))) { InstallJob(app, game, item, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
private class InstallJob(val app: Context, val game: AmazonGame, val item: CatalogItem) : DownloadQueue.DownloadJob {
private class InstallJob(val app: Context, val game: AmazonGame, val item: CatalogItem, val folder: File) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val folder: File = StoreInstallRoot.folderFor(app, Store.AMAZON, game.productId, game.title)
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
@@ -41,6 +41,8 @@ data class DownloadEntry(
/** When the entry reached a terminal state, for ordering and ageing out. */
val finishedAt: Long = 0L,
val startedAt: Long = 0L,
/** Where it is going: the install target's name ("Internal storage", the card's name). */
val location: String = "",
) {
val key: String get() = "${store.id}:$id"
val isActive: Boolean get() = state == DownloadState.QUEUED || state == DownloadState.RUNNING || state == DownloadState.PAUSED
@@ -45,7 +45,7 @@ object DownloadQueue {
}
/** "Downloading: data.pak 12.3 MB/s" → "Downloading: data.pak": the engine's burst rate is not shown twice. */
private fun stripSpeed(s: String): String = s.replace(Regex("\\s+\\S+ [KM]B/s\\s*$"), "").trimEnd()
private fun stripSpeed(s: String): String = s.replace(Regex("\\s+\\S+ [KMG]B/s\\s*$"), "").trimEnd()
/** How far back the shown speed looks: a few seconds, so the figure settles instead of following each file. */
private const val SPEED_WINDOW_MS = 3000.0
@@ -79,13 +79,14 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
return StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending))
}
override fun install(context: Context, item: CatalogItem) {
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
val namespace = item.extra["namespace"] ?: ""
val catalogItemId = item.extra["catalogItemId"] ?: ""
if (namespace.isEmpty() || catalogItemId.isEmpty()) { StoresState.logLine("Epic: \"${item.title}\" is not in your library"); return }
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes)
DownloadQueue.enqueue(app, entry) { InstallJob(app, item, namespace, catalogItemId) }
val folder = StoreInstallRoot.folderFor(app, Store.EPIC, item.id, item.title, root)
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
DownloadQueue.enqueue(app, entry) { InstallJob(app, item, namespace, catalogItemId, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
@@ -96,9 +97,12 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
return EpicAuthClient.getExchangeCode(token)
}
private class InstallJob(val app: Context, val item: CatalogItem, val namespace: String, val catalogItemId: String) : DownloadQueue.DownloadJob {
private class InstallJob(val app: Context, val item: CatalogItem, val namespace: String, val catalogItemId: String, val folder: File) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val folder: File = StoreInstallRoot.folderFor(app, Store.EPIC, item.id, item.title)
// On a card the in-flight chunks go to the app's cache instead: the card's write rate paces
// the whole install, and chunks are read back once at assembly. Internal installs keep the
// cache beside the game, as the engine's contract has it today.
private val scratch: File? = if (StoreInstallRoot.isRemovable(app, folder)) StoreInstallRoot.scratchDir(app, Store.EPIC, item.id) else null
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST, "Checking sign-in…")
@@ -107,7 +111,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
?: throw EpicDownloadManager.InstallException("The manifest could not be fetched")
val tags = EpicInstallTags.tagsForDevice()
var downloading = false
val result = EpicDownloadManager.install(app, manifestJson, folder.path, tags, cancelled, object : EpicDownloadManager.Callback {
val result = EpicDownloadManager.install(app, manifestJson, folder.path, scratch?.path ?: "", tags, cancelled, object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {
when {
message.startsWith("Writing") || message.startsWith("Complete") -> handle.stage(DownloadStage.INSTALL, message)
@@ -138,7 +142,7 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) Thread({ StoreInstalls.deleteTree(folder) }, "epic-cancel-clean").start()
if (deleteFiles) Thread({ StoreInstalls.deleteTree(folder); scratch?.let { StoreInstalls.deleteTree(it) } }, "epic-cancel-clean").start()
}
}
@@ -115,9 +115,11 @@ public final class EpicDownloadManager {
/**
* Installs the app the manifest API JSON describes into {@code installDir}. {@code installTags}
* null = every file. Returns null when cancelled; throws when it fails.
* null = every file. {@code chunkCacheDirPath} "" keeps the chunk cache beside the game
* ({@code <installDir>/.chunks}); a path puts it there instead - the app's cache when the game
* goes to a card. Returns null when cancelled; throws when it fails.
*/
public static Result install(Context ctx, String manifestApiJson, String installDirPath, List<String> installTags, AtomicBoolean cancel, Callback cb) throws InstallException {
public static Result install(Context ctx, String manifestApiJson, String installDirPath, String chunkCacheDirPath, List<String> installTags, AtomicBoolean cancel, Callback cb) throws InstallException {
try {
if (cancel.get()) return null;
cb.onProgress("Reading CDN list…", 0);
@@ -136,7 +138,12 @@ public final class EpicDownloadManager {
File installDir = new File(installDirPath);
installDir.mkdirs();
File chunkCacheDir = new File(installDir, ".chunks");
// The native engine keeps its cache beside the game (its contract names <installDir>/.chunks);
// the scratch path is honoured by the Java pool and the assembly. A path on a card and a
// native run therefore still cache on the card until the engine takes the parameter.
boolean scratch = chunkCacheDirPath != null && !chunkCacheDirPath.isEmpty();
File engineCacheDir = new File(installDir, ".chunks");
File chunkCacheDir = scratch ? new File(chunkCacheDirPath) : engineCacheDir;
chunkCacheDir.mkdirs();
List<FileInfo> selected = resolveInstallFiles(manifest, installTags);
@@ -183,6 +190,7 @@ public final class EpicDownloadManager {
completedBytes, completedCount, lastSpeedMs, lastSpeedBytes, speedBps);
if (r.started) {
javaPool = false;
chunkCacheDir = engineCacheDir;
if (r.cancelled) return null;
if (!r.success) { cb.onLog("epic: engine failed: " + r.error); failCount.incrementAndGet(); }
} else cb.onLog("epic: engine not started (" + r.error + "); using the built-in pool");
@@ -190,11 +198,12 @@ public final class EpicDownloadManager {
if (javaPool) {
cb.onLog("epic: engine=built-in (8 threads)");
ExecutorService pool = Executors.newFixedThreadPool(8);
final File poolCacheDir = chunkCacheDir;
for (ChunkInfo chunk : needed) {
final ChunkInfo fc = chunk;
pool.submit(() -> {
if (cancel.get()) return;
File cached = new File(chunkCacheDir, fc.guidStr());
File cached = new File(poolCacheDir, fc.guidStr());
if (!cached.exists() && !downloadChunkStreaming(fc, manifest.chunkDir, cdnUrls, cached)) {
cb.onLog("FAIL chunk=" + fc.guidStr());
failCount.incrementAndGet();
@@ -239,7 +248,8 @@ public final class EpicDownloadManager {
}
doneFiles++;
}
deleteDir(chunkCacheDir);
deleteDir(engineCacheDir);
if (scratch) deleteDir(new File(chunkCacheDirPath));
cb.onProgress("Complete", 100);
return new Result(manifest.launchExe, manifest.buildVersion, planned);
} catch (InstallException e) {
@@ -65,19 +65,19 @@ object GogBackend : StoreBackend {
return com.droiddeck.launcher.stores.StoreShelves(mark(s.whatsNew), mark(s.deals), mark(s.free), mark(s.trending))
}
override fun install(context: Context, item: CatalogItem) {
override fun install(context: Context, item: CatalogItem, root: File) {
val app = context.applicationContext
val game = GogGame(item.id, item.title, item.imageUrl ?: "", item.description, item.developer, item.tags, 2, item.tallImageUrl)
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes)
DownloadQueue.enqueue(app, entry) { InstallJob(app, game, item) }
val folder = StoreInstallRoot.folderFor(app, Store.GOG, game.gameId, game.title, root)
val entry = DownloadEntry(store, item.id, item.title, cover = item.imageUrl, bytesTotal = item.sizeBytes, location = StoreInstallRoot.labelFor(app, folder))
DownloadQueue.enqueue(app, entry) { InstallJob(app, game, item, folder) }
}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
/** One GOG install, as the queue runs it. */
private class InstallJob(val app: Context, val game: GogGame, val item: CatalogItem) : DownloadQueue.DownloadJob {
private class InstallJob(val app: Context, val game: GogGame, val item: CatalogItem, val folder: File) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private val folder: File = StoreInstallRoot.folderFor(app, Store.GOG, game.gameId, game.title)
override fun run(handle: DownloadQueue.JobHandle): String? {
handle.stage(DownloadStage.MANIFEST)
@@ -65,8 +65,10 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.5f to colors.background.copy(alpha = 0.55f), 1f to Color.Transparent)))
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp)) {
// An install names where it went (internal storage, the card), a download where it is going.
val state = when {
installed != null -> stringResource(R.string.stores_eyebrow_installed)
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
else -> stringResource(R.string.stores_eyebrow_store)
}
@@ -93,7 +95,7 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
}
item?.owned == true -> PrimaryButton(
if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), main = true,
) { StoresState.install(ctx, item) }
) { StoresState.requestInstall(ctx, item) }
item != null && item.isFree -> PrimaryButton(stringResource(R.string.stores_get_free), main = true) { openStoreUrl(ctx, item) }
item != null -> PrimaryButton(if (item.hasPrice && item.finalPrice.isNotBlank()) stringResource(R.string.stores_buy_price, item.finalPrice) else stringResource(R.string.stores_view_on, store.shortLabel), main = true) { openStoreUrl(ctx, item) }
}
@@ -8,8 +8,10 @@ import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
@@ -34,6 +36,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
@@ -83,12 +86,18 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface).border(1.dp, pal.line, Shape12).padding(horizontal = 14.dp, vertical = 10.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
// The game's art, small and fixed, so the row stays one line tall on a narrow page.
CardArt(CatalogItem(d.store, d.id, d.name, d.cover), Modifier.width(96.dp).height(54.dp).clip(RoundedCornerShape(6.dp)))
Column(modifier = Modifier.weight(1f)) {
Text(d.name, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
SourceChip(d.store.id, small = true, modifier = Modifier.padding(top = 2.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 2.dp)) {
SourceChip(d.store.id, small = true)
if (d.location.isNotBlank()) Text(d.location, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
Stages(d)
if (!LocalNarrowPane.current) Stages(d)
}
if (LocalNarrowPane.current) Stages(d)
ProgressBarThin(
if (d.state == DownloadState.INSTALLED) 1f else d.fraction, paused = d.state == DownloadState.PAUSED,
verify = d.stage == DownloadStage.VERIFY, height = 8.dp, done = d.state == DownloadState.INSTALLED,
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.SdCard
import androidx.compose.material.icons.outlined.Smartphone
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.formatBytes
/**
* "Install to": internal storage or a card, each with its free space, asked only when a card is
* there. The row picked last time starts focused, so a pad confirms the usual place with one press;
* nothing is chosen for the user.
*/
@Composable
internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val targets = remember { StoreInstallRoot.targets(ctx) }
val remembered = remember { SessionPrefs.storesInstallTarget(ctx) }
val defaultIndex = targets.indexOfFirst { it.root.absolutePath == remembered }.coerceAtLeast(0)
val focus = remember { List(targets.size) { FocusRequester() } }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { focus[defaultIndex] } }
AppDialog(shown, close, "installWhere", wide = false) {
DialogHeader(item.title, stringResource(R.string.stores_install_where))
Rise(1) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
targets.forEachIndexed { i, t ->
TargetRow(
label = t.label, free = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
removable = t.removable, focus = focus[i],
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresState.install(ctx, item, t.root)
close()
}
}
Text(stringResource(R.string.stores_install_where_note), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
Rise(2) { Actions { SecondaryButton(stringResource(R.string.common_cancel), onClick = close) } }
}
}
@Composable
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, onPick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).focusRequester(focus).clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f))
.glideBorder(hot, Shape12, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onPick)
.controllerConfirm(onClick = onPick)
.padding(horizontal = 14.dp, vertical = 10.dp),
) {
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground)
Column(Modifier.weight(1f)) {
Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
Text(free, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
Text(stringResource(R.string.stores_install), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
}
}
@@ -151,6 +151,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier
}
}
if (settings) StoresSettingsDialog(s, a) { settings = false }
StoresState.pendingInstall?.let { item -> InstallWhereDialog(item) { StoresState.pendingInstall = null } }
}
// ---- the chip row -------------------------------------------------------------------------------
@@ -460,7 +461,7 @@ private fun GameCard(item: CatalogItem, store: Store, s: FrontEndState, a: Front
ProgressBarThin(download.fraction, paused = download.state == DownloadState.PAUSED, verify = download.stage == DownloadStage.VERIFY)
CardButton(downloadLabel(download.state, download.stage, download.percent), primary = false) { }
}
item.owned -> CardButton(if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), primary = true) { StoresState.install(ctx, item) }
item.owned -> CardButton(if (item.sizeBytes > 0) stringResource(R.string.stores_install_size, formatBytes(item.sizeBytes)) else stringResource(R.string.stores_install), primary = true) { StoresState.requestInstall(ctx, item) }
item.isFree -> CardButton(stringResource(R.string.stores_get_free), primary = true) { openStoreUrl(ctx, item) }
else -> CardButton(stringResource(R.string.stores_view_on, store.shortLabel), primary = false) { openStoreUrl(ctx, item) }
}
+3
View File
@@ -2074,6 +2074,9 @@
<string name="stores_download_manager">Download manager</string>
<string name="stores_tier_note">Caps how many chunks the engine fetches at once: Balanced 16 · Fast 32 · Max 96 in flight.</string>
<string name="stores_parallel">Downloads at a time</string>
<string name="stores_install_where">Install to</string>
<string name="stores_install_where_note">Internal storage is the default; a card streams more slowly. Your pick is remembered as the first choice next time.</string>
<string name="stores_target_free">%1$s free</string>
<string name="stores_download_controls_note">Balanced / Fast / Max pull harder from the store; 2–3 at a time share the link. Speed shown is the install rate.</string>
<string name="stores_parallel_note">One manager for all three stores; Steam\'s own downloads are unaffected.</string>
<string name="stores_engine_log">Engine log</string>
@@ -0,0 +1,44 @@
package com.droiddeck.launcher.stores
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
/** Where a store game goes: internal storage unless the user picks a card, and back to its own folder on a rerun. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class StoreInstallRootTest {
private val app get() = RuntimeEnvironment.getApplication()
@Test fun theDefaultRootIsInternalWhateverTheSteamLibrarySettingSays() {
val card = File(app.filesDir, "fake-card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
assertEquals(File(LinuxRuntime.rootDir(app), "root/Games/Stores").absolutePath, StoreInstallRoot.installRoot(app).absolutePath)
// The library's Games folder is still scanned, for installs an earlier build put there.
assertTrue(StoreInstallRoot.roots(app).any { it.absolutePath == File(card, "Games").absolutePath })
assertFalse(StoreInstallRoot.targets(app).first().removable)
}
@Test fun anExistingInstallWinsOverAFreshFolderUnderTheChosenRoot() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val existing = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "Old Name").apply { mkdirs() }
StoreGameSidecar(Store.GOG, "42", "New Name", "game.exe").write(existing)
val other = File(app.filesDir, "elsewhere/Games")
assertEquals(existing.absolutePath, StoreInstallRoot.folderFor(app, Store.GOG, "42", "New Name", other).absolutePath)
assertEquals(File(StoreInstallRoot.storeDir(other, Store.GOG), "Fresh").absolutePath, StoreInstallRoot.folderFor(app, Store.GOG, "7", "Fresh", other).absolutePath)
}
@Test fun theScratchCacheIsPrivateAndNamedSafely() {
val dir = StoreInstallRoot.scratchDir(app, Store.EPIC, "a/b:c")
assertTrue(dir.absolutePath.startsWith(app.cacheDir.absolutePath))
assertEquals("a_b_c", dir.name)
}
}