diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index 2c402e2cd5..a000d2ec87 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -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}/") } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index fc103d55e0..46f18a2547 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 69d4ea65ee..42e0083877 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt index 4c83872b84..31a57029a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstallRoot.kt @@ -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//`. + * 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 diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt index dcc770c4b6..6c436a4ee8 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreInstalls.kt @@ -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}\"") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 6be1397a72..1372a8d316 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt index 9d39de3ffa..18d679461a 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/amazon/AmazonBackend.kt @@ -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…") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt index a92ef0d5e8..a9dd628148 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadModels.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt index 4a80396dde..4f303e3e76 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/download/DownloadQueue.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt index 244ce3fd98..16c7dcf035 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicBackend.kt @@ -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() } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java index 734a813abf..8cd7324f95 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicDownloadManager.java @@ -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) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt index 67300c10a7..4745226022 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt @@ -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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt index 98f75312ec..95aef70af4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt @@ -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) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt index 5dc5633675..7ec1941108 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt @@ -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, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt new file mode 100644 index 0000000000..9ffda1e732 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresInstallDialog.kt @@ -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) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index c2d94b2c6f..cebbb69b80 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -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) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 62de30485f..c7c3042ab7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -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> diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt new file mode 100644 index 0000000000..9a98da7a85 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreInstallRootTest.kt @@ -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) + } +} diff --git a/docs/development/stores.md b/docs/development/stores.md index bb337ea064..7407578c88 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -13,12 +13,20 @@ the rest of the app, and the on-disk contract that makes a store game an ordinar .droiddeck-epic-code one-shot, written right before an Epic launch, read and deleted by the .bat ``` -`<Games storage>` is the second Steam library when one is chosen (the SD card's app folder, bound -into the session at `/mnt/droiddeck-sd`), else the runtime's own tree, where the folder is -`/root/Games/Stores` (`StoreInstallRoot`). Both roots are always scanned; new installs go to the -current one. `<Store>` is `GOG`, `Epic` or `Amazon`; `<title>` is the title with unsafe characters -dropped, at most 60 characters (`StoreInstallRoot.folderName`), chosen once and read back from the -sidecar afterwards. +The default root is the app's internal storage - the runtime's tree, `/root/Games/Stores`, no bind +needed - whatever the session's Game storage setting says. When a card the app may write is in the +device (`GameStorage.options`), Install asks "Install to" (internal / the card, free space shown; +the last pick is only the dialog's default). A card's root is `<card app folder>/Games`; when the +card is the Steam library the library's bind (`/mnt/droiddeck-sd`) already covers it, otherwise +`SessionService` binds the root at `/mnt/droiddeck-stores/<volume uuid>`, so a shortcut's guest +path - and its appid - is the same from one session to the next. Every root is +scanned (`StoreInstallRoot.roots`): internal, every card, and the Steam library's `Games` folder for +installs an earlier build put there. `<Store>` is `GOG`, `Epic` or `Amazon`; `<title>` is the title +with unsafe characters dropped, at most 60 characters (`StoreInstallRoot.folderName`), chosen once; +a rerun (repair, update) lands on the folder whose sidecar carries the game's id, wherever it is. +An Epic install on a card keeps its in-flight chunks in `cacheDir/stores/epic/<id>/` (the Java pool +and the assembly honour it; the native engine's own cache stays `<installDir>/.chunks` until its +contract takes a cache path); the scratch folder is removed on cancel and uninstall. ## The sidecar @@ -88,6 +96,7 @@ each manager runs its Java fetch loop. | Open a store on: Library · Store | `SessionPrefs.storesOpenTab` (library) | the chip row's cog, Setup › Stores | | Download speed tier | `SessionPrefs.gameStoresSpeedTier` (fast) | the cog, Setup › Stores, Downloads | | Downloads at a time | `SessionPrefs.gameStoresParallel` (1) | Downloads | +| Install to (last pick, dialog default only) | `SessionPrefs.storesInstallTarget` | the Install dialog | Credentials live in `filesDir/stores/<store>/credentials.json` only (`StoreAccounts`); store URLs are logged through `StoreLog.redactUrl`, which drops the query string where the signed tokens live. diff --git a/docs/progress-log.md b/docs/progress-log.md index 5f4057a29b..e295fe9e84 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -103,6 +103,17 @@ without it and Setup says "Stores engine not built"). from it, for all three stores; the engine's own figure stays in its log lines, and the detail line under the bar has it stripped. The tier and downloads-at-a-time controls sit on one compact row with a single caption, on the Downloads page and in the cog's popup. +- **Install location (user decision):** the default is the app's internal storage for all three + stores, whatever the session's Game storage says. With a card in the device, Install asks + "Install to" first (internal / the card, free space per target, pad-focusable, last pick as the + default only). A card that is not the Steam library gets a bind of its own in the session + (`/mnt/droiddeck-stores/<volume uuid>`; the library's own bind covers a library card, so installs + already registered there keep their appid); every root is scanned and uninstall works for + either. The Downloads + row shows where a game is going, with its art as a small 16:9 thumbnail; the game page names the + place. Epic installs on a card keep their in-flight chunks in the app's cache (Java pool and + assembly; the native engine's `chunkCacheDir` parameter is not in JNI.md yet and is wired the + moment it lands), cleaned on cancel and uninstall. - **Device-proven on the AYANEO Pocket FIT, 2026-10-08 (GOG):** sign-in, the library (33 owned), DOOM I Enhanced installed through the GOG engine to the SD Games root, shown in Games with the GOG chip and real art, registered as a non-Steam game in the Steam client (grid art present), and