diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index c15996d8f..d286cce1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -875,7 +875,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) } }, "components-restore").start() } - private var pendingGameLink: String? = null + private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null private var gameLinkReading = false private var gameLinkTried = false private var gameSyncFolder by mutableStateOf(null) @@ -947,12 +947,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) val copy = Intent(request) Thread({ - val id = GameLaunchIntent.read(this, copy) + val game = GameLaunchIntent.read(this, copy) ui.post { if (intent === request && !isDestroyed) { gameLinkReading = false - pendingGameLink = id - if (id == null) { + pendingGameLink = game + if (game == null) { syncDualPanel() android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show() } else { @@ -1202,16 +1202,16 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun handleGameLink(games: List, scanned: Boolean = true) { if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return - val id = pendingGameLink ?: return - if (!scanned && games.none { it.gameIdString == id }) return + val request = pendingGameLink ?: return + val game = request.find(games, byTitle = scanned) + if (!scanned && game == null) return gameLinkTried = true ui.postDelayed({ if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel() }, LINK_PANEL_MS) - val game = games.firstOrNull { it.gameIdString == id } val link = intent fun consume() { - if (intent !== link || pendingGameLink != id) return + if (intent !== link || pendingGameLink !== request) return pendingGameLink = null link.data = null link.action = Intent.ACTION_MAIN @@ -1220,7 +1220,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (game == null) { consume() syncDualPanel() - android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show() + android.widget.Toast.makeText(this, + if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing, + android.widget.Toast.LENGTH_LONG).show() } else launchGame(game, returnHome = true, onSettled = ::consume) } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt index 63b5f6b4d..3ab892892 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt @@ -2,6 +2,9 @@ package com.droiddeck.launcher.frontend import android.content.Context import android.content.Intent +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.OpenableColumns import android.util.AtomicFile import com.droiddeck.launcher.R import androidx.core.util.readText @@ -13,27 +16,65 @@ import java.io.InputStream object GameFiles { const val EXTENSION = "steam" - private const val MAX_BYTES = 128 + private const val MAX_BYTES = 4096 private const val MAX_NAME_BYTES = 200 private const val INVENTORY = ".droiddeck-sync.json" private const val FORMAT = "droiddeck-game-files-v1" - fun readIntent(context: Context, request: Intent): String? = runCatching { + fun readIntent(context: Context, request: Intent): GameRequest? = runCatching { if (request.action != Intent.ACTION_VIEW) return null val uri = request.data ?: return null - GameLaunchLink.parse(uri.toString())?.let { return it } + GameRequest.link(uri.toString())?.let { return GameRequest(it) } + val name = displayName(context, uri) + val extension = name?.substringAfterLast('.', "").orEmpty() + if (extension.lowercase(java.util.Locale.ROOT) in GameRequest.PROGRAMS) { + val program = localFile(context, uri)?.takeIf { it.isFile } ?: return null + return GameRequest(title = name?.substringBeforeLast('.'), program = program.canonicalFile) + } val stream = when (uri.scheme) { - "content" -> context.contentResolver.openInputStream(uri) - "file" -> { - if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) return null - File(uri.path ?: return null).inputStream() - } - null -> File(uri.toString()).takeIf { it.isAbsolute }?.inputStream() + "content" -> runCatching { context.contentResolver.openInputStream(uri) }.getOrNull() + ?: localFile(context, uri)?.takeIf { it.isFile }?.inputStream() + "file", null -> localFile(context, uri)?.inputStream() else -> null } ?: return null - stream.use(::read) + val id = stream.use(::read) ?: return null + GameRequest(id, GameRequest.sourceOf(extension), name?.substringBeforeLast('.')) }.getOrNull() + private fun displayName(context: Context, uri: Uri): String? = when (uri.scheme) { + "content" -> runCatching { + context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> + if (c.moveToFirst()) c.getString(0) else null + } + }.getOrNull() ?: uri.lastPathSegment?.substringAfterLast('/')?.substringAfterLast(':') + "file" -> uri.path?.let { File(it).name } + null -> File(uri.toString()).name + else -> null + }?.takeIf { it.isNotEmpty() } + + private fun localFile(context: Context, uri: Uri): File? = when (uri.scheme) { + "file" -> { + if (!uri.authority.isNullOrEmpty() || uri.query != null || uri.fragment != null) null + else uri.path?.let(::File) + } + null -> File(uri.toString()).takeIf { it.isAbsolute } + "content" -> storageDocument(context, uri) ?: uri.pathSegments.let { parts -> + (0..1).asSequence().map { File("/" + parts.drop(it).joinToString("/")) }.firstOrNull { it.isFile } + } + else -> null + } + + // Frontends pass SAF document URIs or FileProvider URIs whose path mirrors shared storage. + private fun storageDocument(context: Context, uri: Uri): File? { + if (uri.authority != "com.android.externalstorage.documents" || !DocumentsContract.isDocumentUri(context, uri)) return null + val id = DocumentsContract.getDocumentId(uri) + val volume = id.substringBefore(':') + val path = id.substringAfter(':', "") + val root = if (volume.equals("primary", ignoreCase = true)) android.os.Environment.getExternalStorageDirectory() + else File("/storage", volume) + return File(root, path) + } + fun read(stream: InputStream): String? { val bytes = ByteArray(MAX_BYTES + 1) var count = 0 @@ -44,8 +85,7 @@ object GameFiles { count += n } if (count > MAX_BYTES) return null - val text = String(bytes, 0, count, Charsets.UTF_8).trim() - return text.takeIf(GameLaunchLink::validId) + return GameRequest.parse(String(bytes, 0, count, Charsets.UTF_8)) } fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String { @@ -61,7 +101,7 @@ object GameFiles { } val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" } val suffix = if (disambiguate) " (${game.gameIdString})" else "" - return "$title$suffix.$EXTENSION" + return "$title$suffix.${GameRequest.extension(game)}" } private fun contents(id: String): String { @@ -130,7 +170,7 @@ object GameFiles { } for (name in previous.keys()) { val id = previous.getString(name) - if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) { + if (!next.has(name) && ours(name) && GameLaunchLink.validId(id)) { val file = child(context, folder, name) if (matches(file, contents(id))) { val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) } @@ -141,6 +181,9 @@ object GameFiles { if (previous.toString() != next.toString()) write(inventory, JSONObject().put("format", FORMAT).put("games", next).toString()) } + private fun ours(name: String) = name.substringAfterLast('.', "").lowercase(java.util.Locale.ROOT) + .let { it == EXTENSION || it in GameRequest.extensions } + private fun inventoryOwns(context: Context, folder: File, record: JSONObject, file: File, id: String): Boolean { if (record.optString(file.name) == id) return true if (!file.exists()) return false diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt index 6f71475cf..3e5d4ae0d 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameLaunchIntent.kt @@ -11,22 +11,26 @@ object GameLaunchIntent { fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION - fun read(context: Context, intent: Intent): String? = when (intent.action) { + fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) { Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent) - ACTION, GAMENATIVE_ACTION -> readId(intent) + ACTION, GAMENATIVE_ACTION -> readExtras(intent) else -> null } @Suppress("DEPRECATION") - internal fun readId(intent: Intent): String? = runCatching { + internal fun readExtras(intent: Intent): GameRequest? = runCatching { if (intent.action != ACTION && intent.action != GAMENATIVE_ACTION) return null - val source = intent.extras?.get(EXTRA_GAME_SOURCE) - if (source != null && (source !is String || !source.equals("STEAM", ignoreCase = true))) return null + val source = when (val value = intent.extras?.get(EXTRA_GAME_SOURCE)) { + null -> Library.SOURCE_STEAM + is String -> GameRequest.sourceNamed(value) ?: return null + else -> return null + } val id = when (val value = intent.extras?.get(EXTRA_APP_ID)) { is Int -> value.takeIf { it > 0 }?.toString() + is Long -> value.takeIf { it != 0L }?.let(java.lang.Long::toUnsignedString) is String -> value.takeIf(GameLaunchLink::validId) else -> null - } - id + } ?: return null + GameRequest(id, source) }.getOrNull() } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt new file mode 100644 index 000000000..a6baf2d70 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRequest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.frontend + +import com.droiddeck.launcher.stores.Store +import java.io.File +import java.util.Locale + +class GameRequest( + val id: String? = null, + val source: String = Library.SOURCE_STEAM, + val title: String? = null, + val program: File? = null, +) { + fun find(games: List, byTitle: Boolean = true): Library.SteamGame? { + program?.let { return owner(games, it) } + val exact = id?.let { id -> games.firstOrNull { it.gameIdString == id } } + if (source == Library.SOURCE_STEAM) return exact ?: games.firstOrNull { it.appId > 0 && it.appId.toString() == id } + exact?.takeIf { it.source == source }?.let { return it } + id?.let { id -> games.firstOrNull { it.source == source && it.storeId == id } }?.let { return it } + if (!byTitle) return null + val key = title?.let(::titleKey)?.takeIf { it.isNotEmpty() } ?: return null + return games.firstOrNull { it.source == source && titleKey(it.name) == key } + } + + private fun owner(games: List, program: File): Library.SteamGame? { + val path = program.path + return games.mapNotNull { game -> + val folder = game.gameFiles ?: return@mapNotNull null + val dir = folder.absolutePath.takeIf { inside(path, it) } + ?: runCatching { folder.canonicalPath }.getOrNull()?.takeIf { inside(path, it) } + dir?.let { game to it.length } + }.maxByOrNull { it.second }?.first + } + + companion object { + val PROGRAMS = setOf("exe", "bat") + private const val CUSTOM_GAME = "CUSTOM_GAME" + private const val CUSTOM_EXTENSION = "pcgame" + private val DAIJISHOU = setOf("# Daijishou Player Template", "# DST") + private val daijishouId = Regex("""(?i)\[steamappid]\s*([0-9]+)""") + private val steamLink = Regex("steam://rungameid/([1-9][0-9]{0,19})") + + val extensions: Set = Store.entries.map { it.id }.toSet() + CUSTOM_EXTENSION + + fun extension(game: Library.SteamGame): String = Store.byId(game.source)?.id ?: GameFiles.EXTENSION + + fun sourceNamed(value: String): String? = when { + value.equals(Library.SOURCE_STEAM, ignoreCase = true) -> Library.SOURCE_STEAM + value.equals(CUSTOM_GAME, ignoreCase = true) -> Library.ADDED + else -> Store.entries.firstOrNull { it.name.equals(value, ignoreCase = true) }?.id + } + + fun sourceOf(extension: String): String = when (val ext = extension.lowercase(Locale.ROOT)) { + CUSTOM_EXTENSION -> Library.ADDED + else -> Store.byId(ext)?.id ?: Library.SOURCE_STEAM + } + + fun link(text: String): String? = text.takeIf(GameLaunchLink::validId) + ?: GameLaunchLink.parse(text) + ?: steamLink.matchEntire(text)?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId) + + fun parse(text: String): String? { + link(text.trim())?.let { return it } + val lines = text.lines().map { it.trim() }.filter { it.isNotEmpty() } + val header = lines.firstOrNull() ?: return null + return when { + DAIJISHOU.any { header.equals(it, ignoreCase = true) } -> lines.firstNotNullOfOrNull { daijishouId.matchEntire(it) } + ?.groupValues?.get(1)?.takeIf(GameLaunchLink::validId) + header.equals("[InternetShortcut]", ignoreCase = true) -> lines.firstOrNull { it.startsWith("URL=", ignoreCase = true) } + ?.substring(4)?.trim()?.takeIf { !GameLaunchLink.validId(it) }?.let(::link) + else -> null + } + } + + internal fun titleKey(name: String): String = name.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() } + + private fun inside(path: String, dir: String) = path.startsWith(dir.trimEnd(File.separatorChar) + File.separator) + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4187e13cd..2fcff59c4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1774,6 +1774,7 @@ This launcher cannot add shortcuts. Use Copy launch link instead. Invalid game launch link. This game is no longer in your DroidDeck library. + Add this game to DroidDeck first, then start it from your frontend. Stop the current session before launching a Steam game. Could not send the game to Steam. Try launching it again. %1$s is a UWP app. This runtime has no Windows app-model host to start it. diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt index bcae5c8fe..b5f58de79 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt @@ -33,27 +33,64 @@ class GameFilesTest { assertEquals("18446744073709551615", file.readText()) val context = RuntimeEnvironment.getApplication() listOf(Uri.fromFile(file), Uri.parse(file.path)).forEach { uri -> - assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))) + assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id) } val provider = LaunchFileProvider(file) provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend" }) ShadowContentResolver.registerProviderInternal("frontend", provider) val uri = Uri.parse("content://frontend/document/opaque%3A42") - assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))) + assertEquals("18446744073709551615", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, uri))?.id) + } + + @Test fun readsIdsFromEveryFrontendFileFormat() { + listOf("8400\n", "steam://rungameid/8400", "droiddeck://game/8400", + "# Daijishou Player Template\n[steamappid] 8400\n", "# DST\n[steamappid] 8400\n", + "[InternetShortcut]\r\nIconIndex=0\r\nURL=steam://rungameid/8400\r\nIconFile=C:\\steam.ico\r\n").forEach { value -> + assertEquals(value, "8400", GameFiles.read(ByteArrayInputStream(value.toByteArray()))) + } } @Test fun rejectsCommandsMalformedIdsLargeFilesAndUnsupportedIntents() { - listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400", - "8400\n8401", "droiddeck://game/8400", "droiddeck://game/8400?command=quit", "x".repeat(129)).forEach { value -> + listOf("", "0", "01", "-1", "18446744073709551616", "steam://rungameid/8400?x=1", "steam://run/8400", + "8400\n8401", "droiddeck://game/8400?command=quit", "x".repeat(4097), + "[InternetShortcut]\nURL=https://example.com/8400", "[InternetShortcut]\nURL=8400", + "# Daijishou Player Template\n[epicappid] 8400").forEach { value -> assertNull(value, GameFiles.read(ByteArrayInputStream(value.toByteArray()))) } - assertEquals("8400", GameFiles.read(ByteArrayInputStream("8400\n".toByteArray()))) val context = RuntimeEnvironment.getApplication() assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_SEND, Uri.parse("droiddeck://game/8400")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com/8400.steam")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("file://remote/game.steam")))) assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(tmp.root, "missing.steam"))))) - assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("droiddeck://game/8400")))?.id) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("8400")))?.id) + assertEquals("8400", GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.parse("steam://rungameid/8400")))?.id) + } + + @Test fun storeFilesCarryTheirSourceAndTitle() { + val context = RuntimeEnvironment.getApplication() + val epic = File(tmp.root, "Hades II.epic").apply { writeText("17") } + val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(epic)))!! + assertEquals("epic", request.source) + assertEquals("Hades II", request.title) + val daijishou = File(tmp.root, "Portal.steamappid").apply { writeText("# Daijishou Player Template\n[steamappid] 400\n") } + val steam = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(daijishou)))!! + assertEquals(Library.SOURCE_STEAM, steam.source) + assertEquals("400", steam.id) + } + + @Test fun programFilesArriveAsPathsNotContents() { + val context = RuntimeEnvironment.getApplication() + val exe = File(tmp.newFolder("Game"), "Game.exe").apply { writeBytes(byteArrayOf(0x4d, 0x5a)) } + val request = GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(exe)))!! + assertEquals(exe.canonicalFile, request.program) + assertNull(request.id) + val provider = LaunchFileProvider(exe) + provider.attachInfo(context, android.content.pm.ProviderInfo().apply { authority = "frontend.files" }) + ShadowContentResolver.registerProviderInternal("frontend.files", provider) + val shared = Uri.parse("content://frontend.files/root" + exe.canonicalPath) + assertEquals(exe.canonicalFile, GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, shared))?.program) + assertNull(GameFiles.readIntent(context, Intent(Intent.ACTION_VIEW, Uri.fromFile(File(exe.parentFile, "Missing.exe"))))) } @Test fun exportsGameIconBeforeCapsuleAndPreservesCustomArtwork() { @@ -185,13 +222,32 @@ class GameFilesTest { val file = GameFiles.export(app, folder, game("620", "Portal 2")) assertEquals("Portal 2.steam", file.name) assertEquals("620", file.readText()) - assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))) + assertEquals("620", GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))?.id) val added = Library.SteamGame(1, "Added Game", null, Library.ADDED, -1L) val addedFile = GameFiles.export(app, folder, added) assertEquals("Added Game.steam", addedFile.name) assertEquals("18446744073709551615", addedFile.readText()) } + @Test fun storeGamesExportUnderTheirStoreExtensionAndLaunchBack() { + val folder = tmp.newFolder() + val forza = Library.SteamGame(1, "Forza Horizon 5", null, Library.ADDED, -7L, source = "xbox", storeId = "9NKX70BBCDRN") + val steam = File(folder, "Forza Horizon 5.steam").apply { writeText(forza.gameIdString) } + File(folder, ".droiddeck-sync.json").writeText( + """{"format":"droiddeck-game-files-v1","games":{"Forza Horizon 5.steam":"${forza.gameIdString}"}}""") + GameFiles.sync(app, folder, listOf(forza)) + val file = File(folder, "Forza Horizon 5.xbox") + assertEquals(forza.gameIdString, file.readText()) + assertFalse(steam.exists()) + val request = GameFiles.readIntent(RuntimeEnvironment.getApplication(), Intent(Intent.ACTION_VIEW, Uri.fromFile(file)))!! + assertEquals("xbox", request.source) + assertSame(forza, request.find(listOf(game("620", "Portal 2"), forza))) + listOf("ubisoft", "ea", "rockstar", "battlenet", "itch", "gamejolt", "epic", "gog", "amazon").forEach { store -> + val game = Library.SteamGame(1, "Game", null, Library.ADDED, -8L, source = store) + assertEquals("Game.$store", GameFiles.filename(game)) + } + } + @Test fun steamSyncDisambiguatesTitlesAndPreservesEditedAndForeignFiles() { val folder = tmp.newFolder() val first = game("620", "A/B") diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt index 002085daf..63b6807c0 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameLaunchIntentTest.kt @@ -14,29 +14,41 @@ class GameLaunchIntentTest { @Test fun acceptsNativeAndExplicitlyRetargetedGameNativeProfiles() { listOf(GameLaunchIntent.ACTION, "app.gamenative.LAUNCH_GAME").forEach { action -> val request = Intent(action).putExtra("app_id", 620).putExtra("game_source", "STEAM") - assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)) - assertEquals("8400", GameLaunchIntent.readId(Intent(action).putExtra("app_id", "8400"))) - assertEquals("620", GameLaunchIntent.readId(request.putExtra("game_source", "steam"))) + assertEquals("620", GameLaunchIntent.read(RuntimeEnvironment.getApplication(), request)?.id) + assertEquals("8400", GameLaunchIntent.readExtras(Intent(action).putExtra("app_id", "8400"))?.id) + assertEquals("620", GameLaunchIntent.readExtras(request.putExtra("game_source", "steam"))?.id) } } - @Test fun stringIdsPreserveUnsignedShortcutIds() { + @Test fun longAndStringIdsPreserveUnsignedShortcutIds() { listOf("2147483648", "18446744073709551615").forEach { id -> - assertEquals(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) + assertEquals(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))?.id) + } + assertEquals("620", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))?.id) + assertEquals("18446744073709551615", GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1L))?.id) + } + + @Test fun storeSourcesComeThroughForLibraryMatching() { + mapOf("EPIC" to "epic", "gog" to "gog", "AMAZON" to "amazon", "XBOX" to "xbox", "UBISOFT" to "ubisoft", + "EA" to "ea", "ROCKSTAR" to "rockstar", "BATTLENET" to "battlenet", "ITCH" to "itch", "GAMEJOLT" to "gamejolt", + "CUSTOM_GAME" to Library.ADDED).forEach { (name, source) -> + val request = GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 1207658924).putExtra("game_source", name)) + assertEquals(name, source, request?.source) + assertEquals("1207658924", request?.id) } } @Test fun rejectsUnsupportedSourcesTypesAndIdsWithoutFallingBackToData() { listOf("", "0", "01", "+1", "-1", "18446744073709551616", "620\n", "steam://rungameid/620").forEach { id -> - assertNull(id, GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) + assertNull(id, GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", id))) } - listOf("EPIC", "GOG", "CUSTOM_GAME", "", "STEAM ").forEach { source -> - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source))) + listOf("STADIA", "", "STEAM ", "added").forEach { source -> + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", source))) } - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620L))) - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1))) - assertNull(GameLaunchIntent.readId(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1))) - assertNull(GameLaunchIntent.readId(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 0L))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", -1))) + assertNull(GameLaunchIntent.readExtras(Intent(GameLaunchIntent.ACTION).putExtra("app_id", 620).putExtra("game_source", 1))) + assertNull(GameLaunchIntent.readExtras(Intent(Intent.ACTION_MAIN).putExtra("app_id", 620))) assertNull(GameLaunchIntent.read(RuntimeEnvironment.getApplication(), Intent(GameLaunchIntent.ACTION, android.net.Uri.parse("droiddeck://game/620")))) } @@ -44,7 +56,7 @@ class GameLaunchIntentTest { @Test fun deepLinksStillAcceptUnsignedShortcutIds() { val context = RuntimeEnvironment.getApplication() assertEquals("18446744073709551615", GameLaunchIntent.read(context, - Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))) + Intent(Intent.ACTION_VIEW, android.net.Uri.parse("droiddeck://game/18446744073709551615")))?.id) assertFalse(GameLaunchIntent.accepts(Intent.ACTION_SEND)) assertTrue(GameLaunchIntent.accepts(GameLaunchIntent.ACTION)) } diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt new file mode 100644 index 000000000..d7a50728c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameRequestTest.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.frontend + +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class GameRequestTest { + @get:Rule val tmp = TemporaryFolder() + + private fun game(id: Long, name: String, source: String = Library.SOURCE_STEAM, storeId: String? = null, files: File? = null, + library: String = "internal", appId: Int = id.toInt()) = + Library.SteamGame(appId, name, null, library, id, gameFiles = files, source = source, storeId = storeId) + + @Test fun steamIdsMatchTheGameIdOrAnAddedGamesSteamAppId() { + val portal = game(400, "Portal") + val added = game(-1L, "Celeste", library = Library.ADDED, source = Library.ADDED, appId = 504230) + val games = listOf(portal, added) + assertSame(portal, GameRequest("400").find(games)) + assertSame(added, GameRequest("18446744073709551615").find(games)) + assertSame(added, GameRequest("504230").find(games)) + assertNull(GameRequest("401").find(games)) + } + + @Test fun titleMatchingWaitsForTheFullScan() { + val cached = game(-2L, "Example", source = "gog", storeId = "111") + assertNull(GameRequest("222", "gog", "Example").find(listOf(cached), byTitle = false)) + assertSame(cached, GameRequest("222", "gog", "Example").find(listOf(cached))) + assertSame(cached, GameRequest("111", "gog", "Other").find(listOf(cached), byTitle = false)) + } + + @Test fun gogMatchesItsProductIdThenTitle() { + val witcher = game(-2L, "The Witcher 3: Wild Hunt", source = "gog", storeId = "1207664663") + val games = listOf(game(292030, "The Witcher 3: Wild Hunt"), witcher) + assertSame(witcher, GameRequest("1207664663", "gog").find(games)) + assertSame(witcher, GameRequest("5", "gog", "The Witcher 3 Wild Hunt").find(games)) + } + + @Test fun storesWithAppLocalIdsMatchByTitleWithinTheirStore() { + val hades = game(-3L, "Hades II", source = "epic", storeId = "Ixion") + val custom = game(-4L, "Cave Story+", library = Library.ADDED, source = Library.ADDED) + val games = listOf(game(1145350, "Hades II"), hades, custom) + assertSame(hades, GameRequest("17", "epic", "hades ii").find(games)) + assertSame(custom, GameRequest("9", Library.ADDED, "Cave Story").find(games)) + assertNull(GameRequest("17", "epic").find(games)) + assertNull(GameRequest("17", "amazon", "Hades II").find(games)) + } + + @Test fun programsStartTheDeepestGameThatOwnsThem() { + val root = tmp.newFolder("Games") + val suite = File(root, "Suite").apply { mkdirs() } + val inner = File(suite, "Episode 2").apply { mkdirs() } + val outer = game(-5L, "Suite", files = suite) + val episode = game(-6L, "Episode 2", files = inner) + val games = listOf(outer, episode) + assertSame(episode, GameRequest(program = File(inner, "bin/game.exe")).find(games)) + assertSame(outer, GameRequest(program = File(suite, "launcher.exe")).find(games)) + assertNull(GameRequest(program = File(root, "Other/other.exe")).find(games)) + assertNull(GameRequest(program = File(root, "Suite2/game.exe")).find(games)) + } +} diff --git a/docs/frontend-integration.md b/docs/frontend-integration.md new file mode 100644 index 000000000..d60a4cbbf --- /dev/null +++ b/docs/frontend-integration.md @@ -0,0 +1,88 @@ +# Launching DroidDeck games from a frontend + +Frontends such as ES-DE, Daijisho, Cocoon, Beacon and iiSU can start any game in the DroidDeck library. DroidDeck can be the default player for a whole Windows or PC platform folder: it reads every file format listed below and starts the matching library game. + +## Launch target + +Send an explicit intent to `com.droiddeck.launcher/com.droiddeck.launcher.FrontEndActivity`. This activity is never disabled. `.MainActivity` is a launcher-icon alias and is disabled when the user picks the light icon, so do not target it. + +The release variants use other package names but the same activity class and action: + +| Build | Package | +| --- | --- | +| Standard | `com.droiddeck.launcher` | +| PUBG | `com.tencent.ig` | +| AnTuTu | `com.antutu.benchmark.full` | +| Ludashi | `com.ludashi.benchmark` | + +An intent that names only the action `com.droiddeck.launcher.LAUNCH_GAME`, without a package, reaches whichever build is installed. + +## Intents + +**Action with extras**, the same shape other PC game apps use: + +```sh +am start -n com.droiddeck.launcher/.FrontEndActivity \ + -a com.droiddeck.launcher.LAUNCH_GAME --es app_id 620 --es game_source STEAM +``` + +- `app_id`: an int, long or decimal string. DroidDeck ids for added and store games are unsigned 64-bit, so send them with `--es`, not `--ei`. `--el` only accepts the signed 64-bit form, so an id above 9223372036854775807 such as `18446744073709551615` must be sent as `-1`, or better with `--es`. +- `game_source` (optional, default `STEAM`): `STEAM`, `EPIC`, `GOG`, `AMAZON`, `XBOX`, `UBISOFT`, `EA`, `ROCKSTAR`, `BATTLENET`, `ITCH`, `GAMEJOLT` or `CUSTOM_GAME`. + +**View a link or a file**: + +```sh +am start -n com.droiddeck.launcher/.FrontEndActivity -a android.intent.action.VIEW -d 'droiddeck://game/620' +am start -n com.droiddeck.launcher/.FrontEndActivity -a android.intent.action.VIEW -d '' +``` + +The data can be `droiddeck://game/`, `steam://rungameid/`, a bare id, or a `file://`, `content://` or absolute path to one of the files below. + +## Game files + +**Frontend files** (the sync button at the top of the Games page) keeps a chosen folder filled with one file per installed game, named after the game, holding only its DroidDeck id. Steam and added games use `.steam`; store games use the store's own extension. + +| Extension | Games | +| --- | --- | +| `.steam` | Steam games and games added from a folder | +| `.epic` `.gog` `.amazon` | Epic, GOG and Amazon games | +| `.xbox` `.ubisoft` `.ea` `.rockstar` `.battlenet` `.itch` `.gamejolt` | Xbox, Ubisoft, EA, Rockstar, Battle.net, itch.io and Game Jolt games | + +DroidDeck also reads files written by other apps: + +- A bare id in any of the extensions above, plus `.pcgame` and `.droiddeck`. For `.epic`, `.gog`, `.amazon` and `.pcgame`, an id DroidDeck does not know falls back to the store's product id (GOG) and then to the game's title from the file name. +- Daijisho player templates (`.steamappid`) with a `[steamappid] ` line. +- Windows Internet Shortcuts (`.url`) whose `URL=` is `steam://rungameid/`. +- `.exe` and `.bat` files. DroidDeck starts the library game whose folder holds the program. A program that belongs to no library game is not run; add its folder in DroidDeck first. + +## Frontend examples + +**ES-DE** (`ES-DE/custom_systems/es_find_rules.xml`): + +```xml + + + com.droiddeck.launcher/com.droiddeck.launcher.FrontEndActivity + + +``` + +and in `es_systems.xml` for the `steam` or `windows` system: + +```xml +%EMULATOR_DROIDDECK% %ACTION%=android.intent.action.VIEW %DATA%=%ROMSAF% +``` + +`%ROMPROVIDER%` works as well. DroidDeck reads the file through the URI, or through the shared-storage path behind it when the URI grants no access. + +**Daijisho** player: + +```text +-n com.droiddeck.launcher/.FrontEndActivity -a android.intent.action.VIEW -d {file.uri} +``` + +**Frontends that inject the file's contents** can send `-a com.droiddeck.launcher.LAUNCH_GAME --es app_id ` or `-a android.intent.action.VIEW -d `. + +## What happens on launch + +DroidDeck matches the request against a fresh library scan and starts the game the same way its own Play button does, through Steam or without Steam as the game is set up. A cold launch boots the session straight into the game. A warm launch hands the game to the running Steam session. When the game exits, DroidDeck returns to the frontend that started it. diff --git a/docs/testing/game-launcher-shortcuts.md b/docs/testing/game-launcher-shortcuts.md index f806f2a8f..833386d9e 100644 --- a/docs/testing/game-launcher-shortcuts.md +++ b/docs/testing/game-launcher-shortcuts.md @@ -6,21 +6,21 @@ DroidDeck exposes installed Steam titles and AddedGames through a canonical laun droiddeck://game/ ``` -The ID is the value accepted by `steam://rungameid/`, including an AddedGames shortcut ID that occupies the unsigned 64-bit range. The app accepts only the exact URI form and only after a fresh library scan finds that game. The deep link does not accept paths, Steam URLs, extra parameters, leading zeroes, or IDs outside the unsigned 64-bit range. Frontends that scan files can instead pass a file or content URI for an exported `.droiddeck` launch file. +The ID is the value accepted by `steam://rungameid/`, including an AddedGames shortcut ID that occupies the unsigned 64-bit range. The app accepts only the exact URI form and only after a fresh library scan finds that game. The deep link does not accept paths, Steam URLs, extra parameters, leading zeroes, or IDs outside the unsigned 64-bit range. Frontends that scan files can instead pass a file or content URI for an exported game file. See [Launching DroidDeck games from a frontend](../frontend-integration.md) for every accepted intent and file format. Each game page's **Shortcut** menu offers **Add to home screen** through Android's pinned-shortcut request and **Copy launch link**. When a launcher invokes `ACTION_CREATE_SHORTCUT`, DroidDeck opens the Games page and returns Android's standard shortcut result after the user chooses a game. With the debug app installed, exercise link routing with an installed game ID from the current library: ```sh -adb shell am start -n com.droiddeck.launcher/.MainActivity \ +adb shell am start -n com.droiddeck.launcher/.FrontEndActivity \ -a android.intent.action.VIEW -d 'droiddeck://game/620' ``` Open the standard shortcut picker with: ```sh -adb shell am start -n com.droiddeck.launcher/.MainActivity \ +adb shell am start -n com.droiddeck.launcher/.FrontEndActivity \ -a android.intent.action.CREATE_SHORTCUT ```