diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 41e8241ba..01e10a3de 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -279,7 +279,7 @@ class MainActivity : ComponentActivity() { if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path) addedGamesDirs = SessionPrefs.addedGamesDirs(this) - addedGamesArt = SessionPrefs.addedGamesArt(this) + addedGamesArt = SessionPrefs.addedGamesArt(this) refreshAddedGames() refresh() } @@ -289,15 +289,23 @@ class MainActivity : ComponentActivity() { val folder = pendingAddedGame ?: return@registerForActivityResult pendingAddedGame = null if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> - SessionPrefs.setAddedGameExe(this, folder, path) - refreshAddedGames() - refresh() + updateGameImport { com.droiddeck.launcher.frontend.AddedGames.changeExecutable(this, folder, path) } } } private var addedGamesDirs by mutableStateOf>(emptyList()) private var addedGamesArt by mutableStateOf(true) @Volatile private var artFetchRunning = false private var addedGames by mutableStateOf>(emptyList()) + + private fun updateGameImport(action: () -> Unit) { + Thread({ + val result = runCatching(action) + ui.post { + if (result.isSuccess) { refreshAddedGames(); refresh() } + else android.widget.Toast.makeText(this, R.string.games_import_failed, android.widget.Toast.LENGTH_LONG).show() + } + }, "game-import").start() + } private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> SessionPrefs.setRomsDir(this, path) @@ -437,6 +445,10 @@ class MainActivity : ComponentActivity() { return false } if (SessionState.running) { + if (game.importPending) { + android.widget.Toast.makeText(this, R.string.games_pending_steam, android.widget.Toast.LENGTH_LONG).show() + return false + } if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) { android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show() return true @@ -548,6 +560,17 @@ class MainActivity : ComponentActivity() { .putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true) }, onSteamGame = { g -> if (shortcutPicker) chooseGameShortcut(g) else launchGame(g) }, + onAddGame = { selection -> updateGameImport { com.droiddeck.launcher.frontend.AddedGames.add(this, selection) } }, + onImportGamesFolder = { folder -> updateGameImport { + SessionPrefs.setAddedGamesDirs(this, SessionPrefs.addedGamesDirs(this) + folder.path) + ui.post { addedGamesDirs = SessionPrefs.addedGamesDirs(this) } + } }, + onChangeGameExe = { game -> + game.gameFiles?.let { folder -> + pendingAddedGame = folder.path + pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), getString(R.string.games_change_exe), folder.path)) + } + }, onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) }, onExportGameFile = { g -> pickGameExport(g) }, onSyncGameFiles = { pickGameExport(null) }, @@ -1233,7 +1256,7 @@ class MainActivity : ComponentActivity() { onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, "Choose a folder of your own games", addedGamesDirs.lastOrNull())) }, onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() }, onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() }, - onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() }, + onAddedGameExe = { folder, path -> updateGameImport { com.droiddeck.launcher.frontend.AddedGames.changeExecutable(this, folder, path) } }, onPickAddedGameExe = { folder -> pendingAddedGame = folder pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), "Choose the game's .exe", folder)) @@ -1441,10 +1464,10 @@ class MainActivity : ComponentActivity() { // One update with the whole list: the wall places games by their position in it, so a // partial list first would shuffle every capsule when the rest arrived. LibraryCache // covers the wait. - val games = if (ready) Library.launchableGames(this) else emptyList() + val games = Library.launchableGames(this) val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } val all = games.distinctBy { it.gameId } - if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all) + com.droiddeck.launcher.frontend.LibraryCache.save(this, all) ui.post { if (scanGeneration == libraryScanGeneration) { steamGames = all 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 949602649..4fff7aed7 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -4,6 +4,7 @@ import android.content.Context import android.util.Log import com.droiddeck.launcher.runtime.LinuxRuntime import org.json.JSONObject +import org.json.JSONArray import com.droiddeck.launcher.session.GameStorage import com.droiddeck.launcher.session.SessionPrefs import java.io.File @@ -23,6 +24,7 @@ object AddedGames { val gameId: Long, val candidates: List, val steamAppId: Int? = null, + val nonSteam: Boolean = false, ) { fun folderName(): String = folder.name } @@ -30,6 +32,65 @@ object AddedGames { /** One Games folder and where the session sees it. */ class Root(val host: File, val guest: String) + data class Selection(val folder: File, val exe: File, val name: String = folder.name) + private data class Entry(val selection: Selection, val id: Long) + + private fun entries(context: Context): List = runCatching { + val array = JSONArray(SessionPrefs.addedGameEntries(context)) + List(array.length()) { i -> + val o = array.getJSONObject(i) + Entry(Selection(File(o.getString("folder")), File(o.getString("exe")), o.getString("name")), o.getLong("id")) + } + }.getOrDefault(emptyList()) + + /** Explicit executable choices keep their identity when their name or target changes. */ + fun add(context: Context, selection: Selection) { + require(selection.name.isNotBlank()) + require(selection.exe.isFile && selection.exe.extension.equals("exe", true)) + require(selection.folder.isDirectory && selection.exe.canonicalPath.startsWith(selection.folder.canonicalPath + "/")) + val old = entries(context) + val key = selection.folder.canonicalPath + val existing = old.firstOrNull { it.selection.folder.canonicalPath == key } + val scanned = scan(context).firstOrNull { it.folder.canonicalPath == key } + val id = existing?.id ?: scanned?.appId ?: (CRC32().apply { + update((selection.exe.canonicalPath + selection.name).toByteArray()) + }.value or 0x80000000L) + val array = JSONArray() + for (entry in old.filterNot { it.selection.folder.canonicalPath == key } + Entry(selection, id)) { + array.put(JSONObject().put("folder", entry.selection.folder.path).put("exe", entry.selection.exe.path) + .put("name", entry.selection.name).put("id", entry.id)) + } + SessionPrefs.setAddedGameEntries(context, array.toString()) + SessionPrefs.setAddedGameExe(context, selection.folder.path, selection.exe.path) + } + + fun changeExecutable(context: Context, folder: String, exe: String) { + val current = scan(context).firstOrNull { it.folder.path == folder } ?: return + require(File(exe).isFile && exe.endsWith(".exe", true)) + require(File(exe).canonicalPath.startsWith(current.folder.canonicalPath + "/")) + SessionPrefs.setAddedGameId(context, folder, current.appId) + SessionPrefs.setAddedGameExe(context, folder, exe) + } + + fun suggestedFolder(exe: File): File { + var folder = requireNotNull(exe.parentFile) + while (folder.name.lowercase() in setOf("bin", "binaries", "win64", "win32", "x64", "x86", "amd64")) { + folder = folder.parentFile ?: break + } + return folder + } + + /** Accept one game or a collection; preview only launchable games, not installers. */ + fun preview(folder: File): List { + val children = folder.listFiles().orEmpty() + if (children.any { it.isFile && it.extension.equals("exe", true) && !SKIP.matches(it.name) } || + children.any { it.isDirectory && (it.name.equals("Binaries", true) || it.name.equals("bin", true)) }) { + return candidates(folder).firstOrNull()?.let { listOf(Selection(folder, it)) } ?: emptyList() + } + return children.filter { it.isDirectory }.sortedBy { it.name.lowercase() } + .mapNotNull { game -> candidates(game).firstOrNull()?.let { Selection(game, it) } } + } + /** * The chosen folders with their guest paths: /root/Games/, or with a short hash of * the host path when two chosen folders share a name (so a folder's guest path, and with it @@ -38,11 +99,14 @@ object AddedGames { fun roots(context: Context): List { val hosts = SessionPrefs.addedGamesDirs(context).map { File(it) } val names = hosts.groupingBy { it.name.lowercase() }.eachCount() - return hosts.map { host -> + val collections = hosts.map { host -> val name = host.name.ifEmpty { "games" } val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name Root(host, "$GUEST_DIR/$guestName") } + return collections + entries(context).map { it.selection.folder }.distinctBy { it.canonicalPath } + .filter { folder -> collections.none { folder.canonicalPath == it.host.canonicalPath || folder.canonicalPath.startsWith(it.host.canonicalPath + "/") } } + .map { Root(it, "$GUEST_DIR/game-" + "%08x".format(CRC32().apply { update(it.canonicalPath.toByteArray()) }.value)) } } private val SKIP = Regex( @@ -55,19 +119,21 @@ object AddedGames { /** Where a host path appears inside the session, or null when the session cannot see it. */ fun guestPath(context: Context, host: File): String? { - val path = host.absolutePath + val path = host.canonicalPath // The Games folders are bound on their own, so a folder anywhere - an SD card, a USB // drive - works without being inside one of the other binds. for (root in roots(context)) { - val dir = root.host.absolutePath + val dir = root.host.canonicalPath if (path == dir) return root.guest if (path.startsWith("$dir/")) return root.guest + "/" + path.removePrefix("$dir/") } SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { roms -> - if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/") + val dir = File(roms).canonicalPath + if (path.startsWith("$dir/")) return "/root/ROMs/" + path.removePrefix("$dir/") } GameStorage.effective(context)?.let { lib -> - if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/") + val dir = File(lib.path).canonicalPath + if (path.startsWith("$dir/")) return "$LIBRARY/" + path.removePrefix("$dir/") } return null } @@ -75,11 +141,7 @@ object AddedGames { /** The .exe files a game folder offers, best first. */ fun candidates(folder: File): List { val exes = ArrayList() - val roots = listOf(folder) + (folder.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) - for (dir in roots) { - dir.listFiles { f -> f.isFile && f.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(f.name) } - ?.let { exes.addAll(it) } - } + folder.walkTopDown().maxDepth(4).filter { it.isFile && it.extension.equals("exe", true) && !SKIP.matches(it.name) }.forEach(exes::add) val key = folder.name.lowercase().replace(Regex("[^a-z0-9]"), "") return exes.sortedWith( compareByDescending { it.parentFile == folder } @@ -90,14 +152,20 @@ object AddedGames { fun scan(context: Context): List { val out = ArrayList() - val folders = roots(context).map { it.host } + listOfNotNull( + for (entry in entries(context)) { + val selection = entry.selection + scanGame(context, selection.folder, out, selection, entry.id) + } + val folders = SessionPrefs.addedGamesDirs(context).map(::File) + listOfNotNull( GameStorage.effective(context)?.let { File(it.path) }, GameStorage.effective(context)?.let { File(it.path, "steamapps/common") }, ) for (dir in folders.distinctBy { it.absolutePath }) { if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue } val steamInstalls = steamInstallDirs(dir) - for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) { + val selectedFolders = if (dir in SessionPrefs.addedGamesDirs(context).map(::File)) preview(dir).map { it.folder } + else dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList() + for (folder in selectedFolders) { if (folder.name.lowercase() in steamInstalls) continue scanGame(context, folder, out) } @@ -123,22 +191,23 @@ object AddedGames { private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE) - private fun scanGame(context: Context, folder: File, out: MutableList) { + private fun scanGame(context: Context, folder: File, out: MutableList, selection: Selection? = null, id: Long? = null) { run { val candidates = candidates(folder) val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } - val exe = chosen ?: candidates.firstOrNull() ?: return + val exe = if (selection != null) chosen ?: selection.exe.takeIf { it.isFile } ?: return + else chosen ?: candidates.firstOrNull() ?: return val guestExe = guestPath(context, exe) if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return } val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return - val name = folder.name + val name = selection?.name ?: folder.name // Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put. val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value - val appId = crc or 0x80000000L + val appId = id ?: SessionPrefs.addedGameId(context, folder.path).takeIf { it != 0L } ?: (crc or 0x80000000L) val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam") - val steamId = steamRoute(steamRoot, appId) + val steamId = if (selection != null) null else steamRoute(steamRoot, appId) out.add(Game(folder, name, exe, guestExe, guestDir, appId, - steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId)) + steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId, selection != null)) } } @@ -152,6 +221,14 @@ object AddedGames { .optInt(appId.toString()).takeIf { it > 0 } }.getOrNull() + fun pending(context: Context, game: Game): Boolean = runCatching { + val array = JSONArray(File(context.filesDir, "session/added-games.json").readText()) + (0 until array.length()).none { i -> + val o = array.getJSONObject(i) + o.getLong("appid") == game.appId && o.getString("exe") == game.guestExe && o.getString("name") == game.name + } + }.getOrDefault(true) + /** The list the session hands the runtime's shortcuts writer; one file per session start. */ fun writeListing(context: Context, games: List): File { val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() } @@ -159,6 +236,7 @@ object AddedGames { games.forEachIndexed { i, g -> if (i > 0) json.append(',') json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe)) + .append(",\"nonSteam\":").append(g.nonSteam) .append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir)) .append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId) // The art, as the session sees it: the app's cache is bound at its own path, a file in diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 9ccc0ff3b..e12bc5c5f 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -24,6 +24,7 @@ object Library { val hero: File? = null, val lastPlayed: Long = 0L, val gameFiles: File? = null, val protonPrefix: File? = null, val icon: File? = null, + val importPending: Boolean = false, ) { /** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */ val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId) @@ -147,6 +148,7 @@ object Library { hero = art.hero ?: art.header, gameFiles = g.folder, protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId), icon = art.icon?.takeIf { it.extension.lowercase() != "ico" }, + importPending = AddedGames.pending(context, g), ) } }).distinctBy { it.gameId } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/LibraryCache.kt b/app/src/main/java/com/droiddeck/launcher/frontend/LibraryCache.kt index 2add24685..d36e1606c 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/LibraryCache.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/LibraryCache.kt @@ -26,6 +26,7 @@ object LibraryCache { library = o.getString("library"), gameId = o.getLong("gameId"), hero = o.file("hero"), lastPlayed = o.optLong("lastPlayed"), gameFiles = o.file("gameFiles"), protonPrefix = o.file("protonPrefix"), icon = o.file("icon"), + importPending = o.optBoolean("importPending"), ) } }.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); emptyList() } @@ -36,6 +37,7 @@ object LibraryCache { for (g in games) array.put( JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId) .put("lastPlayed", g.lastPlayed).putFile("art", g.art).putFile("hero", g.hero) + .put("importPending", g.importPending) .putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon), ) val f = file(context) 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 220544604..8bf281cea 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -586,6 +586,18 @@ object SessionPrefs { prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply() } + fun addedGameEntries(context: Context): String = prefs(context).getString("addedGameEntries", "[]") ?: "[]" + + fun setAddedGameEntries(context: Context, entries: String) { + prefs(context).edit().putString("addedGameEntries", entries).apply() + } + + fun addedGameId(context: Context, folder: String): Long = prefs(context).getLong("addedId:$folder", 0L) + + fun setAddedGameId(context: Context, folder: String, id: Long) { + prefs(context).edit().putLong("addedId:$folder", id).apply() + } + /** Whether added games without art of their own get Steam's store art fetched for them. */ fun addedGamesArt(context: Context): Boolean = prefs(context).getBoolean("addedGamesArt", true) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddGameDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddGameDialog.kt new file mode 100644 index 000000000..c3298a91b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddGameDialog.kt @@ -0,0 +1,105 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.files.InAppFilePicker +import com.droiddeck.launcher.frontend.AddedGames +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File + +@Composable +internal fun AddGameDialog(onDismiss: () -> Unit, onAdd: (AddedGames.Selection) -> Unit, onImport: (File) -> Unit) { + val context = LocalContext.current + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + var executable by rememberSaveable { mutableStateOf(null) } + var gameFolder by rememberSaveable { mutableStateOf(null) } + var importFolder by rememberSaveable { mutableStateOf(null) } + var name by rememberSaveable { mutableStateOf("") } + var advanced by rememberSaveable { mutableStateOf(false) } + val pickExecutable = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedFile(result.data)?.let { exe -> + executable = exe.path + gameFolder = AddedGames.suggestedFolder(exe).path + name = AddedGames.suggestedFolder(exe).name.takeUnless { it.equals("Download", true) || it.equals("Downloads", true) } + ?: exe.nameWithoutExtension + importFolder = null + } + } + val pickImport = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedPath(result.data)?.let { + importFolder = it; executable = null + } + } + val pickGameFolder = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + if (result.resultCode == Activity.RESULT_OK) InAppFilePicker.pickedPath(result.data)?.let { gameFolder = it } + } + val preview by produceState?>(null, importFolder) { + value = null + value = importFolder?.let { withContext(Dispatchers.IO) { AddedGames.preview(File(it)) } } + } + val file = executable?.let(::File) + val folder = gameFolder?.let(::File) + val valid = file != null && folder != null && name.isNotBlank() && + file.canonicalPath.startsWith(folder.canonicalPath + "/") + AppDialog(shown, close, "addGame", wide = false) { + DialogHeader(stringResource(R.string.content_games), stringResource(R.string.games_add)) + PrimaryButton(stringResource(if (file == null) R.string.games_choose_exe else R.string.games_change_exe), + modifier = Modifier.fillMaxWidth()) { + pickExecutable.launch(InAppFilePicker.buildIntent(context, listOf("exe"), context.getString(R.string.games_choose_exe), gameFolder)) + } + SecondaryButton(stringResource(R.string.games_import_folder), modifier = Modifier.fillMaxWidth()) { + pickImport.launch(InAppFilePicker.buildDirIntent(context, context.getString(R.string.games_import_folder), importFolder)) + } + if (file != null) { + AdbTextField(name, { name = it.take(80) }, stringResource(R.string.add_app_name), KeyboardType.Text, ImeAction.Done, compact = true) + Text(file.path, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp) + SecondaryButton(stringResource(R.string.drawer_effects_advanced), compact = true) { advanced = !advanced } + if (advanced) ActionRow(stringResource(R.string.games_game_folder), gameFolder, stringResource(R.string.add_app_change_file)) { + pickGameFolder.launch(InAppFilePicker.buildDirIntent(context, context.getString(R.string.games_game_folder), gameFolder)) + } + } + if (importFolder != null) { + Text(importFolder!!, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp) + when { + preview == null -> Small(stringResource(R.string.games_scanning)) + preview!!.isEmpty() -> Note(stringResource(R.string.games_import_empty)) + else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (game in preview!!) { + Text(game.name, color = MaterialTheme.colorScheme.onBackground) + Small(game.exe.name) + } + } + } + } + DialogFooter( + note = if (file != null && !valid && name.isNotBlank()) stringResource(R.string.games_exe_outside_folder) else null, + confirm = if (importFolder != null) pluralStringResource(R.plurals.games_import_count, preview?.size ?: 0, preview?.size ?: 0) else stringResource(R.string.add_app_confirm), + enabled = if (importFolder != null) !preview.isNullOrEmpty() else valid, + onCancel = close, + onConfirm = { + if (importFolder != null) onImport(File(importFolder!!)) + else if (valid) onAdd(AddedGames.Selection(folder!!, file!!, name.trim())) + close() + }, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt index 33226c3b3..ba3003a48 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -30,12 +30,14 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Add import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import kotlinx.coroutines.flow.first import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -63,12 +65,28 @@ import com.droiddeck.launcher.frontend.Library */ @Composable internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) { + var adding by rememberSaveable { androidx.compose.runtime.mutableStateOf(false) } + if (adding) AddGameDialog(onDismiss = { adding = false }, onAdd = a.onAddGame, onImport = a.onImportGamesFolder) + Column(modifier) { + if (!s.shortcutPicker) { + Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.content_games), fontSize = 22.sp, fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.weight(1f)) + PrimaryButton(stringResource(R.string.games_add), enabled = !s.busy, compact = true, icon = Icons.Filled.Add) { adding = true } + } + } + GamesContent(s, a, selected, onSelect, Modifier.weight(1f).fillMaxWidth()) + } +} + +@Composable +private fun GamesContent(s: FrontEndState, a: FrontEndActions, selected: String, onSelect: (String) -> Unit, modifier: Modifier) { val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } } val narrow = LocalNarrowPane.current val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull() if (current == null) { Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) { - Rise(0) { PageHeader(stringResource(R.string.content_games)) } + if (s.shortcutPicker) Rise(0) { PageHeader(stringResource(R.string.content_games)) } Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) } if (!s.shortcutPicker) Rise(2) { Actions { PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp), onClick = a.onPlay) } @@ -135,8 +153,10 @@ private fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) { @Composable private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) { + if (g.importPending) Note(stringResource(R.string.games_pending_steam)) Actions { - PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) } + PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), + enabled = !s.busy && (s.shortcutPicker || !s.sessionRunning || !g.importPending), main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) } g.gameFiles?.takeIf { it.isDirectory }?.let { dir -> SecondaryButton(stringResource(R.string.games_files), compact = true) { a.onBrowseFiles(dir) } } @@ -146,6 +166,9 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio if (g.library == Library.ADDED) ManageSaves(g, dir, a) } if (!s.shortcutPicker) GameShortcutMenu(g, a) + if (!s.shortcutPicker && g.library == Library.ADDED && g.gameFiles != null) { + SecondaryButton(stringResource(R.string.games_change_exe), compact = true) { a.onChangeGameExe(g) } + } BusyChip(s) } } @@ -242,10 +265,6 @@ private fun GameList( verticalArrangement = Arrangement.spacedBy(2.dp), modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp), ) { - Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 6.dp, bottom = 10.dp)) { - Text(stringResource(R.string.content_games), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1) - Text(games.size.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp)) - } for (g in games) key(g.appId) { GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) }) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index d8f8b2275..10f33cd43 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -132,6 +132,9 @@ class FrontEndActions( val onPlay: () -> Unit, val onPlayDesktopUi: () -> Unit, val onSteamGame: (Library.SteamGame) -> Unit, + val onAddGame: (com.droiddeck.launcher.frontend.AddedGames.Selection) -> Unit = {}, + val onImportGamesFolder: (File) -> Unit = {}, + val onChangeGameExe: (Library.SteamGame) -> Unit = {}, val onGameShortcut: (Library.SteamGame) -> Unit = {}, val onExportGameFile: (Library.SteamGame) -> Unit = {}, val onSyncGameFiles: () -> Unit = {}, diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 19f259ef2..e2a2d5801 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -41,7 +41,7 @@ %1$s: engine failed %1$s: needs Lossless Scaling %1$s %2$s · starting - A folder with one subfolder per Windows game. Games you own on Steam use their Steam entries after Steam restarts; the rest become non-Steam shortcuts. + Choose one Windows game folder or a folder containing several games. Games you own on Steam use their Steam entries; the rest become non-Steam shortcuts. Adds a Steam library and scans it for Windows games. Owned games use their Steam entries; the rest become non-Steam shortcuts. Forget removes the shortcuts next session. Files stay on disk. Game environment @@ -892,6 +892,20 @@ Last played %1$s Internal storage Added game + Add game + Choose executable + Change executable + Import folder + Game folder + Scanning folder… + No game executables found. Choose an executable instead. + Choose a game folder that contains the executable. + + Import %1$d game + Import %1$d games + + Available next Steam start + Couldn’t add the game. Check the selected files and folder. The best pair for this GPU, kept up to date Pick a pair yourself Checking for drivers… diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameImportTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameImportTest.kt new file mode 100644 index 000000000..0bea59cf7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGameImportTest.kt @@ -0,0 +1,135 @@ +package com.droiddeck.launcher.frontend + +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.* +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class AddedGameImportTest { + @get:Rule val tmp = TemporaryFolder() + private val context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + SessionPrefs.setAddedGamesDirs(context, emptyList()) + SessionPrefs.setAddedGameEntries(context, "[]") + SessionPrefs.setGameStorage(context, SessionPrefs.GAME_STORAGE_OFF, "") + File(context.filesDir, "session/added-games.json").delete() + } + + private fun exe(folder: File, path: String) = File(folder, path).apply { parentFile!!.mkdirs(); writeText("game") } + + @Test fun previewsEitherOneGameOrACollectionAndSkipsInstallers() { + val collection = tmp.newFolder("Games") + val first = File(collection, "Example").apply { mkdirs() } + val second = File(collection, "Other").apply { mkdirs() } + exe(first, "Example.exe") + exe(first, "setup.exe") + exe(second, "Binaries/Win64/Other.exe") + exe(File(collection, "Installer"), "setup.exe") + assertEquals(listOf("Example", "Other"), AddedGames.preview(collection).map { it.name }) + assertEquals(first, AddedGames.preview(first).single().folder) + assertEquals(second, AddedGames.preview(second).single().folder) + } + + @Test fun individuallySelectedNestedExecutableIsBoundAndListedImmediately() { + val folder = tmp.newFolder("Example") + val file = exe(folder, "Binaries/Win64/Custom.exe") + assertEquals(folder, AddedGames.suggestedFolder(file)) + AddedGames.add(context, AddedGames.Selection(folder, file, "My mod")) + val game = AddedGames.scan(context).single() + assertEquals("My mod", game.name) + assertTrue(game.nonSteam) + assertNull(game.steamAppId) + assertEquals(folder, AddedGames.roots(context).single().host) + assertTrue(game.guestExe.endsWith("/Binaries/Win64/Custom.exe")) + assertTrue(AddedGames.pending(context, game)) + assertEquals("My mod", Library.launchableGames(context).single().name) + AddedGames.writeListing(context, listOf(game)) + assertFalse(AddedGames.pending(context, game)) + } + + @Test fun editingTargetAndNameKeepsShortcutIdentityAndMarksItPending() { + val folder = tmp.newFolder("Example") + val first = exe(folder, "Example.exe") + val alternate = exe(folder, "Mod.exe") + AddedGames.add(context, AddedGames.Selection(folder, first)) + val original = AddedGames.scan(context).single() + AddedGames.writeListing(context, listOf(original)) + AddedGames.changeExecutable(context, folder.path, alternate.path) + val edited = AddedGames.scan(context).single() + assertEquals(original.gameId, edited.gameId) + assertEquals(alternate, edited.exe) + assertTrue(AddedGames.pending(context, edited)) + AddedGames.add(context, AddedGames.Selection(folder, alternate, "Renamed mod")) + assertEquals(original.gameId, AddedGames.scan(context).single().gameId) + } + + @Test fun existingFolderImportsKeepTheirIdentityWhenChangingExecutable() { + val collection = tmp.newFolder("Games") + val folder = File(collection, "Example").apply { mkdirs() } + exe(folder, "Example.exe") + val alternate = exe(folder, "Mod.exe") + SessionPrefs.setAddedGamesDirs(context, listOf(collection.path)) + val original = AddedGames.scan(context).single() + AddedGames.changeExecutable(context, folder.path, alternate.path) + assertEquals(original.appId, AddedGames.scan(context).single().appId) + assertFalse(AddedGames.scan(context).single().nonSteam) + } + + @Test fun overlappingFolderAndIndividualImportsDoNotDuplicateAGame() { + val collection = tmp.newFolder("Games") + val folder = File(collection, "Example").apply { mkdirs() } + val file = exe(folder, "Example.exe") + AddedGames.add(context, AddedGames.Selection(folder, file)) + val original = AddedGames.scan(context).single().gameId + SessionPrefs.setAddedGamesDirs(context, listOf(collection.path)) + assertEquals(1, AddedGames.roots(context).size) + assertEquals(original, AddedGames.scan(context).single().gameId) + } + + @Test fun executableOutsideGameFolderIsRejectedWithoutChangingEntry() { + val folder = tmp.newFolder("Example") + val file = exe(folder, "Example.exe") + val outside = exe(tmp.newFolder("Other"), "Other.exe") + AddedGames.add(context, AddedGames.Selection(folder, file)) + assertThrows(IllegalArgumentException::class.java) { AddedGames.changeExecutable(context, folder.path, outside.path) } + assertEquals(file, AddedGames.scan(context).single().exe) + } + + @Test fun aSingleGameFolderCanBeImportedWithoutAParentCollection() { + val folder = tmp.newFolder("Example") + val file = exe(folder, "Example.exe") + SessionPrefs.setAddedGamesDirs(context, listOf(folder.path)) + assertEquals(file, AddedGames.scan(context).single().exe) + } + + @Test fun missingExplicitTargetDoesNotSilentlySwitchToAnotherExecutable() { + val folder = tmp.newFolder("Example") + val file = exe(folder, "Mod.exe") + exe(folder, "Example.exe") + AddedGames.add(context, AddedGames.Selection(folder, file)) + file.delete() + assertTrue(AddedGames.scan(context).isEmpty()) + } + + @Test fun storageAliasesShareTheExistingBindWithoutLosingTheManualGame() { + val collection = tmp.newFolder("Games") + val folder = File(collection, "Example").apply { mkdirs() } + val file = exe(folder, "Example.exe") + val alias = File(tmp.root, "Alias") + java.nio.file.Files.createSymbolicLink(alias.toPath(), collection.toPath()) + SessionPrefs.setAddedGamesDirs(context, listOf(alias.path)) + AddedGames.add(context, AddedGames.Selection(folder, file)) + assertEquals(1, AddedGames.roots(context).size) + assertTrue(AddedGames.scan(context).single().guestExe.endsWith("/Example/Example.exe")) + } +} diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 7967dd650..b1f3b3757 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -1,5 +1,17 @@ # Steam game imports +Games has a persistent **Add game** action, including for an empty library. Choose an +executable and confirm its name to add one non-Steam game, or use **Import folder** to +preview one game folder or a collection before importing. Folder imports retain Steam +ownership matching; explicit executable entries remain non-Steam shortcuts. Advanced +lets the user change the game folder when the inferred folder is not correct. + +Added entries appear in DroidDeck immediately. **Available next Steam start** means +the executable or name differs from the last session's import listing. A running +session cannot launch that pending entry; starting a new Steam session refreshes the +binds and shortcuts. **Change executable** on an added game's page keeps its shortcut +ID, so its Proton prefix and saves stay associated with the same game. + Second Library still registers the selected Steam library. It now also scans Windows executables in its immediate game subfolders and `steamapps/common`, using the same importer as Added Games. Existing Steam manifests are preserved. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index 50802187c..de6b1e3bd 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -74,6 +74,8 @@ def manifest_ids(steamapps, name): def identify(game): + if game.get("nonSteam"): + return None folder = Path(game["folder"]) steamapps = folder.parent.parent for library in ([steamapps] if folder.parent.name == "common" and steamapps.name == "steamapps" else []) + [folder.parent / WINNATIVE]: @@ -344,6 +346,9 @@ def route(steam_root, acct, games): owned, candidates, sources = {}, {}, {} shortcuts, routes = [], {} for game in games: + if game.get("nonSteam"): + shortcuts.append(game) + continue folder = game.get("folder", "") appid = candidates.get(folder, candidates.get(legacy_path(folder))) stamp = source_stamp(game) diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index 1639c6ada..f9c026e86 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -54,6 +54,17 @@ class ImportsTest(unittest.TestCase): self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve()) self.assertEqual(b'game', self.exe.read_bytes()) + def test_explicit_non_steam_executable_is_not_promoted_to_owned_title(self): + self.snapshot() + self.game['nonSteam'] = True + with patch.object(imports.urllib.request, 'urlopen') as search: + self.assertIsNone(imports.identify(self.game)) + search.assert_not_called() + games, routes = imports.route(self.steam, self.acct, [self.game]) + self.assertEqual([self.game], games) + self.assertEqual({}, routes) + self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists()) + def test_migrates_only_unchanged_legacy_import_manifests(self): self.snapshot() imports.route(self.steam, self.acct, [self.game])