diff --git a/README.md b/README.md index 066136eab3..71024514c4 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). - [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. +- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - `WriteProcessMemory` hooks fall back to `/proc//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. - Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim. diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index a843500c95..74cd5d6b45 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -163,6 +163,7 @@ struct layer { ARect geo_src, geo_dst; int geo_valid; int alloc_tier; + unsigned import_failed_fmts; uint64_t pool_modifier; int first_logged; int64_t drop_logged_ns; @@ -487,7 +488,8 @@ static const char *tier_name(int tier) { static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) { g_alloc_failed = 0; - while (l->alloc_tier <= TIER_LINEAR) { + const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u; + while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) { const int tier = l->alloc_tier; AHardwareBuffer_Desc d = { .width = (uint32_t)w, .height = (uint32_t)h, .layers = 1, @@ -560,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd); AHardwareBuffer_release(ahb); if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; } + l->import_failed_fmts |= fmt_bit; g_alloc_failed = 1; return -1; } diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 7184ff644f..61b2765c5b 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -1494,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) { } int vkp_can_import_ahb(void) { - return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import && + return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import && g_vk.GetAndroidHardwareBufferPropertiesANDROID; } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index b281adf4c2..a26bb5d81e 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -53,6 +53,8 @@ import com.droiddeck.launcher.session.SessionLogShare import com.droiddeck.launcher.session.SessionPaths import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SteamRepair +import com.droiddeck.launcher.session.LaunchCoordinator +import com.droiddeck.launcher.session.LaunchTicket import com.droiddeck.launcher.core.CpuCores import com.droiddeck.launcher.core.DownloadSource import com.droiddeck.launcher.core.PhantomProcessLimit @@ -215,7 +217,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var soundtracksLoaded by mutableStateOf(false) private var gameStoresSpeedTier by mutableStateOf("fast") private var navRequest by mutableStateOf(null) - private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong() + private val launchCoordinator = LaunchCoordinator() private var preparingGames by mutableStateOf(emptySet()) private var storesShowMature by mutableStateOf(false) private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first()) @@ -897,7 +899,6 @@ 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: com.droiddeck.launcher.frontend.GameRequest? = null private var gameLinkReading = false private var gameLinkTried = false private var gameSyncFolder by mutableStateOf(null) @@ -951,7 +952,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key request.data = null gameLinkReading = false - pendingGameLink = null syncDualPanel() return } @@ -964,7 +964,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet steamGames = emptyList() shortcutLibraryScanning = true } else shortcutLibraryScanning = false - pendingGameLink = null gameLinkReading = false gameLinkTried = false soundtrackLaunch = false @@ -977,6 +976,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return } if (GameLaunchIntent.accepts(request.action)) { + val ticket = launchCoordinator.beginLink(request) gameLinkReading = true com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) val copy = Intent(request) @@ -985,12 +985,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ui.post { if (intent === request && !isDestroyed) { gameLinkReading = false - pendingGameLink = game + if (!launchCoordinator.resolve(ticket, game)) { + clearGameLinkIntent(request) + syncDualPanel() + return@post + } if (game == null) { + launchCoordinator.consume(ticket) syncDualPanel() android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show() } else { - handleGameLink(steamGames, scanned = false) + handleGameLink(steamGames, scanned = false, ticket = ticket) refresh() } } @@ -999,37 +1004,66 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } - private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) { - val request = gameLaunchRequest.incrementAndGet() + private fun beginUiLaunch(): LaunchTicket { + val dropped = launchCoordinator.pendingLink() + val ticket = launchCoordinator.beginLaunch() + dropped?.let { if (intent === it.owner) clearGameLinkIntent(it.owner) } + return ticket + } + + private fun clearGameLinkIntent(link: Intent) { + link.data = null + link.action = Intent.ACTION_MAIN + link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + } + + private fun launchGame( + game: Library.SteamGame, + returnHome: Boolean = false, + onHandled: () -> Unit = {}, + onSettled: () -> Unit = {}, + ticket: LaunchTicket? = null, + ) { if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) if (pkgStage != null) { + ticket?.let(launchCoordinator::releaseHandling) onHandled() android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() return } + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + onHandled() + return + } val files = game.gameFiles if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) { - if (startGame(game, returnHome, onHandled)) onSettled() + if (startGame(game, returnHome, onHandled, request)) onSettled() + else launchCoordinator.releaseHandling(request) return } Thread({ val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files) ui.post { when { - request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled() + !launchCoordinator.isCurrent(request) || isFinishing || isDestroyed -> { + launchCoordinator.releaseHandling(request) + onHandled() + } refused -> { onHandled() android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show() onSettled() } - startGame(game, returnHome, onHandled) -> onSettled() + startGame(game, returnHome, onHandled, request) -> onSettled() + else -> launchCoordinator.releaseHandling(request) } } }, "xbox-app-model").start() } - private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean { - if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled) + private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit, ticket: LaunchTicket): Boolean { + if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled, ticket) onHandled() if (SessionState.running) { if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) { @@ -1074,15 +1108,34 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet .apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) } } - private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean { + private fun launchWithoutSteam( + game: Library.SteamGame, + returnHome: Boolean, + onHandled: () -> Unit = {}, + ticket: LaunchTicket? = null, + ): Boolean { + if (pkgStage != null) { + onHandled() + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return false + } val app = applicationContext + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + onHandled() + return false + } Thread({ val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added) ui.post { onHandled() - if (isDestroyed) return@post + if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { + launchCoordinator.releaseHandling(request) + return@post + } if (command == null) { + launchCoordinator.releaseHandling(request) android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show() return@post } @@ -1234,22 +1287,27 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet ui.postDelayed(poll, SESSION_SWITCH_POLL_MS) } - private fun handleGameLink(games: List, scanned: Boolean = true) { + private fun handleGameLink(games: List, scanned: Boolean = true, ticket: LaunchTicket? = null) { if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return - val request = pendingGameLink ?: return + val link = launchCoordinator.pendingLink() ?: return + if (ticket != null && link.ticket !== ticket) return + val request = link.request ?: return + if (launchCoordinator.isHandling(link.ticket)) return + if (ticket == null && !link.ownedBy(intent)) { + // A refresh may only finish the link that belongs to the intent this activity shows. + launchCoordinator.consume(link.ticket) + 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 link = intent + val linkIntent = link.owner fun consume() { - if (intent !== link || pendingGameLink !== request) return - pendingGameLink = null - link.data = null - link.action = Intent.ACTION_MAIN - link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + if (!launchCoordinator.consume(link.ticket)) return + if (intent === linkIntent) clearGameLinkIntent(linkIntent) } if (game == null) { consume() @@ -1257,7 +1315,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet 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) + } else { + if (!launchCoordinator.beginHandling(link.ticket)) return + launchGame(game, returnHome = true, onSettled = ::consume, ticket = link.ticket) + } } private fun chooseGameShortcut(game: Library.SteamGame) { @@ -1448,16 +1509,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet }, onStoreGame = { store, id -> val key = "${store.id}:$id" - if (key !in preparingGames) { + if (pkgStage != null) { + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + } else if (key !in preparingGames) { preparingGames = preparingGames + key + val ticket = beginUiLaunch() val app = applicationContext Thread({ val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull() runOnUiThread { - if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key) - else { + if (g != null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) { + prepareAndLaunch(g, key, ticket) + } else { preparingGames = preparingGames - key - if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show() + if (g == null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show() } } }, "store-play").start() @@ -1960,10 +2025,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) - gameLaunchRequest.incrementAndGet() + supersedeUncommittedLaunch() if (intent.action == SteamIntegration.ACTION_SETUP) { gameLinkReading = false - pendingGameLink = null syncDualPanel() readIntegrationIntent(intent) return @@ -1973,6 +2037,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet startSteamAtStartupIfEnabled() } + /** A replacement activity intent supersedes anything this activity has not dispatched yet. */ + private fun supersedeUncommittedLaunch() { + launchCoordinator.cancelAll() + } + private var soundtrackLaunch = false // A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own. @@ -2251,13 +2320,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java) else @Suppress("DEPRECATION") state.getParcelable(key) - private fun prepareAndLaunch(g: Library.SteamGame, key: String) { - val request = gameLaunchRequest.incrementAndGet() + private fun prepareAndLaunch(g: Library.SteamGame, key: String, ticket: LaunchTicket? = null) { + if (pkgStage != null) { + preparingGames = preparingGames - key + android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() + return + } + val request = ticket ?: beginUiLaunch() + if (!launchCoordinator.isCurrent(request)) { + preparingGames = preparingGames - key + return + } val done = { preparingGames = preparingGames - key } com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) { - if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch } + if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { done(); return@beforeLaunch } com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { - if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done) + if (launchCoordinator.isCurrent(request) && !isFinishing && !isDestroyed) launchGame(g, onHandled = done, ticket = request) else done() } } @@ -2267,7 +2345,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet // The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too. queuedLaunchRunner.destroy() triggerKeys.cancel() - gameLaunchRequest.incrementAndGet() + launchCoordinator.cancelAll() cancelCompatLaunch() updates.unregister() runCatching { unregisterReceiver(shortcutsInstallStatus) } @@ -2346,7 +2424,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId) } - private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried) + private fun launchPending(): Boolean = gameLinkReading || (launchCoordinator.hasPending() && !gameLinkTried) private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) { val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 98cabab689..7deb31a83e 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -875,9 +875,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde cornerTap = SessionPrefs.drawerCornerTap(this) applyOutputPacing() if (!SessionState.running) { - SessionState.followScreen = followChoice() - SessionState.followScale = followScale() + SessionState.followScales = SessionPrefs.followScales(this, displayMode(), + com.droiddeck.launcher.session.SessionDisplay.panelSize(this)) } + applyFollowChoice() applyFollowOrientation(resources.configuration) goFullscreen() volumeControlStream = android.media.AudioManager.STREAM_MUSIC @@ -2995,16 +2996,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this) - private fun followScale(): Float { - val mode = displayMode() - val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()) - return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f - } - - private fun followChoice(): Boolean { - val mode = displayMode() - return com.droiddeck.launcher.session.SessionDisplay.isFollow( - SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())) + private fun applyFollowChoice() { + val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first } + SessionState.followScreen = scale != null + SessionState.followScale = scale ?: 1f } private fun applyFollowOrientation(config: android.content.res.Configuration) { @@ -3018,6 +3013,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.setActivityDisplay(this, sessionActivityDisplayId) } cancelTouchGestures() + applyFollowChoice() applyFollowOrientation(newConfig) applyNotchInset() applyUnfoldedControls() diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index c847dbcdfc..a063f251da 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -28,7 +28,9 @@ object DeviceSupport { com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI")) } - fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists() + fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable()) + + internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady fun openDriverActive(context: Context): Boolean { if (adreno()) return false 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 e3c2d9a749..9968b1c1fd 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -31,6 +31,7 @@ object AddedGames { val exeUncertain: Boolean = false, val launchOptions: String = "", val single: Boolean = false, + val steamProgram: Boolean = true, ) { fun folderName(): String = folder.name } @@ -336,7 +337,10 @@ object AddedGames { val owner = ownerFolder(app, exe) if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) { single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { - if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path)) + if (guestPath(app, it.exe) != null) { + SessionPrefs.setAddedGameExe(app, owner.path, it.exe.path) + AddedExes.put(app, AddedExes.Entry(owner.path, it.exe.path)) + } return AddResult.Existing(it) } } @@ -442,9 +446,9 @@ object AddedGames { val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile } ?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile } val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return - val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) } + val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) } ?.launcherFile(folder)?.takeIf { it.isFile } - val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found + val launch = storeLauncher ?: found val foundGuest = guestPath(context, launch) if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return } val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name @@ -470,7 +474,13 @@ object AddedGames { val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() } ?: sidecarDir ?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return - val steamId = config?.let { steamRoute(it, appId) } + if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null && + guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) { + SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path) + } + val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true || + SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true + val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) } out.add(Game(folder, name, exe, guestExe, guestDir, appId, steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId, source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id, @@ -480,7 +490,7 @@ object AddedGames { sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context) else -> "" }, - single = single != null)) + single = single != null, steamProgram = steamProgram)) } } @@ -520,6 +530,11 @@ object AddedGames { return file.takeIf { inside && it.isFile } } + internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean { + val steam = unquote(record?.optJSONObject("steam")?.optString("Exe")) + return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/") + } + private fun unquote(value: String?): String = value.orEmpty().trim().trim('"') internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) { @@ -568,6 +583,7 @@ object AddedGames { .append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path)) if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions)) if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source)) + if (!g.steamProgram) json.append(",\"route\":false") val art = AddedGameArt.resolve(context, g) val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon) .mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } } diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java index d8aad76348..a26b1987fd 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/TurnipDriver.java @@ -308,8 +308,7 @@ public final class TurnipDriver { } } if (chosen != null && !chosen.isEmpty()) { - if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context)) - && SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen) + if (SessionPrefs.INSTANCE.displayDriverFromAuto(context) && gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) { Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system"); return null; diff --git a/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt b/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt new file mode 100644 index 0000000000..2170ab5030 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/AxisPacing.kt @@ -0,0 +1,39 @@ +package com.droiddeck.launcher.input + +internal class AxisPacing(private val intervalMs: Long) { + private var lastWriteAt = 0L + private var written = false + private var heldUntil = NOT_HELD + + fun dueAt(now: Long, axesOnly: Boolean): Long = + if (axesOnly && written && now - lastWriteAt < intervalMs) lastWriteAt + intervalMs else now + + fun wrote(at: Long) { + lastWriteAt = at + written = true + } + + fun hold(due: Long): Boolean { + if (heldUntil != NOT_HELD) return false + heldUntil = due + return true + } + + fun release(now: Long): Boolean { + if (heldUntil == NOT_HELD || now < heldUntil) return false + heldUntil = NOT_HELD + return true + } + + fun cancel(): Boolean { + if (heldUntil == NOT_HELD) return false + heldUntil = NOT_HELD + return true + } + + companion object { + private const val NOT_HELD = Long.MIN_VALUE + + @JvmStatic fun keepsMoving(before: Int, after: Int): Boolean = before == after || (before != 0 && after != 0) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java index 4675546d61..dc847e90ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java +++ b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java @@ -1,5 +1,9 @@ package com.droiddeck.launcher.input; +import android.os.Handler; +import android.os.HandlerThread; +import android.os.Process; +import android.os.SystemClock; import android.util.Log; import java.io.File; @@ -128,6 +132,16 @@ public class FakeInputWriter { private static final Object RING_LOCK = new Object(); private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS]; + private static final long AXIS_REPORT_INTERVAL_MS = 4; + + private static final class Pacing { + static final Handler HANDLER; + static { + HandlerThread thread = new HandlerThread("pad-pacing", Process.THREAD_PRIORITY_DISPLAY); + thread.start(); + HANDLER = new Handler(thread.getLooper()); + } + } static { System.loadLibrary("sdnative"); @@ -156,6 +170,9 @@ public class FakeInputWriter { private boolean hasChanges = false; private boolean pendingFullResend = false; private boolean forceResend = false; + private final AxisPacing axisPacing = new AxisPacing(AXIS_REPORT_INTERVAL_MS); + private final PadState pacedPad = new PadState(); + private final Runnable pacedWrite = this::writePacedPad; public FakeInputWriter(String fakeInputPath, int slot) { this.slot = slot; @@ -711,10 +728,12 @@ public class FakeInputWriter { } public synchronized void close() { + cancelPacedWrite(); isOpen = false; } public synchronized void reset() { + cancelPacedWrite(); if (!isOpen && !open()) return; @@ -822,6 +841,53 @@ public class FakeInputWriter { } public synchronized void writePad(PadState state) { + long now = SystemClock.uptimeMillis(); + long due = axisPacing.dueAt(now, !pendingFullResend && onlyAxesMove(state)); + if (due > now) { + pacedPad.copyFrom(state); + if (axisPacing.hold(due)) + Pacing.HANDLER.postAtTime(pacedWrite, due); + return; + } + cancelPacedWrite(); + writePadNow(state); + } + + private synchronized void writePacedPad() { + if (axisPacing.release(SystemClock.uptimeMillis())) + writePadNow(pacedPad); + } + + private void cancelPacedWrite() { + if (axisPacing.cancel()) + Pacing.HANDLER.removeCallbacks(pacedWrite); + } + + private boolean onlyAxesMove(PadState state) { + for (int i = 0; i < 10; i++) { + if (prevButtonStates[i] != state.isDown(i)) + return false; + } + return prevButtonStates[SNAPSHOT_IDX_MODE] == state.isDown(PadState.GUIDE) + && prevQam == state.isDown(PadState.QAM) + && prevHatX == state.hatX() && prevHatY == state.hatY() + && AxisPacing.keepsMoving(prevThumbLX, stickValue(state.leftX)) + && AxisPacing.keepsMoving(prevThumbLY, stickValue(state.leftY)) + && AxisPacing.keepsMoving(prevThumbRX, stickValue(state.rightX)) + && AxisPacing.keepsMoving(prevThumbRY, stickValue(state.rightY)) + && AxisPacing.keepsMoving(prevTriggerL, triggerValue(state.leftTrigger)) + && AxisPacing.keepsMoving(prevTriggerR, triggerValue(state.rightTrigger)); + } + + private static int stickValue(float value) { + return (int) (value * 32767); + } + + private static int triggerValue(float value) { + return (int) (value * 255); + } + + private void writePadNow(PadState state) { if (!isOpen && !open()) return; @@ -845,10 +911,10 @@ public class FakeInputWriter { hasChanges = true; } - int lx = (int) (state.leftX * 32767); - int ly = (int) (state.leftY * 32767); - int rx = (int) (state.rightX * 32767); - int ry = (int) (state.rightY * 32767); + int lx = stickValue(state.leftX); + int ly = stickValue(state.leftY); + int rx = stickValue(state.rightX); + int ry = stickValue(state.rightY); if (forceResend || lx != prevThumbLX) { prevThumbLX = lx; @@ -867,8 +933,8 @@ public class FakeInputWriter { writeEvent(EV_ABS, ABS_RY, ry); } - int tl = (int) (state.leftTrigger * 255); - int tr = (int) (state.rightTrigger * 255); + int tl = triggerValue(state.leftTrigger); + int tr = triggerValue(state.rightTrigger); if (forceResend || tl != prevTriggerL) { prevTriggerL = tl; writeEvent(EV_ABS, ABS_BRAKE, tl); @@ -895,6 +961,8 @@ public class FakeInputWriter { if (!flushBuffer()) { Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable"); pendingFullResend = true; + } else { + axisPacing.wrote(SystemClock.uptimeMillis()); } } forceResend = false; diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt index 7ce94fc93b..0e42e770e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -436,6 +436,7 @@ object BwrapSpawner { "DDNATV_ROOT" to sandbox, "DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(), "DDNATV_LINK_ROOT" to rootfs.path, + "DDNATV_REAL_EXE" to program.path, "DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" }, "DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context), "LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path }, diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt index c609fe7c4b..61f91598d5 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt @@ -73,9 +73,10 @@ object NativeGuest { fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path } /** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */ - fun environment(root: File, preload: List = emptyList()): Map = linkedMapOf( + fun environment(root: File, program: String, preload: List = emptyList()): Map = linkedMapOf( "DDNATV_ROOT" to root.path, "DDNATV_EXEC" to execLoader.orEmpty(), + "DDNATV_REAL_EXE" to hostProgram(root, program).path, "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), ).filterValues { it.isNotEmpty() } @@ -85,17 +86,20 @@ object NativeGuest { */ fun command(root: File, program: String, args: List, libraryPath: String = libraryPath(root)): List { val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" } - val host = File(root, program.removePrefix("/")) + val host = hostProgram(root, program) val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch) } + private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/")) + /** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */ - fun sessionEnvironment(root: File, binds: List, hostname: String? = null): Map { + fun sessionEnvironment(root: File, binds: List, program: String, hostname: String? = null): Map { val preload = preloadList(root) return linkedMapOf( "DDNATV_ROOT" to root.path, "DDNATV_EXEC" to execLoader.orEmpty(), + "DDNATV_REAL_EXE" to hostProgram(root, program).path, "DDNATV_HOSTNAME" to hostname.orEmpty(), "DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" }, "DDNATV_PRELOAD" to preload.joinToString(":"), @@ -114,7 +118,7 @@ object NativeGuest { .also { builder -> builder.environment().apply { remove("LD_AUDIT") - putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context))) + putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context))) } } @@ -278,7 +282,7 @@ object NativeGuest { builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root) builder.environment().apply { clear() - putAll(environment(root, preload)) + putAll(environment(root, program, preload)) putAll(env) } return builder diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt index 5300b24720..b25ed487a2 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt @@ -328,7 +328,7 @@ object BottomDesktop { LinuxRuntime.commandWithBinds(context, current.root, binds, guest) } val environment = if (current.nativeUserland) { - com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context)) + com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context)) .map { (k, v) -> "$k=$v" }.toTypedArray() } else current.hostEnvironment val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") } diff --git a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt index b437f3ae4e..e1b38fe9ec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt @@ -935,7 +935,7 @@ internal object EnhancedSessionLogShare { private fun category(entry: String): Category { val value = entry.lowercase(Locale.US) - if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || + if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") || value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) || listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS @@ -950,6 +950,7 @@ internal object EnhancedSessionLogShare { "frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json", "battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt", + "rpcs3", "RPCS3.log", ) private val KNOWN_COMPONENT_PATTERNS = listOf( Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"), diff --git a/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt b/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt new file mode 100644 index 0000000000..d989f4bc88 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/LaunchCoordinator.kt @@ -0,0 +1,82 @@ +package com.droiddeck.launcher.session + +/** + * Orders launch attempts and at most one pending game link. + * + * This is main-thread state: call it from the UI thread. A ticket is an identity, + * not a counter comparison, so a stale callback can only act on its own request. + */ +internal class LaunchTicket internal constructor(val serial: Long) + +internal class LaunchCoordinator { + internal class Link internal constructor( + val ticket: LaunchTicket, + val owner: O, + val request: R?, + ) { + /** Only the activity intent that delivered this link may finish it by a refresh. */ + fun ownedBy(owner: O?): Boolean = this.owner === owner + } + + private var next = 0L + private var current: LaunchTicket? = null + private var pending: Link? = null + private var handling: LaunchTicket? = null + + /** A launch that is allowed to proceed; it supersedes any pending link. */ + fun beginLaunch(): LaunchTicket { + val ticket = LaunchTicket(++next) + current = ticket + pending = null + handling = null + return ticket + } + + /** A game-link intent; it supersedes any earlier launch or link. */ + fun beginLink(owner: O): LaunchTicket { + val ticket = LaunchTicket(++next) + current = ticket + pending = Link(ticket, owner, null) + handling = null + return ticket + } + + /** The asynchronous link read returned; false means a newer request won. */ + fun resolve(ticket: LaunchTicket, request: R?): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket) return false + pending = Link(ticket, link.owner, request) + return true + } + + fun beginHandling(ticket: LaunchTicket): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket || link.request == null) return false + handling = ticket + return true + } + + fun releaseHandling(ticket: LaunchTicket) { + if (handling === ticket) handling = null + } + + fun isHandling(ticket: LaunchTicket): Boolean = handling === ticket + fun isCurrent(ticket: LaunchTicket): Boolean = current === ticket + fun hasPending(): Boolean = pending != null + fun pendingLink(): Link? = pending + + fun consume(ticket: LaunchTicket): Boolean { + val link = pending ?: return false + if (link.ticket !== ticket) return false + pending = null + handling = null + return true + } + + fun cancelAll() { + next++ + current = null + pending = null + handling = null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt index 2b4744574f..03c9fddcae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -75,6 +75,7 @@ object SessionArtifacts { LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context)) val record = Record(dir) copySteamLogs(context, dir, record, steamArch) + copyRpcs3Log(context, dir, record) VacDiagnostics.collect(context, dir) SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log")) SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log")) @@ -321,6 +322,9 @@ object SessionArtifacts { runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" } private const val LOG_MARKS = "steam-log-marks.txt" + private const val RPCS3_LOG_MARKS = "rpcs3-log-marks.txt" + private const val RPCS3_LOGS = "root/.cache/rpcs3" + private const val RPCS3_LOG = "RPCS3.log" private const val MAX_STEAM_LOG = 8L * 1024 * 1024 private const val HEAD = 4096L @@ -328,11 +332,19 @@ object SessionArtifacts { private class CopyResult(val files: List, val failed: Boolean, val deferred: Boolean) fun markSteamLogs(dir: File, logs: File) { - val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f -> + logs.listFiles { f -> f.isFile }?.let { markLogs(dir, LOG_MARKS, it.toList()) } + } + + fun markRpcs3Log(dir: File, root: File) { + markLogs(dir, RPCS3_LOG_MARKS, listOf(File(root, "$RPCS3_LOGS/$RPCS3_LOG")).filter { it.isFile }) + } + + private fun markLogs(dir: File, marks: String, files: List) { + val lines = files.mapNotNull { f -> val size = f.length() head(f, size)?.let { "$size\t$it\t${f.name}" } - } ?: return - runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) } + } + runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) } } private fun head(f: File, length: Long): String? = runCatching { @@ -348,8 +360,8 @@ object SessionArtifacts { java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) } }.getOrNull() - private fun steamLogMarks(dir: File): List? = runCatching { - File(dir, LOG_MARKS).readLines().mapNotNull { line -> + private fun logMarks(dir: File, marks: String): List? = runCatching { + File(dir, marks).readLines().mapNotNull { line -> val parts = line.split('\t', limit = 3) parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } } } @@ -371,11 +383,32 @@ object SessionArtifacts { val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs") if (!logs.isDirectory) return val out = File(dir, "steam").apply { mkdirs() } - val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } + addCopied(record, copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }) + Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") + } + + private fun copyRpcs3Log(context: Context, dir: File, record: Record, stopWhenSessionStarts: Boolean = false) { + val out = File(dir, "rpcs3") + val logs = File(LinuxRuntime.rootDir(context), RPCS3_LOGS) + val copied = copyRpcs3LogResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } ?: return + addCopied(record, copied) + if (copied.files.isNotEmpty()) Log.i(TAG, "collected RPCS3's log, scrubbed, into $out") + } + + internal fun copyRpcs3Log(logs: File, dir: File, out: File): List = copyRpcs3LogResult(logs, dir, out) { false }?.files.orEmpty() + + private fun copyRpcs3LogResult(logs: File, dir: File, out: File, shouldStop: () -> Boolean): CopyResult? { + if (!File(dir, RPCS3_LOG_MARKS).isFile || !File(logs, RPCS3_LOG).isFile) return null + out.mkdirs() + val result = copySessionLogsResult(logs, dir, out, marksName = RPCS3_LOG_MARKS, accept = { it.name == RPCS3_LOG }, shouldStop = shouldStop) + if (result.files.isEmpty()) out.delete() + return result + } + + private fun addCopied(record: Record, result: CopyResult) { result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) } record.failed = record.failed || result.failed record.deferred = record.deferred || result.deferred - Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out") } internal fun copySessionLogs( @@ -383,20 +416,22 @@ object SessionArtifacts { dir: File, out: File, openWriter: (File) -> Writer = { it.bufferedWriter() }, - ): List = copySessionLogsResult(logs, dir, out, openWriter) { false }.files + ): List = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files private fun copySessionLogsResult( logs: File, dir: File, out: File, + marksName: String = LOG_MARKS, + accept: (File) -> Boolean = { true }, openWriter: (File) -> Writer = { it.bufferedWriter() }, shouldStop: () -> Boolean, ): CopyResult { - val marks = steamLogMarks(dir) + val marks = logMarks(dir, marksName) val copied = ArrayList() var failed = false var deferred = false - val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false) + val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false) for (src in sources) { if (shouldStop()) { failed = true @@ -567,6 +602,7 @@ object SessionArtifacts { steamArch = recordedClient(dir), stopWhenSessionStarts = stopWhenSessionStarts, ) + copyRpcs3Log(context, dir, record, stopWhenSessionStarts) if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) { if (!record.failed && VacDiagnostics.collect(context, dir)) { try { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index 101e413933..177774a4ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -263,7 +263,9 @@ object SessionFiles { "usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json", "usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke", "usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime", + "usr/local/lib/droiddeck/dwarfsextract" to "usr/local/lib/droiddeck/dwarfsextract", "usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst", + "usr/local/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE", "usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE", ) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) -> val dir = asset.substringBeforeLast('/') 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 9645c411cc..8889ccb261 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -814,6 +814,11 @@ object SessionPrefs { prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply() } + fun displayDriverFromAuto(context: Context): Boolean { + val id = androidDriver(context) + return id.isEmpty() || (gpuDriverMode(context) == GPU_DRIVERS_AUTO && id in gpuAutoInstalled(context)) + } + fun picturePosition(context: Context): String = prefs(context).getString("picturePosition", "center") @@ -1343,6 +1348,10 @@ object SessionPrefs { SessionDisplay.effectiveChoice( resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait) + fun followScales(context: Context, mode: String, panel: Pair): Pair = + SessionDisplay.followScale(resolutionChoice(context, mode, panel, false)) to + SessionDisplay.followScale(resolutionChoice(context, mode, panel, true)) + fun resolutionStored(context: Context, mode: String, panel: Pair, portrait: Boolean): String { if (!portrait) return landscapeResolutionStored(context, mode, panel) val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE @@ -1553,7 +1562,7 @@ object SessionPrefs { fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean = synchronized(addedGameLock) { val unchanged = addedGameExe(context, folderPath) == expected - if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply() + if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putString("addedAdopted:Exe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply() unchanged } 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 144fad8894..f7af8ff9ae 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -784,7 +784,7 @@ class SessionService : Service() { if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back") val hostEnv = if (nativeUserland) HostEnvironment().also { env -> Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)") - com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this)) + com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this)) .forEach { (k, v) -> env[k] = v } } else prootEnv @@ -1070,6 +1070,7 @@ class SessionService : Service() { guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this))) guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216") if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) + SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) } SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null SessionState.steamClientArch?.let { arch -> guest.add("DD_STEAM_CLIENT_ARCH=$arch") diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index e695f8b932..92255febec 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -148,6 +148,9 @@ object SessionState { @Volatile var outputSize: Pair = Pair(1920, 1080) + @Volatile + var followScales: Pair = null to null + @Volatile var followScreen = false var followScale = 1f diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index 54571ab172..0efcedbe88 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -65,6 +65,7 @@ class StoreLoginActivity : ComponentActivity() { val readsPage: Boolean get() = false val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()" fun pageReady(result: String): Boolean = true + fun browserStep(page: String): String? = null fun forgetSignIn(done: () -> Unit) = done() fun pageFinished(view: WebView, url: String) {} } @@ -72,6 +73,7 @@ class StoreLoginActivity : ComponentActivity() { private var store: Store? = null private var clientUrl: String? = null private var flow: Flow? = null + private var pendingBrowserStep: String? = null private var webViewRef: WebView? = null private var popupWebView: WebView? = null private lateinit var contentHost: FrameLayout @@ -211,6 +213,7 @@ class StoreLoginActivity : ComponentActivity() { private fun reloadLogin() { dismissPopup(); clearError() + pendingBrowserStep = null captured.set(false) val fresh = generateState() oauthState = fresh @@ -332,9 +335,13 @@ class StoreLoginActivity : ComponentActivity() { private fun readPage(view: WebView, f: Flow, left: Int) { view.evaluateJavascript(f.pageScript) { json -> + if (flow !== f) return@evaluateJavascript val result = json ?: "" if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS) - else Thread({ settle(f.finish(this, view, result)) }, "store-login").start() + else { + val step = f.browserStep(result) + if (step == null || !continueInBrowser(step)) Thread({ settle(f.finish(this, view, result)) }, "store-login").start() + } } } @@ -350,6 +357,21 @@ class StoreLoginActivity : ComponentActivity() { if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start() } + private fun continueInBrowser(url: String): Boolean { + if (isFinishing || isDestroyed) return false + if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) { + pendingBrowserStep = url + return true + } + val opened = runCatching { startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url))) } + .onFailure { Log.w(TAG, "no browser took the sign-in step: ${it.javaClass.simpleName}") } + .isSuccess + if (!opened) return false + titleText.text = getString(R.string.stores_login_title, store?.label ?: "") + showError(getString(R.string.stores_login_continue_in_browser, store?.label ?: "")) + return true + } + private fun settle(problem: String?) { runOnUiThread { if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread } @@ -367,6 +389,10 @@ class StoreLoginActivity : ComponentActivity() { override fun onStart() { super.onStart() + pendingBrowserStep?.let { step -> + pendingBrowserStep = null + if (!continueInBrowser(step)) reloadLogin() + } if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt index ff804a85e3..f2ee5a26a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicLogin.kt @@ -5,8 +5,9 @@ import android.webkit.WebView import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.StoreLoginActivity import org.json.JSONObject +import org.json.JSONTokener -internal class EpicLogin private constructor( +internal class EpicLogin internal constructor( override val startUrl: String, override val userAgent: String, private val redirectPrefix: String, @@ -15,6 +16,12 @@ internal class EpicLogin private constructor( override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix) + override fun browserStep(page: String): String? { + val action = correctiveAction(page) ?: return null + Log.i(TAG, "the redirect page asks for a corrective action: $action") + return ACCOUNT_SIGN_IN_URL + } + override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty() if (code.isEmpty()) { @@ -38,6 +45,15 @@ internal class EpicLogin private constructor( companion object { private const val TAG = "EpicLogin" + private const val CORRECTIVE_ACTION_REQUIRED = "errors.com.epicgames.oauth.corrective_action_required" + internal const val ACCOUNT_SIGN_IN_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal" + + internal fun correctiveAction(page: String): String? { + val text = runCatching { JSONTokener(page).nextValue() }.getOrNull() as? String ?: page + val body = runCatching { JSONObject(text.trim()) }.getOrNull() ?: return null + if (body.optString("errorCode") != CORRECTIVE_ACTION_REQUIRED) return null + return body.optJSONObject("metadata")?.optString("correctiveAction").orEmpty().ifEmpty { "unknown" } + } fun create(): StoreLoginActivity.Flow? { val config = EpicNative.call("auth.config") ?: return null diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt index 8904f2c2d4..4d4ac7adc0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -117,6 +117,7 @@ import com.droiddeck.launcher.IconPack import android.content.pm.ShortcutInfo import android.graphics.Bitmap import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.drop import kotlinx.coroutines.withContext import com.droiddeck.launcher.HomeWidgets @@ -388,21 +389,49 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod } val front = LocalFrontFocus.current val steer = rememberCoroutineScope() - // Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or + // The tile a move is heading to, by its id so that a list update cannot shift it, and the number of the latest move. + val aim = remember { arrayOfNulls(1) } + val moves = remember { intArrayOf(0) } + val move = remember { arrayOfNulls(1) } + // Up and Down go to the tile straight above or below. The grid's own search works from where the tiles are drawn at that + // moment, so while a scroll is still catching up with fast presses it skips a row or drifts a column, and above a short or // unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it. + // Presses aim from the tile a move is already heading to, so none is lost before the focus lands. Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event -> val k = event.nativeKeyEvent - if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false - val from = entries.indexOfFirst { tileId(it) == front.last } + val down = k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN + if ((!down && k.keyCode != KeyEvent.KEYCODE_DPAD_UP) || front == null) return@onPreviewKeyEvent false + val aimed = aim[0]?.let { id -> entries.indexOfFirst { tileId(it) == id } } ?: -1 + if (aim[0] != null && aimed < 0) { + // The tile a move was heading to has left the list: that move is dropped and the press aims from the focus. + move[0]?.cancel() + aim[0] = null + } + val from = aimed.takeIf { it >= 0 } ?: entries.indexOfFirst { tileId(it) == front.last } val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1 - if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false + if (from < 0) return@onPreviewKeyEvent false + // At the first or last row the press leaves the grid, unless a move has not landed yet: then it waits for it. + val edge = if (down) from / columns == entries.lastIndex / columns else from < columns + if (edge) return@onPreviewKeyEvent aim[0] != null if (k.action == KeyEvent.ACTION_DOWN) { - val id = tileId(entries[minOf(from + columns, entries.lastIndex)]) - val shown = (front.attached[id] ?: 0) > 0 - if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch { - // The row below is not laid out yet: bring it in, then take it. - if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat()) - focusSoon { front.items.getValue(id) } + val to = if (down) minOf(from + columns, entries.lastIndex) else from - columns + val id = tileId(entries[to]) + aim[0] = id + val mine = ++moves[0] + // A newer move replaces the one still on its way, so an older target cannot take focus after it lands. + move[0]?.cancel() + move[0] = steer.launch { + try { + // Show the row before it takes focus. The grid composes rows ahead of the view without placing them, and a + // tile focused there neither scrolls in nor has a place for the next search to start from. + grid.reveal(to + leadItems) + if (moves[0] != mine) return@launch + focusSoon { front.items.getValue(id) } + } finally { + // Also when a touch scroll cancels the reveal, so the edge rows do not keep waiting for a move that ended. + // Only the latest move clears it: a cancelled one finishing late must not clear a newer move's target. + if (moves[0] == mine) aim[0] = null + } } } true @@ -558,6 +587,26 @@ private fun HeaderChoiceButton( } } +/** Scrolls the least that shows item [index] whole inside the padding, a row at a time while it is still outside the laid out items. */ +private suspend fun LazyGridState.reveal(index: Int) { + repeat(4) { + val info = layoutInfo + val shown = info.visibleItemsInfo + val item = shown.firstOrNull { it.index == index } + val by = when { + item != null -> { + val bottom = item.offset.y + item.size.height - (info.viewportEndOffset - info.afterContentPadding) + if (item.offset.y < 0) item.offset.y else maxOf(bottom, 0) + } + index > (shown.lastOrNull() ?: return).index -> shown.last().size.height + index < shown.first().index -> -shown.first().size.height + else -> return + } + if (by == 0) return + scrollBy(by.toFloat()) + } +} + @Composable private fun AlphabetScroller(entries: List, grid: LazyGridState, leadItems: Int, modifier: Modifier) { val colors = MaterialTheme.colorScheme diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt index 9fd3631553..5a1363a65e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ExePickerDialog.kt @@ -60,7 +60,8 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.R -import com.droiddeck.launcher.session.GameStorage +import com.droiddeck.launcher.files.StorageRoot +import com.droiddeck.launcher.files.StorageRoots import com.droiddeck.launcher.stores.formatBytes import java.io.File @@ -74,10 +75,16 @@ internal class PickVolume(val root: File, val label: String, val removable: Bool } internal fun pickVolumes(context: Context): List = - listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) + - GameStorage.options(context).mapNotNull { o -> - File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) } - }.distinctBy { it.root.absolutePath } + pickVolumes(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), StorageRoots.list(context)) + +internal fun pickVolumes(internal: File, internalLabel: String, roots: List): List { + val internalPath = internal.absolutePath.trimEnd('/') + fun overlapsInternal(path: String) = path == internalPath || path.startsWith("$internalPath/") || internalPath.startsWith("$path/") + return listOf(PickVolume(internal, internalLabel, removable = false)) + + roots.filter { it.readable && !overlapsInternal(it.dir.absolutePath.trimEnd('/')) } + .map { PickVolume(it.dir, it.label, removable = true) } + .distinctBy { it.root.absolutePath } +} internal class PickFolder(val dir: File, val readable: Boolean) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 0062c67b24..543c5f6857 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -1098,8 +1098,6 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron internal const val GAME_SETTINGS_MENU = "game-settings" -private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal" - @Composable private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) { val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext @@ -1149,7 +1147,7 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro MenuItem(stringResource(R.string.epic_resolve), checked = false) { host.open = null runCatching { - appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) + appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.epic.EpicLogin.ACCOUNT_SIGN_IN_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index 79ee2d8491..f06c43851c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -38,8 +38,10 @@ import com.droiddeck.launcher.input.InputButtonShape import com.droiddeck.launcher.input.InputButtonImages import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PadKit +import com.droiddeck.launcher.input.ThrottledRedraw import com.droiddeck.launcher.input.pcKeyLabel import com.droiddeck.launcher.session.SessionPrefs +import kotlin.math.abs import kotlin.math.atan2 import kotlin.math.hypot import kotlin.math.min @@ -581,6 +583,10 @@ class InputSurfaceView( private var originY = 0f private var knobX = 0f private var knobY = 0f + private var drawnX = 0f + private var drawnY = 0f + private var atRim = false + private val redraw = ThrottledRedraw(this, STICK_REDRAW_MS) private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE } private val knob = Paint(Paint.ANTI_ALIAS_FLAG) @@ -663,6 +669,7 @@ class InputSurfaceView( MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r) MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { touching = false + atRim = false val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0 travel = maxOf(travel, hypot(event.x - downX, event.y - downY)) lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L @@ -678,15 +685,27 @@ class InputSurfaceView( var dx = x - originX var dy = y - originY val length = hypot(dx, dy) - if (length > r) { dx *= r / length; dy *= r / length } - if (force || dx != knobX || dy != knobY) move(dx, dy, r) + val rim = length > r + if (rim) { dx *= r / length; dy *= r / length } + val reachedRim = rim && !atRim + atRim = rim + if (force || dx != knobX || dy != knobY) move(dx, dy, r, throttled = !force && !reachedRim, rim = rim) } - private fun move(dx: Float, dy: Float, r: Float) { + private fun move(dx: Float, dy: Float, r: Float, throttled: Boolean = false, rim: Boolean = false) { knobX = dx knobY = dy source?.update(dx / r, dy / r) - invalidate() + if (!throttled) { + redraw.cancel() + drawnX = dx + drawnY = dy + invalidate() + } else if (rim || abs(dx - drawnX) >= MIN_STICK_MOVE_PX || abs(dy - drawnY) >= MIN_STICK_MOVE_PX) { + drawnX = dx + drawnY = dy + redraw.request() + } } private fun setClick(down: Boolean) { @@ -699,6 +718,7 @@ class InputSurfaceView( override fun onDetachedFromWindow() { setClick(false) if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f) + redraw.cancel() super.onDetachedFromWindow() } } @@ -766,6 +786,8 @@ class InputSurfaceView( companion object { private const val CLICK_MS = 300L private const val STICK_TAP_MS = 200L + private const val STICK_REDRAW_MS = 33L + private const val MIN_STICK_MOVE_PX = 1f private const val CLASSIC_REACH = 0.5f private const val PANEL_REACH = 0.30f private const val HIT_SLACK = 0.25f diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 8d43d09c7b..d9d2eb111f 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -84,7 +84,7 @@ object CompositorHost { com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context) WaylandCompositor.nativeStartWithSurface( surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir, - SessionPrefs.androidDriver(context).isEmpty(), + SessionPrefs.displayDriverFromAuto(context), ) attached = surface started = true diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 973c8bb6c0..59188caba6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -2818,6 +2818,7 @@ الاتصال بصفحة تسجيل الدخول غير آمن. تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى. فشل تسجيل الدخول. حاوِل مرة أخرى. + يحتاج %1$s إلى خطوة أخرى. أكملها في المتصفح الذي فُتح، ثم حاول مرة أخرى. إغلاق رجوع تعديل diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 540eec6450..c1314a8bd6 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -2784,6 +2784,7 @@ La conexión con la página de inicio de sesión no es segura. No se pudo verificar el inicio de sesión. Inténtalo de nuevo. No se pudo iniciar sesión. Inténtalo de nuevo. + %1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo. Cerrar Atrás Editar diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 340f2d8467..2ab13542e9 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -2714,6 +2714,7 @@ Връзката със страницата за вход не е защитена. Входът не можа да бъде потвърден. Опитай отново. Входът се провали. Опитай отново. + %1$s изисква още една стъпка. Завърши я в браузъра, който се отвори, и опитай отново. Затвори Назад Редактирай diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 9cae733f68..04231de374 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -2766,6 +2766,7 @@ Spojení s přihlašovací stránkou není zabezpečené. Přihlášení se nepodařilo ověřit. Zkuste to znovu. Přihlášení se nezdařilo. Zkuste to znovu. + %1$s vyžaduje ještě jeden krok. Dokončete ho v prohlížeči, který se otevřel, a zkuste to znovu. Zavřít Zpět Upravit diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 59329a1f9e..609965ad7f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -2714,6 +2714,7 @@ Forbindelsen til loginsiden er ikke sikker. Login kunne ikke bekræftes. Forsøg igen. Login mislykkedes. Forsøg igen. + %1$s kræver et trin mere. Fuldfør det i browseren, der blev åbnet, og prøv igen. Luk Tilbage Rediger diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3559dcecec..f803d555bd 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -2703,6 +2703,7 @@ Die Verbindung zur Anmeldeseite ist nicht sicher. Die Anmeldung konnte nicht bestätigt werden. Versuche es erneut. Anmeldung fehlgeschlagen. Versuche es erneut. + %1$s braucht noch einen Schritt. Schließe ihn im geöffneten Browser ab und versuche es dann erneut. Schließen Zurück Bearbeiten diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 50903050c4..08d647886a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -2714,6 +2714,7 @@ Η σύνδεση με τη σελίδα σύνδεσης δεν είναι ασφαλής. Δεν ήταν δυνατή η επαλήθευση της σύνδεσης. Δοκιμάστε ξανά. Η σύνδεση απέτυχε. Δοκιμάστε ξανά. + Το %1$s χρειάζεται ένα ακόμη βήμα. Ολοκληρώστε το στο πρόγραμμα περιήγησης που άνοιξε και δοκιμάστε ξανά. Κλείσιμο Πίσω Επεξεργασία diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 3138760ebe..d1859b029a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -2737,6 +2737,7 @@ La conexión con la página de inicio de sesión no es segura. No se pudo verificar el inicio de sesión. Inténtalo de nuevo. No se pudo iniciar sesión. Inténtalo de nuevo. + %1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo. Cerrar Atrás Editar diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index f551a03c7e..4cf72f1674 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -2714,6 +2714,7 @@ Yhteys kirjautumissivulle ei ole suojattu. Kirjautumista ei voitu vahvistaa. Yritä uudelleen. Kirjautuminen epäonnistui. Yritä uudelleen. + %1$s vaatii vielä yhden vaiheen. Viimeistele se avautuneessa selaimessa ja yritä sitten uudelleen. Sulje Takaisin Muokkaa diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8a93091282..c735507d40 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -2736,6 +2736,7 @@ La liaison avec la page de connexion n\'est pas sécurisée. Impossible de vérifier la connexion. Réessayez. Échec de la connexion. Réessayez. + %1$s demande une étape de plus. Terminez-la dans le navigateur qui s\'est ouvert, puis réessayez. Fermer Retour Modifier diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 3b76665f48..c3b71210f6 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -2714,6 +2714,7 @@ साइन-इन पेज से कनेक्शन सुरक्षित नहीं है। साइन-इन सत्यापित नहीं हो सका। फिर कोशिश करें। साइन-इन विफल रहा। फिर कोशिश करें। + %1$s को एक और चरण चाहिए। खुले हुए ब्राउज़र में इसे पूरा करें, फिर दोबारा कोशिश करें। बंद करें बैक संपादित करें diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index ea47bab819..8c51e3cf8a 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -2714,6 +2714,7 @@ A kapcsolat a bejelentkezési oldalhoz nem biztonságos. A bejelentkezést nem sikerült ellenőrizni. Próbálja újra. A bejelentkezés sikertelen. Próbálja újra. + A(z) %1$s még egy lépést kér. Fejezze be a megnyílt böngészőben, majd próbálja újra. Bezárás Vissza Szerkesztés diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 110833e35e..d067290684 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -2689,6 +2689,7 @@ Koneksi ke halaman masuk tidak aman. Proses masuk tidak dapat diverifikasi. Coba lagi. Proses masuk gagal. Coba lagi. + %1$s memerlukan satu langkah lagi. Selesaikan di browser yang terbuka, lalu coba lagi. Tutup Kembali Edit diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 8ec37be21e..2dfa1da981 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -2728,6 +2728,7 @@ La connessione alla pagina di accesso non è sicura. Impossibile verificare l\'accesso. Riprova. Accesso non riuscito. Riprova. + %1$s richiede un altro passaggio. Completalo nel browser che si è aperto, poi riprova. Chiudi Indietro Modifica diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index e012fed66b..b51efa75a8 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -2689,6 +2689,7 @@ ログインページへの接続は安全ではありません。 ログインを確認できませんでした。もう一度お試しください。 ログインに失敗しました。もう一度お試しください。 + %1$s で追加の手順が必要です。開いたブラウザーで完了してから、もう一度お試しください。 閉じる 戻る 編集 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 337c0d437e..8b3f92a2a9 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -2689,6 +2689,7 @@ 로그인 페이지 연결이 안전하지 않습니다. 로그인을 확인할 수 없습니다. 다시 시도하세요. 로그인에 실패했습니다. 다시 시도하세요. + %1$s에서 한 단계가 더 필요합니다. 열린 브라우저에서 완료한 다음 다시 시도하세요. 닫기 뒤로 편집 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index ef8393e099..95364b21d1 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -2689,6 +2689,7 @@ Sambungan ke halaman log masuk tidak selamat. Log masuk tidak dapat disahkan. Cuba lagi. Log masuk gagal. Cuba lagi. + %1$s memerlukan satu langkah lagi. Selesaikannya dalam pelayar yang dibuka, kemudian cuba lagi. Tutup Kembali Sunting diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 81e2cfd0ba..2fd355eec3 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -2714,6 +2714,7 @@ Tilkoblingen til innloggingssiden er ikke sikker. Innloggingen kunne ikke verifiseres. Prøv igjen. Innlogging mislyktes. Prøv igjen. + %1$s trenger ett trinn til. Fullfør det i nettleseren som ble åpnet, og prøv igjen. Lukk Tilbake Rediger diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 2a8fb73b58..b788d41499 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -2714,6 +2714,7 @@ De verbinding met de aanmeldpagina is niet beveiligd. De aanmelding kon niet worden geverifieerd. Probeer het opnieuw. Aanmelden mislukt. Probeer het opnieuw. + %1$s vraagt nog één stap. Rond die af in de browser die is geopend en probeer het opnieuw. Sluiten Terug Bewerken diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 4fcc9f537b..59fadab554 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -2766,6 +2766,7 @@ Połączenie ze stroną logowania nie jest bezpieczne. Nie udało się zweryfikować logowania. Spróbuj ponownie. Logowanie nie powiodło się. Spróbuj ponownie. + %1$s wymaga jeszcze jednego kroku. Dokończ go w otwartej przeglądarce, a potem spróbuj ponownie. Zamknij Wstecz Edytuj diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 12267238f7..5e1f62f5d1 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -2742,6 +2742,7 @@ A ligação à página de início de sessão não é segura. Não foi possível verificar o início de sessão. Tente novamente. Falha no início de sessão. Tente novamente. + %1$s precisa de mais um passo. Conclua-o no navegador que foi aberto e tente novamente. Fechar Voltar Editar diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index e51abbbead..6372234699 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -2750,6 +2750,7 @@ A conexão com a página de login não é segura. Não foi possível verificar o login. Tente de novo. Falha no login. Tente de novo. + %1$s precisa de mais uma etapa. Conclua no navegador que foi aberto e tente novamente. Fechar Voltar Editar diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 89e8d30b85..f25f8abbb2 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -2740,6 +2740,7 @@ Conexiunea la pagina de autentificare nu este sigură. Autentificarea nu a putut fi verificată. Încearcă din nou. Autentificarea a eșuat. Încearcă din nou. + %1$s mai cere un pas. Finalizează-l în browserul care s-a deschis, apoi încearcă din nou. Închide Înapoi Editează diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 09bb9155f6..956c3d5136 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -2764,6 +2764,7 @@ Подключение к странице входа не защищено. Не удалось подтвердить вход. Повторите попытку. Ошибка входа. Повторите попытку. + %1$s требует ещё один шаг. Завершите его в открывшемся браузере и попробуйте снова. Закрыть Назад Изменить diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 69960f0a1b..9361bca121 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -2714,6 +2714,7 @@ Anslutningen till inloggningssidan är inte säker. Inloggningen kunde inte verifieras. Försök igen. Inloggningen misslyckades. Försök igen. + %1$s behöver ett steg till. Slutför det i webbläsaren som öppnades och försök sedan igen. Stäng Tillbaka Redigera diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 924715aad9..a7f07bbe93 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -2689,6 +2689,7 @@ การเชื่อมต่อไปยังหน้าลงชื่อเข้าใช้ไม่ปลอดภัย ไม่สามารถยืนยันการลงชื่อเข้าใช้ได้ ลองใหม่ ลงชื่อเข้าใช้ล้มเหลว ลองใหม่ + %1$s ต้องการอีกหนึ่งขั้นตอน ทำให้เสร็จในเบราว์เซอร์ที่เปิดขึ้น แล้วลองอีกครั้ง ปิด กลับ แก้ไข diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 0056965a36..581d4aecbb 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -2703,6 +2703,7 @@ Oturum açma sayfasına bağlantı güvenli değil. Oturum açma doğrulanamadı. Yeniden deneyin. Oturum açma başarısız oldu. Yeniden deneyin. + %1$s bir adım daha istiyor. Açılan tarayıcıda tamamlayın, ardından yeniden deneyin. Kapat Geri Düzenle diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 3505527050..8db1b46441 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -2766,6 +2766,7 @@ З’єднання зі сторінкою входу не захищене. Не вдалося підтвердити вхід. Спробуйте ще раз. Вхід не вдався. Спробуйте ще раз. + %1$s потребує ще одного кроку. Завершіть його у відкритому браузері та спробуйте ще раз. Закрити Назад Редагувати diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 5598b9b8f2..707c107c89 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -2689,6 +2689,7 @@ Kết nối đến trang đăng nhập không an toàn. Không thể xác minh đăng nhập. Hãy thử lại. Đăng nhập thất bại. Hãy thử lại. + %1$s cần thêm một bước. Hãy hoàn tất trong trình duyệt vừa mở, rồi thử lại. Đóng Quay lại Sửa diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 7df9807375..e95780a79c 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -2763,6 +2763,7 @@ 与登录页面的连接不安全。 无法验证登录。请重试。 登录失败。请重试。 + %1$s 还需要一个步骤。请在已打开的浏览器中完成,然后重试。 关闭 返回 编辑 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 6eb5d1a6dd..28dcdcb49f 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -2686,6 +2686,7 @@ 與登入頁面的連線不安全。 無法驗證登入,請再試一次。 登入失敗,請再試一次。 + %1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。 關閉 返回 編輯 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index a678d12b2c..a1f1534f67 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -2686,6 +2686,7 @@ 與登入頁面的連線不安全。 無法驗證登入。請再試一次。 登入失敗。請再試一次。 + %1$s 還需要一個步驟。請在已開啟的瀏覽器中完成,然後再試一次。 關閉 返回 編輯 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 844524c2f0..69b03e75f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3034,6 +3034,7 @@ The connection to the sign-in page is not secure. The sign-in could not be verified. Try again. Sign-in failed. Try again. + %1$s needs one more step. Finish it in the browser that opened, then try again. Close Back Edit diff --git a/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt b/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt new file mode 100644 index 0000000000..0eba5d4667 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/FrontEndIntentSupersedeTest.kt @@ -0,0 +1,85 @@ +package com.droiddeck.launcher + +import android.content.Intent +import com.droiddeck.launcher.core.SteamIntegration +import com.droiddeck.launcher.frontend.GameRequest +import com.droiddeck.launcher.session.LaunchCoordinator +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +/** + * A replacement activity intent invalidates everything this activity has not dispatched yet: a + * resolved but unhandled game link, and an accepted launch that is still waiting for its session. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class FrontEndIntentSupersedeTest { + private lateinit var activity: FrontEndActivity + private lateinit var coordinator: LaunchCoordinator + + @Before + fun setUp() { + activity = Robolectric.buildActivity(FrontEndActivity::class.java).get() + coordinator = ReflectionHelpers.getField(activity, "launchCoordinator") + } + + @Test + fun aReplacementIntentDropsAResolvedPendingLink() { + val owner = Intent(activity, FrontEndActivity::class.java) + val ticket = coordinator.beginLink(owner) + assertTrue(coordinator.resolve(ticket, GameRequest(id = "app"))) + + supersede() + + assertFalse(coordinator.hasPending()) + assertNull(coordinator.pendingLink()) + } + + @Test + fun aReplacementIntentInvalidatesAnAcceptedLaunch() { + val ticket = coordinator.beginLaunch() + assertTrue(coordinator.isCurrent(ticket)) + + supersede() + + assertFalse(coordinator.isCurrent(ticket)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + @Test + fun anActionSetupIntentSupersedesTheGameLinkItReplaced() { + val owner = Intent(activity, FrontEndActivity::class.java) + val ticket = coordinator.beginLink(owner) + assertTrue(coordinator.resolve(ticket, GameRequest(id = "app"))) + + deliver(Intent(activity, FrontEndActivity::class.java).setAction(SteamIntegration.ACTION_SETUP)) + + assertFalse(coordinator.hasPending()) + assertFalse(coordinator.isCurrent(ticket)) + assertNull(shadowOf(activity).nextStartedActivity) + } + + private fun supersede() { + ReflectionHelpers.callInstanceMethod(activity, "supersedeUncommittedLaunch") + } + + /** onNewIntent() is protected, which is exactly how the platform delivers a replacement intent. */ + private fun deliver(intent: Intent) { + val method = FrontEndActivity::class.java.getDeclaredMethod("onNewIntent", Intent::class.java) + method.isAccessible = true + try { + method.invoke(activity, intent) + } finally { + method.isAccessible = false + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt index 6338889980..a554a647bb 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/DeviceSupportTest.kt @@ -11,4 +11,10 @@ class DeviceSupportTest { // A PowerVR HAL without usable DRM access also reaches this unavailable case. assertFalse(DeviceSupport.graphicsAvailable(adreno = false, powerVrReady = false)) } + + @Test fun bridgeServesEveryNonAdrenoWithoutASystemDriverRoute() { + assertTrue(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = false)) + assertFalse(DeviceSupport.bridgeUsable(adreno = true, systemDriverReady = false)) + assertFalse(DeviceSupport.bridgeUsable(adreno = false, systemDriverReady = true)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt index e0fcc5593a..5409eee150 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedExesTest.kt @@ -92,6 +92,38 @@ class AddedExesTest { } } + @Test fun reselectingTheCurrentExeKeepsItWhenTheRankingChanges() { + val storage = tmp.newFolder("Ranked") + exe(File(storage, "Example/Example.exe")) + exe(File(storage, "Example/Other.exe")) + SessionPrefs.setAddedGamesDirs(app, emptyList()) + SessionPrefs.setGameStorage(app, storage.path, "Card") + val folder = File(storage, "Example") + val current = AddedGames.scan(app).single { it.folder == folder }.exe + val other = listOf("Example.exe", "Other.exe").map { File(folder, it) }.single { it.path != current.path } + val existing = AddedGames.addExe(app, current) + assertTrue(existing is AddedGames.AddResult.Existing) + assertEquals(current.path, SessionPrefs.addedGameExe(app, folder.path)) + File(folder, "MicrosoftGame.config").writeText("") + assertEquals(other.path, AddedGames.rank(folder).exes.first().path) + assertEquals(current.path, AddedGames.scan(app).single { it.folder == folder }.exe.path) + } + + @Test fun reselectingASteamInstallsExeThroughAnAliasStoresTheReachablePath() { + val storage = tmp.newFolder("Aliased") + val pick = exe(File(storage, "steamapps/common/Example/Example.exe")) + File(storage, "steamapps/appmanifest_123.acf").writeText("\"installdir\" \"Example\"") + SessionPrefs.setAddedGamesDirs(app, emptyList()) + SessionPrefs.setGameStorage(app, storage.path, "Card") + val alias = File(tmp.newFolder("Links"), "Example.exe") + java.nio.file.Files.createSymbolicLink(alias.toPath(), pick.toPath()) + assertTrue(AddedGames.addExe(app, alias) is AddedGames.AddResult.Existing) + assertEquals(pick.path, AddedExes.list(app).single { it.folder == pick.parentFile!!.path }.exe) + assertEquals(pick.path, SessionPrefs.addedGameExe(app, pick.parentFile!!.path)) + assertEquals(pick.path, AddedGames.scan(app).single { it.folder == pick.parentFile }.exe.path) + AddedExes.drop(app, pick.parentFile!!.path) + } + @Test fun anotherExeInTheSameGameSwitchesItsExe() { noGamesFolders() val first = onStorage("Games2/Hades/Hades.exe") @@ -297,6 +329,39 @@ class AddedExesTest { assertEquals(listOf(other.path), AddedGames.scan(app).map { it.exe.path }) } + private fun routeEveryGameTo(steamApp: Int) { + val config = File(SessionPrefs.activeSteamRoot(app), "userdata/123/config").apply { mkdirs() } + val routes = org.json.JSONObject() + AddedGames.scan(app).forEach { routes.put(it.appId.toString(), steamApp) } + File(config, ".droiddeck-routes.json").writeText(routes.toString()) + } + + @Test fun anotherProgramOfASteamInstallIsNotRoutedToTheSteamApp() { + noGamesFolders() + val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe") + val launcher = onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe") + AddedExes.put(app, AddedExes.Entry(main.parent!!, launcher.path)) + routeEveryGameTo(250900) + val game = AddedGames.scan(app).single() + assertEquals(launcher.path, game.exe.path) + assertEquals(main.path, game.candidates.first().path) + assertNull(game.steamAppId) + assertTrue(!game.steamProgram) + assertTrue(File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("\"route\":false")) + } + + @Test fun theSteamAppsOwnProgramStillRoutesToTheSteamApp() { + noGamesFolders() + val main = onStorage("Games2/The Binding of Isaac Rebirth/isaac-ng.exe") + onStorage("Games2/The Binding of Isaac Rebirth/REPENTOGONLauncher.exe") + AddedExes.put(app, AddedExes.Entry(main.parent!!, main.path)) + routeEveryGameTo(250900) + val game = AddedGames.scan(app).single() + assertEquals(250900, game.steamAppId) + assertTrue(game.steamProgram) + assertTrue(!File(AddedGames.writeListing(app, listOf(game), emptyList()).path).readText().contains("route")) + } + @Test fun aDifferentGameWithANumberedNameIsNotTakenAsAnotherBuild() { noGamesFolders() val held = onStorage("Games2/id/Doom/Doom.exe") diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt index 953c3989f1..6177547d58 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSteamEditsTest.kt @@ -47,6 +47,11 @@ class AddedGamesSteamEditsTest { .writeText(JSONObject().put("games", JSONObject().put(appId.toString(), game)).toString()) } + private fun legacyAdoption(exe: File, seen: Int) { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .putString("addedExe:${folder.path}", exe.path).putInt("addedExeSeen:${folder.path}", seen).commit() + } + private fun scanned() = AddedGames.scan(context).single { it.folder == folder } @Test fun aTargetChangedInSteamBecomesTheAppsChoiceOnce() { @@ -68,6 +73,65 @@ class AddedGamesSteamEditsTest { assertEquals(main.path, SessionPrefs.addedGameExe(context, folder.path)) } + @Test fun aTargetChosenInSteamKeepsTheSteamAppsRouteBeforeAndAfterItIsAdopted() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + assertEquals(250900, scanned().steamAppId) + + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1) + val adopted = scanned() + assertEquals(other, adopted.exe) + assertEquals(250900, adopted.steamAppId) + assertTrue(adopted.steamProgram) + + val later = scanned() + assertEquals(other, later.exe) + assertEquals(250900, later.steamAppId) + assertTrue(later.steamProgram) + } + + @Test fun aTargetAdoptedBeforeTheMarkerExistedKeepsTheSteamAppsRoute() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1) + legacyAdoption(other, 1) + assertNull(SessionPrefs.addedGameAdopted(context, folder.path, "Exe")) + val legacy = scanned() + assertEquals(other, legacy.exe) + assertEquals(250900, legacy.steamAppId) + assertTrue(legacy.steamProgram) + assertEquals(other.path, SessionPrefs.addedGameAdopted(context, folder.path, "Exe")) + } + + @Test fun aProgramPickedInDroidDeckThatSteamNeverEditedStaysOutOfTheRoute() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/Example.exe", 1) + legacyAdoption(other, 1) + val picked = scanned() + assertEquals(other, picked.exe) + assertNull(picked.steamAppId) + assertTrue(!picked.steamProgram) + } + + @Test fun aProgramChosenInDroidDeckAfterASteamEditLeavesTheSteamAppsRoute() { + val first = scanned() + val routes = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-routes.json") + routes.writeText(JSONObject().put(first.appId.toString(), 250900).toString()) + record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1) + assertEquals(other, scanned().exe) + + val third = File(folder, "Third.exe").apply { writeBytes(ByteArray(4)) } + SessionPrefs.setAddedGameExe(context, folder.path, third.path) + val chosen = scanned() + assertEquals(third, chosen.exe) + assertNull(chosen.steamAppId) + assertTrue(!chosen.steamProgram) + } + @Test fun theListingTellsTheSessionWhichSteamEditTheAppHasTaken() { val first = scanned() record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 3) diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt index 1c61034221..bdacbc4d6a 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesStoreScanTest.kt @@ -66,6 +66,27 @@ class AddedGamesStoreScanTest { assertTrue(game.guestExe.endsWith("/Tools/Editor.exe")) } + @Test fun everyStoreKeepsItsLauncherWhenItsOwnExeIsReselected() { + for (store in listOf(Store.GOG, Store.AMAZON, Store.EPIC)) { + val folder = install(store, "own-${store.id}", "Own ${store.label}", "Binaries/Game.exe", launcher = true) + val own = File(folder, "Binaries/Game.exe") + val before = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing) + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertEquals(own.path, game.exe.path) + assertTrue(game.guestExe.endsWith("/" + StoreLaunch.LAUNCHER)) + assertEquals(before.appId, game.appId) + } + } + + @Test fun aDifferentPickedExeOnAnyStoreGameIsRunDirectly() { + val folder = install(Store.GOG, "tool", "Tool GOG", "Binaries/Game.exe", launcher = true) + val tool = File(folder, "Tools/Editor.exe").apply { parentFile!!.mkdirs(); writeText("tool") } + AddedExes.put(app, AddedExes.Entry(folder.path, tool.path, picked = true)) + val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath } + assertTrue(game.guestExe.endsWith("/Tools/Editor.exe")) + } + @Test fun anOlderSidecarsSteamSwitchIsIgnoredEveryInstallIsListed() { val folder = install(Store.AMAZON, "amzn1.adg.product.x", "Yakuza 0", "Yakuza0.exe") val file = StoreGameSidecar.file(folder) diff --git a/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt new file mode 100644 index 0000000000..d88a9e7964 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/AxisPacingTest.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AxisPacingTest { + @Test fun theFirstReportIsWrittenAtOnce() { + assertEquals(100L, AxisPacing(4).dueAt(100, true)) + } + + @Test fun stickMotionInsideTheIntervalWaitsForItsEnd() { + val pacing = AxisPacing(4) + pacing.wrote(100) + assertEquals(104L, pacing.dueAt(101, true)) + assertEquals(104L, pacing.dueAt(103, true)) + assertEquals(104L, pacing.dueAt(104, true)) + assertEquals(110L, pacing.dueAt(110, true)) + } + + @Test fun buttonsAndRestTransitionsAreNeverHeldBack() { + val pacing = AxisPacing(4) + pacing.wrote(100) + assertEquals(101L, pacing.dueAt(101, false)) + } + + @Test fun onlyMotionThatStaysOffRestIsPaced() { + assertTrue(AxisPacing.keepsMoving(0, 0)) + assertTrue(AxisPacing.keepsMoving(1200, 1300)) + assertTrue(AxisPacing.keepsMoving(-40, 25)) + assertFalse(AxisPacing.keepsMoving(0, 900)) + assertFalse(AxisPacing.keepsMoving(900, 0)) + } + + @Test fun theIntervalRunsFromTheFlushNotFromTheRequest() { + val pacing = AxisPacing(4) + assertEquals(100L, pacing.dueAt(100, true)) + pacing.wrote(110) + assertEquals(114L, pacing.dueAt(111, true)) + } + + @Test fun aHeldReportIsReleasedOnlyAtItsDeadline() { + val pacing = AxisPacing(4) + assertTrue(pacing.hold(104)) + assertFalse(pacing.hold(104)) + assertFalse(pacing.release(103)) + assertTrue(pacing.release(104)) + assertFalse(pacing.release(105)) + } + + @Test fun aCallbackFromACancelledHoldCannotPublishTheNextHoldEarly() { + val pacing = AxisPacing(4) + assertTrue(pacing.hold(104)) + assertTrue(pacing.cancel()) + pacing.wrote(104) + assertTrue(pacing.hold(pacing.dueAt(105, true))) + assertFalse(pacing.release(105)) + assertTrue(pacing.release(108)) + } + + @Test fun cancellingWithNothingHeldRemovesNoCallback() { + val pacing = AxisPacing(4) + assertFalse(pacing.cancel()) + assertTrue(pacing.hold(104)) + assertTrue(pacing.release(104)) + assertFalse(pacing.cancel()) + } + + @Test fun aThousandHertzPadReachesTheGuestAtTheIntervalRate() { + val writes = feed(AxisPacing(4), sampleMs = 1, durationMs = 1000) + assertTrue("$writes writes", writes in 249..251) + } + + @Test fun aPadSlowerThanTheIntervalIsNeverDelayed() { + val pacing = AxisPacing(4) + for (now in 0L until 1000L step 5) { + assertEquals(now, pacing.dueAt(now, true)) + pacing.wrote(now) + } + } + + private fun feed(pacing: AxisPacing, sampleMs: Long, durationMs: Long): Int { + var writes = 0 + var pendingAt = -1L + for (now in 0L until durationMs step sampleMs) { + if (pendingAt in 0..now) { + pacing.wrote(pendingAt) + writes++ + pendingAt = -1 + } + val due = pacing.dueAt(now, true) + if (due <= now) { + pacing.wrote(now) + writes++ + } else if (pendingAt < 0) { + pendingAt = due + } + } + return writes + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt index 4fe7a60dc0..d8ea5ee185 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt @@ -45,7 +45,7 @@ class NativeGuestTest { val command = NativeGuest.command(root, "/usr/bin/env", listOf("-i", "A=1")) assertEquals(File(root, "usr/lib/ld-linux-aarch64.so.1").path, command[0]) assertEquals(listOf("--library-path", NativeGuest.libraryPath(root), "--argv0", "env", File(root, "usr/bin/env").path, "-i", "A=1"), command.drop(1)) - assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root)) + assertTrue("LD_LIBRARY_PATH" !in NativeGuest.environment(root, "/usr/bin/env")) } @Test @@ -79,13 +79,22 @@ class NativeGuestTest { @Test fun mountsWithoutADestinationMapToThemselves() { val root = rootWithLoader() - val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b")) + val env = NativeGuest.sessionEnvironment(root, listOf("/dev", "/a:/b"), "/usr/bin/env") assertEquals("/dev:/dev|/a:/b", env["DDNATV_BINDS"]) assertEquals(root.path, env["DDNATV_ROOT"]) assertTrue("LD_LIBRARY_PATH" !in env) assertTrue(env.getValue("LD_PRELOAD").replace(File.separatorChar, '/').endsWith("usr/lib/libddnatv-hook.so")) } + @Test + fun theProgramTheLoaderRunsIsNamedInItsEnvironment() { + val root = rootWithLoader() + val program = NativeGuest.command(root, "/usr/bin/env", listOf("-i"))[5] + assertEquals(program, NativeGuest.sessionEnvironment(root, listOf("/dev"), "/usr/bin/env")["DDNATV_REAL_EXE"]) + assertEquals(program, NativeGuest.environment(root, "/usr/bin/env")["DDNATV_REAL_EXE"]) + assertEquals(program, NativeGuest.builder(root, "/", listOf("/usr/bin/env", "-i"), emptyMap()).environment()["DDNATV_REAL_EXE"]) + } + private val linkRoot = "/data/user/0/app/files/linuxfs" private val sdBinds = listOf( "/mnt/media_rw/CARD/files/steam:/mnt/droiddeck-sd", diff --git a/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt new file mode 100644 index 0000000000..1ab248db85 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/DisplayDriverFromAutoTest.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.gpu.TurnipDriver +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class DisplayDriverFromAutoTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun noDisplayDriverChoiceIsAuto() { + SessionPrefs.setAndroidDriver(context, TurnipDriver.AUTO) + for (mode in listOf(SessionPrefs.GPU_DRIVERS_AUTO, SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) { + SessionPrefs.setGpuDriverMode(context, mode) + assertTrue(mode, SessionPrefs.displayDriverFromAuto(context)) + } + } + + @Test fun aPairDisplayHalfInstalledByAutoIsAuto() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0", "DD-Turnip_v0.8.0-linux")) + SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0") + assertTrue(SessionPrefs.displayDriverFromAuto(context)) + } + + @Test fun aDriverTheUserImportedStaysTheirChoiceUnderAuto() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0")) + SessionPrefs.setAndroidDriver(context, "user-import") + assertFalse(SessionPrefs.displayDriverFromAuto(context)) + } + + @Test fun anAutoInstalledDriverPickedByHandStaysTheUsersChoice() { + SessionPrefs.setGpuAutoInstalled(context, setOf("DD-Turnip_v0.8.0")) + SessionPrefs.setAndroidDriver(context, "DD-Turnip_v0.8.0") + for (mode in listOf(SessionPrefs.GPU_DRIVERS_MANUAL, SessionPrefs.GPU_DRIVERS_MIX)) { + SessionPrefs.setGpuDriverMode(context, mode) + assertFalse(mode, SessionPrefs.displayDriverFromAuto(context)) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt index 05ef3bdd33..ea6bd6238d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/EnhancedSessionLogShareTest.kt @@ -403,6 +403,23 @@ class EnhancedSessionLogShareTest { SessionLogShare.clear(app) } + @Test fun rpcs3LogIsSharedByNameWithTheGameLogs() { + val session = tmp.newFolder("2026-11-24-05-rpcs3") + session.resolve("session.log").writeText("session\n") + session.resolve("rpcs3").mkdirs() + session.resolve("rpcs3/RPCS3.log").writeText("PPU: compiling\n") + + val zips = EnhancedSessionLogShare.create(app, session) + fun entries(suffix: String) = ZipFile(zips.single { it.name.endsWith("-$suffix.zip") }).use { archive -> + archive.entries().toList().map { it.name } + } + + assertTrue(entries("games").contains("${session.name}/rpcs3/RPCS3.log")) + assertTrue(entries("session").contains("${session.name}/session.log")) + assertFalse(entries("games").contains("${session.name}/session.log")) + SessionLogShare.clear(app) + } + @Test fun unreadableDiscoverySubtreeKeepsOtherLogsAndMarksTheManifestPartial() { assumeFilePermissionsEnforced() assumeFalse(System.getProperty("os.name").startsWith("Windows")) diff --git a/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt new file mode 100644 index 0000000000..0a2feeed36 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/LaunchCoordinatorTest.kt @@ -0,0 +1,121 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test + +class LaunchCoordinatorTest { + @Test + fun aNewLaunchSupersedesAnOlderLaunch() { + val coordinator = LaunchCoordinator() + val first = coordinator.beginLaunch() + val second = coordinator.beginLaunch() + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + } + + @Test + fun anAllowedLaunchDropsThePendingLink() { + val coordinator = LaunchCoordinator() + coordinator.beginLink("link") + coordinator.beginLaunch() + assertFalse(coordinator.hasPending()) + } + + @Test + fun aLinkReadResolvesAndIsConsumed() { + val coordinator = LaunchCoordinator() + val ticket = coordinator.beginLink("link") + assertTrue(coordinator.resolve(ticket, "game")) + assertEquals("game", coordinator.pendingLink()?.request) + assertTrue(coordinator.consume(ticket)) + assertFalse(coordinator.hasPending()) + } + + @Test + fun aStaleLinkReadCannotReplaceTheNewLink() { + val coordinator = LaunchCoordinator() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + assertFalse(coordinator.resolve(first, "old")) + assertTrue(coordinator.resolve(second, "new")) + assertEquals("new", coordinator.pendingLink()?.request) + } + + @Test + fun handlingNeedsAResolvedLink() { + val coordinator = LaunchCoordinator() + val ticket = coordinator.beginLink("link") + assertFalse(coordinator.beginHandling(ticket)) + coordinator.resolve(ticket, "game") + assertTrue(coordinator.beginHandling(ticket)) + assertTrue(coordinator.isHandling(ticket)) + } + + @Test + fun aStaleCompletionCannotConsumeTheNewLink() { + val coordinator = LaunchCoordinator() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + coordinator.resolve(second, "new") + assertFalse(coordinator.consume(first)) + assertTrue(coordinator.hasPending()) + } + + @Test + fun aUiLaunchDropsThePendingLinkBeforeItLaunches() { + val coordinator = LaunchCoordinator() + coordinator.beginLink("link") + val launch = coordinator.beginLaunch() + assertNull(coordinator.pendingLink()) + assertTrue(coordinator.isCurrent(launch)) + } + + @Test + fun aSecondLinkReplacesTheFirst() { + val coordinator = LaunchCoordinator() + val first = coordinator.beginLink("first") + val second = coordinator.beginLink("second") + assertFalse(coordinator.isCurrent(first)) + assertTrue(coordinator.isCurrent(second)) + assertEquals("second", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkKeepsItsOwnerForIntentCleanup() { + val coordinator = LaunchCoordinator() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + assertSame("intent-a", coordinator.pendingLink()?.owner) + } + + @Test + fun aLinkIsOwnedOnlyByItsIntent() { + val coordinator = LaunchCoordinator() + val ticket = coordinator.beginLink("intent-a") + coordinator.resolve(ticket, "game") + val link = requireNotNull(coordinator.pendingLink()) + assertTrue(link.ownedBy("intent-a")) + assertFalse(link.ownedBy("intent-b")) + assertFalse(link.ownedBy(null)) + assertTrue(coordinator.consume(ticket)) + assertNull(coordinator.pendingLink()) + } + + @Test + fun cancelAllInvalidatesEveryOutstandingTicket() { + val coordinator = LaunchCoordinator() + coordinator.beginLaunch() + val link = coordinator.beginLink("link") + assertTrue(coordinator.isCurrent(link)) + coordinator.cancelAll() + assertFalse(coordinator.isCurrent(link)) + assertFalse(coordinator.hasPending()) + assertNull(coordinator.pendingLink()) + assertFalse(coordinator.resolve(link, "late")) + assertFalse(coordinator.consume(link)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index fb9199157b..f010e97a65 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.session import android.content.Context +import android.content.pm.ActivityInfo import org.junit.Assert.* import org.junit.Before import org.junit.Test @@ -74,6 +75,35 @@ class PortraitResolutionTest { assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) } + @Test fun followScreenInLandscapeLeavesAFixedPortraitSizeFixed() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.FOLLOW_SCREEN) + SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) + assertEquals(1f to null, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun followScreenInPortraitLeavesAFixedLandscapeSizeFixed() { + SessionPrefs.setResolutionChoice(app, "steam", "1080p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(2f), portrait = true) + assertEquals(null to 2f, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun followScalesKeepLinkedAndFixedChoices() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(1.5f)) + assertEquals(1.5f to 1.5f, SessionPrefs.followScales(app, "steam", panel)) + SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) + assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel)) + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + assertEquals(null to null, SessionPrefs.followScales(app, "steam", panel)) + } + + @Test fun anAutoOrientationIsNotChangedByFollowScreen() { + assertFalse(SessionPrefs.portrait(app)) + SessionPrefs.setOrientation(app, ActivityInfo.SCREEN_ORIENTATION_USER) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, true, 700)) + assertEquals(ActivityInfo.SCREEN_ORIENTATION_USER, SessionPrefs.windowOrientation(app, false, 700)) + } + @Test fun modesKeepSeparateChoices() { SessionPrefs.setResolutionChoice(app, "steam", "1080p", portrait = true) assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt index 3b996ae3d2..89baf52834 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSteamLogsTest.kt @@ -63,6 +63,70 @@ class SessionSteamLogsTest { assertFalse(File(out, "web.txt").readText().contains("abcdef123456")) } + private fun rpcs3Root(): Pair { + val root = tmp.newFolder("rootfs") + return root to File(root, "root/.cache/rpcs3").apply { mkdirs() } + } + + @Test fun rpcs3LogRewrittenThisSessionIsCollectedAloneAndRedacted() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(logs, "RPCS3.log").writeText("earlier run\n") + File(logs, "RPCS3.log.gz").writeBytes(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0)) + File(logs, "RPCS3.buf").writeText("lock\n") + SessionArtifacts.markRpcs3Log(session, root) + + File(logs, "RPCS3.log").writeText("PPU: compiling\nGET /x?sessionid=abcdef123456 200\n") + File(logs, "RPCS3.log.gz").appendBytes(byteArrayOf(1, 2, 3)) + File(logs, "RPCS3.buf").appendText("more\n") + + val copied = SessionArtifacts.copyRpcs3Log(logs, session, out) + assertEquals(listOf("RPCS3.log"), names(copied)) + val text = File(out, "RPCS3.log").readText() + assertTrue(text.startsWith("PPU: compiling\n")) + assertFalse(text.contains("abcdef123456")) + assertEquals(listOf("RPCS3.log"), out.list()!!.sorted()) + } + + @Test fun rpcs3LogFirstWrittenThisSessionIsCollected() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + SessionArtifacts.markRpcs3Log(session, root) + + File(logs, "RPCS3.log").writeText("first boot\n") + + assertEquals(listOf("RPCS3.log"), names(SessionArtifacts.copyRpcs3Log(logs, session, out))) + assertEquals("first boot\n", File(out, "RPCS3.log").readText()) + } + + @Test fun anRpcs3LogFromAnEarlierSessionIsNotCollected() { + val (root, logs) = rpcs3Root() + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(logs, "RPCS3.log").writeText("earlier run\n") + SessionArtifacts.markRpcs3Log(session, root) + + assertTrue(SessionArtifacts.copyRpcs3Log(logs, session, out).isEmpty()) + assertFalse(out.exists()) + } + + @Test fun anUnmarkedSessionCollectsNoRpcs3LogEvenWithSteamMarks() { + val (_, logs) = rpcs3Root() + val steam = tmp.newFolder("steam-logs") + val session = tmp.newFolder("session") + val out = File(session, "rpcs3") + File(steam, "console_log.txt").writeText("steam\n") + SessionArtifacts.markSteamLogs(session, steam) + File(logs, "RPCS3.log").writeText("another session's run\n") + + assertTrue(SessionArtifacts.copyRpcs3Log(logs, session, out).isEmpty()) + assertFalse(out.exists()) + File(steam, "console_log.txt").appendText("new\n") + assertEquals(listOf("console_log.txt"), names(SessionArtifacts.copySessionLogs(steam, session, tmp.newFolder("out")))) + } + @Test fun aCopyFailurePreservesThePreviousSnapshotAndRemovesPartialStaging() { val logs = tmp.newFolder("logs") val session = tmp.newFolder("session") diff --git a/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt new file mode 100644 index 0000000000..c5e9ab63fc --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/epic/EpicLoginTest.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.stores.epic + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class EpicLoginTest { + private fun innerText(body: String): String = JSONObject.quote(body) + + private fun corrective(action: String) = + """{"errorCode":"errors.com.epicgames.oauth.corrective_action_required","metadata":{"correctiveAction":"$action"}}""" + + private fun epicLogin() = EpicLogin("https://www.epicgames.com/id/authorize", "test-agent", "http://127.0.0.1/launcher/authorized") + + @Test fun aRedirectPageAskingForTermsIsACorrectiveAction() { + assertEquals("PRIVACY_POLICY_ACCEPTANCE", EpicLogin.correctiveAction(innerText(corrective("PRIVACY_POLICY_ACCEPTANCE")))) + assertEquals("EULA_ACCEPTANCE", EpicLogin.correctiveAction(innerText(corrective("EULA_ACCEPTANCE")))) + assertEquals("EULA_ACCEPTANCE", EpicLogin.correctiveAction(corrective("EULA_ACCEPTANCE"))) + assertEquals(EpicLogin.ACCOUNT_SIGN_IN_URL, epicLogin().browserStep(innerText(corrective("EULA_ACCEPTANCE")))) + } + + @Test fun aCorrectiveActionWithoutItsNameStillSelectsTheBrowserStep() { + val body = """{"errorCode":"errors.com.epicgames.oauth.corrective_action_required"}""" + assertEquals("unknown", EpicLogin.correctiveAction(innerText(body))) + assertEquals(EpicLogin.ACCOUNT_SIGN_IN_URL, epicLogin().browserStep(innerText(body))) + } + + @Test fun anAuthorizationCodeOrAnotherErrorStaysInTheSignInPage() { + val pages = listOf( + innerText("""{"warning":"Do not share this code with any 3rd party service.","redirectUrl":"https://localhost/launcher/authorized?code=c1","authorizationCode":"c1","sid":null}"""), + innerText("""{"errorCode":"errors.com.epicgames.common.authentication.authentication_failed","message":"Sorry"}"""), + innerText("Sign in"), + "null", + "", + ) + for (page in pages) { + assertNull(page, EpicLogin.correctiveAction(page)) + assertNull(page, epicLogin().browserStep(page)) + } + } + + @Test fun otherSignInFlowsHaveNoBrowserStep() { + val url = "https://www.epicgames.com/id/authorize?client_id=c85f4c6238b04d3399bc0080e83b83fd&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A41234%2Flauncher%2Fauthorized&state=x" + val flow = EpicClient.loginFlow(url, "test-browser")!! + assertNull(flow.browserStep(innerText(corrective("EULA_ACCEPTANCE")))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt new file mode 100644 index 0000000000..0ab95caf7f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PickVolumesTest.kt @@ -0,0 +1,88 @@ +package com.droiddeck.launcher.ui + +import android.os.Environment +import android.os.Process +import android.os.storage.StorageManager +import com.droiddeck.launcher.files.StorageRoot +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +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.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.StorageVolumeBuilder +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class PickVolumesTest { + @get:Rule val temporary = TemporaryFolder() + + private val internal = File("/storage/emulated/0") + + private fun root(label: String, path: String, removable: Boolean = true, readable: Boolean = true) = + StorageRoot(label, File(path), removable, readable) + + @Test fun aCardOnlyReachableThroughMediaRwIsListed() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated/0", removable = false), + root("4A1C-830B", "/mnt/media_rw/4A1C-830B"), + )) + + assertEquals(listOf("/storage/emulated/0", "/mnt/media_rw/4A1C-830B"), volumes.map { it.root.path }) + assertEquals("Internal storage", volumes.first().label) + assertFalse(volumes.first().removable) + assertEquals("4A1C-830B", volumes[1].label) + assertTrue(volumes[1].removable) + } + + @Test fun aVisibleCardKeepsItsStoragePathAndLabel() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated/0", removable = false), + root("SanDisk SD card", "/storage/1234-ABCD"), + root("USB drive", "/storage/5678-EF01"), + )) + + assertEquals(listOf("Internal storage", "SanDisk SD card", "USB drive"), volumes.map { it.label }) + assertEquals(File("/storage/1234-ABCD"), volumes[1].root) + } + + @Test fun unreadableVolumesAndInternalStorageAreNotListedTwice() { + val volumes = pickVolumes(internal, "Internal storage", listOf( + root("Internal", "/storage/emulated", removable = false), + root("Internal", "/storage/emulated/0/Android/data/com.droiddeck.launcher/files", removable = false), + root("SD card", "/storage/1234-ABCD", readable = false), + root("USB drive", "/mnt/media_rw/5678-EF01"), + root("USB drive", "/mnt/media_rw/5678-EF01"), + )) + + assertEquals(listOf("/storage/emulated/0", "/mnt/media_rw/5678-EF01"), volumes.map { it.root.path }) + } + + @Test fun withNoExternalVolumesOnlyInternalStorageIsListed() { + val volumes = pickVolumes(internal, "Internal storage", listOf(root("Internal", "/storage/emulated/0", removable = false))) + + assertEquals(listOf(internal), volumes.map { it.root }) + } + + @Test fun aMountedVolumeWithoutAnAppFolderReachesThePicker() { + val mount = temporary.newFolder("4A1C-830B") + val context = RuntimeEnvironment.getApplication() + val volume = StorageVolumeBuilder("public:179,1", mount, "SD card", Process.myUserHandle(), Environment.MEDIA_MOUNTED) + .setIsPrimary(false) + .setIsEmulated(false) + .setIsRemovable(true) + .build() + shadowOf(context.getSystemService(StorageManager::class.java)).addStorageVolume(volume) + + val card = pickVolumes(context).single { it.root.absoluteFile == mount.absoluteFile } + + assertEquals("SD card", card.label) + assertTrue(card.removable) + } +} diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index 8d366151e6..916fa30dc6 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -212,6 +212,12 @@ more, so its fix removes both variables, also from its launch options, and sets `vk_x11_strict_image_count=true`, the option Mesa's driconf gives the game. A per-game value in the environment editor still wins. +Dragon Quest Monsters 4 does not draw slime bodies at its default monster mesh +detail, leaving only their tips. Before each launch, DroidDeck sets +`r.SkeletalMeshLODBias=-4` and `r.SkeletalMeshLODRadiusScale=0.25` under +`[SystemSettings]` in the game's `Engine.ini`. It does this every time because the +game ignores `-ini:` overrides and deletes a writable `Engine.ini` after reading it. + ## Defaults and available suggestions The initial configuration enables Mesa shader caching with diff --git a/docs/development/steam-display-scaling.md b/docs/development/steam-display-scaling.md index a5c5a674f0..a0594fb0d7 100644 --- a/docs/development/steam-display-scaling.md +++ b/docs/development/steam-display-scaling.md @@ -215,6 +215,15 @@ Still to check by hand: pasting Android text into a game. Force fullscreen is still unsafe without a matching Game Resolution: with the default (native), a game drawing at another size fights it as in run 4. It stays off by default. +## Stretch 16:9 with two Xwayland servers + +With "Stretch 16:9 to panel" the games' server starts at the 16:9 nested size, but the client sets it +to the output size at every launch (run 7), so games saw a near-square screen and letterboxed +themselves. While stretching, the session script rewrites a `GAMESCOPE_XWAYLAND_MODE_CONTROL` that +sizes the game server (`1`) to exactly the output into the nested size with `allow_super_res` set, +since gamescope otherwise clamps it to the output. A Game Resolution chosen in Steam is a different +size and is kept. + ## Force fullscreen removed (`feat/remove-force-fullscreen`) With games on their own Xwayland server, FlatOut 2 no longer shrinks under the QAM, which was the diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 52d69934fc..5ebaf5cdfd 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -60,7 +60,9 @@ missing prefix is removed first, and nothing is copied. The account's `.droiddeck-routes.json` maps shortcut IDs to real Steam app IDs so the Android launcher uses the same title and Proton prefix as Steam. Other accounts do not -inherit those routes. Managed shortcuts are replaced; user-created shortcuts and +inherit those routes. A program chosen in DroidDeck other than the folder's default executable (for example a mod +launcher beside the game's own executable) is never routed: it stays its own shortcut and tile. +A target set in the Steam shortcut's properties keeps the route. Managed shortcuts are replaced; user-created shortcuts and unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton registration. diff --git a/tools/build_local.sh b/tools/build_local.sh index 2c76362956..b5d15acea6 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -312,6 +312,12 @@ else mkdir -p "${linuxfs_dir}/usr/local/lib/droiddeck" "${linuxfs_dir}/usr/local/share/licenses/uruntime" install -m644 "${uruntime_binary}" "${linuxfs_dir}/usr/local/lib/droiddeck/uruntime" install -m644 "${repo_root}/tools/linuxfs/licenses/uruntime-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/uruntime/LICENSE" + dwarfs_wrapper=$(cached "${DWARFS_SHA256}" "${DWARFS_ASSET}" \ + bash -c 'curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o "$out" "$0"' "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}") + mkdir -p "${linuxfs_dir}/usr/local/share/licenses/dwarfs" + bash "${repo_root}/tools/linuxfs/unwrap-dwarfs.sh" "${dwarfs_wrapper}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract" + printf '%s %s\n' "${DWARFS_PAYLOAD_SHA256}" "${linuxfs_dir}/usr/local/lib/droiddeck/dwarfsextract" | shasum -a 256 -c - >&2 + install -m644 "${repo_root}/tools/linuxfs/licenses/dwarfs-LICENSE" "${linuxfs_dir}/usr/local/share/licenses/dwarfs/LICENSE" sync_assets="${repo_root}/app/src/main/assets/droiddeck-esync" if [[ -f "${repo_root}/tools/droiddeck-esync/release.env" ]]; then diff --git a/tools/components/recipes.json b/tools/components/recipes.json index 5fd8ca4bc2..5cccf80ffa 100644 --- a/tools/components/recipes.json +++ b/tools/components/recipes.json @@ -8,6 +8,7 @@ "tools/linuxfs/desktop", "tools/linuxfs/licenses", "tools/linuxfs/uruntime.env", + "tools/linuxfs/unwrap-dwarfs.sh", "tools/gamescope/release.env", "tools/wlroots/release.env", "tools/mangoapp", diff --git a/tools/components/recipes/runtime.sh b/tools/components/recipes/runtime.sh index aa5273d270..9de7efba18 100644 --- a/tools/components/recipes/runtime.sh +++ b/tools/components/recipes/runtime.sh @@ -26,6 +26,13 @@ echo "${URUNTIME_SHA256} uruntime" | sha256sum -c - install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime" install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE" rm uruntime +curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o dwarfs-wrapper "https://github.com/mhx/dwarfs/releases/download/${DWARFS_VERSION}/${DWARFS_ASSET}" +echo "${DWARFS_SHA256} dwarfs-wrapper" | sha256sum -c - +bash tools/linuxfs/unwrap-dwarfs.sh dwarfs-wrapper dwarfsextract +echo "${DWARFS_PAYLOAD_SHA256} dwarfsextract" | sha256sum -c - +install -Dm644 dwarfsextract "$D/usr/local/lib/droiddeck/dwarfsextract" +install -Dm644 tools/linuxfs/licenses/dwarfs-LICENSE "$D/usr/local/share/licenses/dwarfs/LICENSE" +rm dwarfs-wrapper dwarfsextract M="$D/usr/local/lib/mangoapp" mkdir -p "$M" mango-pkgs grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index cc719ce35b..bf14bf25b5 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -416,3 +416,12 @@ changed focus. In a nested session with no other window the SDL window stayed hi on screen. Focus is now chosen again whenever a window's opacity crosses zero in either direction; a change between two visible opacities leaves focus alone. `tools/tests/test_gamescope_focus_opacity.py` compiles the rule from this patch and checks the property handler applies it. + +## 0141 wlserver: the nested mouse moves the pointer while touch is Disabled + +The nested Wayland pointer reaches wlserver as touch 0 (`bAlwaysWarpCursor`, see 0111), and in the Disabled touch click +mode `wlserver_touchmotion` returned before anything moved. Buttons take `wlserver_mousebutton`, so they still arrived, +at a pointer that never left the top-left corner. Steam picks Disabled for some games (Don't Starve Together): the drawn +cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as +in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the +branch from this patch. diff --git a/tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch b/tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch new file mode 100644 index 0000000000..c165ccc50b --- /dev/null +++ b/tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch @@ -0,0 +1,16 @@ +diff --git a/src/wlserver.cpp b/src/wlserver.cpp +index df352b0..9740875 100644 +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -3326,7 +3326,10 @@ void wlserver_touchmotion( double x, double y, int touch_id, uint32_t time, bool + } + else if ( eMode == gamescope::TouchClickModes::Disabled ) + { +- return; ++ if ( !bAlwaysWarpCursor ) ++ return; ++ ++ wlserver_mousewarp( tx, ty, time, false ); + } + else if ( eMode == gamescope::TouchClickModes::Trackpad ) + { diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index 64a809b7c9..6a1cdc4d08 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -118,6 +118,9 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then # On the system PowerVR driver, Firefox's hardware WebRender on zink leaves stale, half-drawn # frames; its software renderer draws correctly. [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export MOZ_ACCELERATED=0 + # The system driver's (PowerVR, Xclipse) libhybris Wayland swapchain needs the app compositor's Android-buffer + # protocol, which KWin lacks: Plasma's clients present through DRI instead. + [ "${DD_STEAM_GL_PRESENT:-}" = 1 ] && export LIBGL_KOPPER_DISABLE=true if [ -z "${KWIN_RENDER_NODES:-}" ]; then for node in /dev/dri/renderD0 /dev/dri/renderD307 /dev/dri/renderD*; do if [ -c "$node" ]; then export KWIN_RENDER_NODES="$node"; break; fi diff --git a/tools/linuxfs/licenses/dwarfs-LICENSE b/tools/linuxfs/licenses/dwarfs-LICENSE new file mode 100644 index 0000000000..747b40c737 --- /dev/null +++ b/tools/linuxfs/licenses/dwarfs-LICENSE @@ -0,0 +1,49 @@ +Parts of the DwarFS project are licensed under the MIT license, while others are +licensed under the GPL-3.0 license. In general, the code used to *read* DwarFS +images is licensed under the MIT license, while the code used to *write* DwarFS +images is licensed under the GPL-3.0 license. Also, all testing/benchmarking +code is currently licensed under the GPL-3.0 license. + +That means you can use `mkdwarfs` to create images and then use these images +with only the MIT-licensed code. + +The following libraries and associated header files are licensed under the +MIT license: + +- `dwarfs_common` +- `dwarfs_compressor` +- `dwarfs_decompressor` +- `dwarfs_extractor` +- `dwarfs_reader` + +The following libraries and associated header files are licensed under the +GPL-3.0 license: + +- `dwarfs_rewrite` +- `dwarfs_writer` + +Each header and source file should contain an SPDX identifier near the top +of the file. + +Please also check the licenses of the projects that DwarFS depends on. + +---- + +MIT License + +Copyright (c) Marcus Holland-Moritz + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks index e91b7090ff..24dd97d4c0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import hashlib import json import os diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory b/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory index 947c5bb1c3..86645bed2b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-diagnostic-inventory @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import argparse import hashlib import json diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index a25b755cee..af236125f7 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -27,6 +27,7 @@ GAME_ENVIRONMENT = os.path.join(HOME, ".config", "droiddeck", "game-environment. BIN_DIR = os.path.dirname(os.path.abspath(__file__)) PRELOADS = "/usr/local/lib/droiddeck-fex" URUNTIME = "/usr/local/lib/droiddeck/uruntime" +DWARFSEXTRACT = "/usr/local/lib/droiddeck/dwarfsextract" HOST_PRELOAD = "/etc/ld.so.preload" FEX_APPID = "3127680" OWN_FEX = "/usr/local" @@ -824,6 +825,30 @@ def extracted(): return os.path.isdir("squashfs-root") +def dwarfs_image(image): + try: + offset = appimage_offset(image) + with open(image, "rb") as f: + f.seek(offset) + return f.read(6) == b"DWARFS" + except (OSError, ValueError, struct.error): + return False + + +def dwarfs_extract(image): + clear_extracted() + os.mkdir("squashfs-root") + with open(image, "rb") as source: + status = subprocess.call([DWARFSEXTRACT, "--input", "/proc/self/fd/%d" % source.fileno(), + "--image-offset=%d" % appimage_offset(image), "--output", "squashfs-root", + "--log-level=error"], stdout=subprocess.DEVNULL, pass_fds=(source.fileno(),)) + if status == 0 and extracted(): + return True + say("dwarfsextract could not extract it (status %d)" % status) + clear_extracted() + return False + + def want_fex(): with locked(): update_own_fex() @@ -869,6 +894,10 @@ def extract(image): return 0 say("uruntime could not extract it (status %d)" % status) clear_extracted() + if os.access(DWARFSEXTRACT, os.X_OK) and dwarfs_image(image) and dwarfs_extract(image): + if x86: + want_fex() + return 0 fex = prepare() if x86 else None if fex is not None: status = subprocess.call([fex["bin"], image, "--appimage-extract"], stdout=subprocess.DEVNULL, diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index e620d47b2f..e1bee1c12a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -242,6 +242,57 @@ def skip_red_launcher(command): return command +DQM4_MESH_DETAIL = {"r.SkeletalMeshLODBias": "-4", "r.SkeletalMeshLODRadiusScale": "0.25"} + + +def with_system_settings(text, settings): + lines = text.splitlines() + try: + section = lines.index("[SystemSettings]") + except ValueError: + if lines and lines[-1].strip(): + lines.append("") + lines.append("[SystemSettings]") + section = len(lines) - 1 + end = next((i for i in range(section + 1, len(lines)) if lines[i].startswith("[")), len(lines)) + block = [line for line in lines[section + 1:end] if line.split("=", 1)[0].strip() not in settings] + while block and not block[-1].strip(): + block.pop() + block += ["%s=%s" % item for item in settings.items()] + tail = lines[end:] + return "\n".join(lines[:section + 1] + block + ([""] if tail else []) + tail) + "\n" + + +# The game ignores -ini: overrides and deletes a writable Engine.ini after reading it, so this runs at every launch. +def dragon_quest_monsters_4_mesh_detail(exe, env): + project = Path(exe).stem.split("-", 1)[0] + if not project.lower().startswith("dragonquestmonsters4"): + return + prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx" + config = prefix / "drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini" + try: + if not prefix.is_dir(): + return + text = config.read_text(encoding="utf-8") if config.exists() else "" + updated = with_system_settings(text, DQM4_MESH_DETAIL) + if updated == text: + return + config.parent.mkdir(parents=True, exist_ok=True) + handle, staged = tempfile.mkstemp(prefix=".engine-", dir=config.parent) + try: + with os.fdopen(handle, "w", encoding="utf-8") as target: + target.write(updated) + if config.exists(): + os.chmod(staged, config.stat().st_mode & 0o7777) + os.replace(staged, config) + except BaseException: + os.unlink(staged) + raise + print("droiddeck-game-env: Dragon Quest Monsters 4: full-detail monster meshes", file=sys.stderr) + except (OSError, UnicodeDecodeError) as error: + print("droiddeck-game-env: Dragon Quest Monsters 4 mesh detail left as is (%s)" % error, file=sys.stderr) + + UBISOFT_LAUNCHER = "drive_c/Program Files (x86)/Ubisoft/Ubisoft Game Launcher" UBISOFT_SETTINGS = "drive_c/users/steamuser/AppData/Local/Ubisoft Game Launcher/settings.yaml" @@ -1412,6 +1463,7 @@ def main(): command = skip_red_launcher(command) if len(command) > 2: death_stranding_allocator(app_id, command[2]) + dragon_quest_monsters_4_mesh_detail(command[2], effective_env) ubisoft_overlay_off(env) project_zomboid_jvm(command) fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], []) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime b/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime index d6fd4cd3bc..f296a57c6a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import json import os import select diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 61dbb5feda..8bcf875fce 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -540,7 +540,7 @@ if [ -z "${DD_INSIDE:-}" ]; then args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h") if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then args+=(-S stretch) - export DD_STRETCHED=1 + export DD_STRETCHED=1 DD_STRETCH_OUTPUT="${width}x${height}" DD_STRETCH_GAME="${nested}x${nested_h}" fi if [ "${DD_REFRESH:-0}" -gt 0 ]; then args+=(-r "$DD_REFRESH") @@ -593,6 +593,12 @@ dd_xprop_set_all() { done [ "$ok" = 1 ] } +dd_stretch_game_screen() { + local idx w h super + IFS=', ' read -r idx w h super <<<"$1" + [ "$idx" = 1 ] && [ "${w}x${h}" = "$2" ] && [ "${super:-0}" = 0 ] || return 1 + xprop -root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL "$idx, ${3%x*}, ${3#*x}, 1" 2>/dev/null +} export GDK_BACKEND=x11 QT_QPA_PLATFORM=xcb SDL_VIDEODRIVER=x11 reap_orphans() { local round p stat pid left @@ -1205,7 +1211,7 @@ case $mode in [ "${DD_STRETCHED:-0}" = 1 ] && stretch=1 [ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1 atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP) - [ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER) + [ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER GAMESCOPE_XWAYLAND_MODE_CONTROL) prop_value() { case $1 in *'not found'*|*=) pv=$2; return ;; esac pv=${1#*=} @@ -1273,6 +1279,11 @@ case $mode in xprop -root -f GAMESCOPE_NEW_SCALING_SCALER 32c -set GAMESCOPE_NEW_SCALING_SCALER 4 2>/dev/null \ && echo "== stretch 16:9 to panel: the client's scaler was Auto, set to Stretch" ;; + GAMESCOPE_XWAYLAND_MODE_CONTROL*) + prop_value "$line" "" + dd_stretch_game_screen "$pv" "$DD_STRETCH_OUTPUT" "$DD_STRETCH_GAME" \ + && echo "== stretch 16:9 to panel: the client sized the game screen to the output ($DD_STRETCH_OUTPUT), set to $DD_STRETCH_GAME" + ;; esac done < <(xprop -spy -root "${atoms[@]}" 2>/dev/null) ) & diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index c618cadf35..a3cbb9578e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 import ctypes as C import functools import json @@ -71,6 +71,10 @@ def store_game(game): return bool(game.get("store")) +def steam_program(game): + return game.get("route") is not False + + def manifest_ids(steamapps, name): matches = [] try: @@ -230,7 +234,7 @@ def remember_tried(steam_root, account, appids): def watch(steam_root, listing): - games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")] + games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native") and steam_program(game)] if os.environ.get("DD_STEAM_OFFLINE") == "1" or not games: return candidates, sources = {}, {} @@ -526,6 +530,13 @@ def release(steam_root, game, stale, reason): print(f"droiddeck-steam-games: {game.get('name', appid)} {reason}; it is no longer Steam app {appid}") +def release_stale(steam_root, game, stale): + try: + release(steam_root, game, stale, "names another Steam app now") + except OSError as error: + print(f"droiddeck-steam-games: earlier import not undone ({error})") + + PREFIX_LINKS = ".droiddeck-prefix-links.json" @@ -603,17 +614,18 @@ def route(steam_root, acct, games): if game.get("native"): shortcuts.append(game) continue + if not steam_program(game): + release_stale(steam_root, game, lambda old: old == SPACEWAR) + share_prefix(steam_root, game) + shortcuts.append(game) + continue folder = game.get("folder", "") appid = candidates.get(folder, candidates.get(legacy_path(folder))) stamp = source_stamp(game) recorded = sources.get(folder, sources.get(legacy_path(folder))) current = stamp is not None and recorded in (stamp, [stamp[0], legacy_path(stamp[1])] + stamp[2:]) named = isinstance(appid, int) and 0 < appid < 0x80000000 and appid != SPACEWAR - try: - release(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid), - "names another Steam app now") - except OSError as error: - print(f"droiddeck-steam-games: earlier import not undone ({error})") + release_stale(steam_root, game, lambda old: old == SPACEWAR or (current and named and old != appid)) confirmed = named and current and owned.get(str(appid)) is True if confirmed: try: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts index fc35c0fec3..31d679677c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/python3 """Import added games while Steam is closed, preserving user-created shortcuts. Usage: droiddeck-steam-shortcuts diff --git a/tools/linuxfs/preload/descriptor.c b/tools/linuxfs/preload/descriptor.c index 686030988c..5f2c19ed22 100644 --- a/tools/linuxfs/preload/descriptor.c +++ b/tools/linuxfs/preload/descriptor.c @@ -31,7 +31,7 @@ static int store_root(char *out, size_t size) { return n > 0 && (size_t)n < size ? n : -1; } -static int store_exists(void) { +static __attribute__((noinline)) int store_exists(void) { char root[PATH_MAX]; if (store_seen) return 1; @@ -223,10 +223,18 @@ int fremovexattr(int fd, const char *name) { return 0; } +static int watched(void) { + int saved = errno, found; + + found = dd_is_wineserver() && store_exists(); + errno = saved; + return found; +} + static int tracked(const char *path, char *out, size_t size) { int saved = errno, found; - found = dd_is_wineserver() && store_exists() && resolved(path, out, size) == 0; + found = resolved(path, out, size) == 0; errno = saved; return found; } @@ -258,22 +266,30 @@ static void follow(const char *from, const char *to) { errno = saved; } -__attribute__((visibility("hidden"))) -int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { +static __attribute__((noinline)) int removed(const char *path, int (*real)(const char *), int folder) { char target[PATH_MAX]; int known = tracked(path, target, sizeof(target)), result = real(path); - if (result == 0 && known) forget(target, 0); + if (result == 0 && known) forget(target, folder); + return result; +} + +static __attribute__((noinline)) int moved(const char *from, const char *to, int (*real)(const char *, const char *)) { + char old[PATH_MAX], new[PATH_MAX]; + int known = tracked(from, old, sizeof(old)), result = real(from, to); + + if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); return result; } __attribute__((visibility("hidden"))) -int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { - char target[PATH_MAX]; - int known = tracked(path, target, sizeof(target)), result = real(path); +int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { + return watched() ? removed(path, real, 0) : real(path); +} - if (result == 0 && known) forget(target, 1); - return result; +__attribute__((visibility("hidden"))) +int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { + return watched() ? removed(path, real, 1) : real(path); } __attribute__((visibility("hidden"))) @@ -283,9 +299,5 @@ int dd_descriptor_remove(const char *path, int (*real)(const char *)) { __attribute__((visibility("hidden"))) int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) { - char old[PATH_MAX], new[PATH_MAX]; - int known = tracked(from, old, sizeof(old)), result = real(from, to); - - if (result == 0 && known && tracked(to, new, sizeof(new))) follow(old, new); - return result; + return watched() ? moved(from, to, real) : real(from, to); } diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index 4dd7d1f115..54aac381fa 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -1146,7 +1146,7 @@ static int steam_runtime_path(const char *path) { const char *name = strrchr(path, '/'); size_t i; - if (name == NULL || strcmp(name + 1, "steam") != 0) return 0; + if (name == NULL || (strcmp(name + 1, "steam") != 0 && strcmp(name + 1, "streaming_client") != 0)) return 0; for (i = 0; i < sizeof(runtimes) / sizeof(runtimes[0]); i++) { size_t length = strlen(runtimes[i]); diff --git a/tools/linuxfs/preload/tracer.c b/tools/linuxfs/preload/tracer.c index ec8dd003f9..4b12a1d6a7 100644 --- a/tools/linuxfs/preload/tracer.c +++ b/tools/linuxfs/preload/tracer.c @@ -72,15 +72,12 @@ static int read_only_copy(const char *data, size_t len, int flags) { return ro; } -__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { +static __attribute__((noinline)) int status_copy(const char *path, int flags, long pid) { char text[STATUS_MAX]; size_t len = 0; int saved = errno; int out = -1; - long pid; - if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) - return -1; // through the next open(): the native userland's hook gives the app's ids as root's there static int (*next_open)(const char *, int, ...) = NULL; if (!next_open) next_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open"); @@ -116,3 +113,10 @@ done: errno = saved; return out; } + +__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { + long pid; + if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) + return -1; + return status_copy(path, flags, pid); +} diff --git a/tools/linuxfs/unwrap-dwarfs.sh b/tools/linuxfs/unwrap-dwarfs.sh new file mode 100755 index 0000000000..2956967667 --- /dev/null +++ b/tools/linuxfs/unwrap-dwarfs.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +wrapper=${1:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT} +output=${2:?usage: unwrap-dwarfs.sh WRAPPER OUTPUT} +[ "$(tail -c 32 "$wrapper" | head -c 8)" = "SQUEEZE!" ] || { echo "unwrap-dwarfs.sh: $wrapper has no SQUEEZE! trailer" >&2; exit 1; } +packed=$(tail -c 16 "$wrapper" | od -An -tu8 -N8 | tr -d ' ') +[ "$packed" -gt 0 ] && [ "$packed" -le $(( $(wc -c < "$wrapper") - 32 )) ] || { echo "unwrap-dwarfs.sh: bad payload size in $wrapper" >&2; exit 1; } +tail -c $((packed + 32)) "$wrapper" | head -c "$packed" | zstd -dcq > "$output" diff --git a/tools/linuxfs/uruntime.env b/tools/linuxfs/uruntime.env index f1b445d860..55e73d3eff 100644 --- a/tools/linuxfs/uruntime.env +++ b/tools/linuxfs/uruntime.env @@ -1,3 +1,7 @@ URUNTIME_VERSION=v0.8.1 URUNTIME_ASSET=uruntime-appimage-lite-aarch64 URUNTIME_SHA256=8485ae20eb0bfd4eaeac38d7fd7f78e153b391c718cf33ff07879605683be1ea +DWARFS_VERSION=v0.15.7 +DWARFS_ASSET=dwarfs-fuse-extract-0.15.7-Linux-aarch64 +DWARFS_SHA256=edb698186db6b162c755770ffabfcc05482bb7105a716fd943548e64244b0fd2 +DWARFS_PAYLOAD_SHA256=cc3b3e342ca6537139d8c90d3c0a00236cf786bb61bdccf019e5ed0ca5917a7a diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index 3468b57b9c..1ae6b19a28 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -134,8 +134,11 @@ static void init_ddnatv_hook(void) { // environment is kept in. A program that had changed its environment (putenv, setenv) and passed it // to execv() before its first call into the hook handed the exec code a block that was freed by the // time it was read. -__attribute__((constructor(103))) static void init_ddnatv_hook_early(void) { +static void compact_loader_args(int argc, char **argv); + +__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) { init_ddnatv_hook(); + compact_loader_args(argc, argv); // The kernel names the process after what it executed, the rootfs ld.so: process monitors, and // the app's own checks of /proc//comm (steam, wineserver), saw only "ld-linux-aarch64.so.1" const char *name = program_invocation_short_name; @@ -232,27 +235,39 @@ static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) { return fn; } -static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { - char path[64]; - snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid); - int fd = open(path, O_RDONLY | O_CLOEXEC); - if (fd < 0) return 0; - size_t cap = 65536, used = 0, keylen = strlen(key); - char *env = malloc(cap + 1); - ssize_t got; - while (env && (got = read(fd, env + used, cap - used)) > 0) { +static char *read_proc_file(const char *path, size_t *len, int *whole) { + *len = 0; + *whole = 0; + int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return NULL; + size_t cap = 65536, used = 0; + char *text = malloc(cap + 1); + ssize_t got = 0; + while (text && (got = (ssize_t)syscall(SYS_read, fd, text + used, cap - used)) > 0) { used += (size_t)got; if (used == cap) { - char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL; + char *bigger = cap < (8u << 20) ? realloc(text, cap * 2 + 1) : NULL; if (!bigger) break; - env = bigger; + text = bigger; cap *= 2; } } - close(fd); + syscall(SYS_close, fd); + if (!text) return NULL; + text[used] = '\0'; + *len = used; + *whole = got == 0; + return text; +} + +static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { + char path[64]; + snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid); + size_t used, keylen = strlen(key); + int whole; + char *env = read_proc_file(path, &used, &whole); int found = 0; if (env) { - env[used] = '\0'; for (char *e = env; e < env + used; e += strlen(e) + 1) { if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') { ddnatv_copy_cstr(out, outsz, e + keylen + 1); @@ -265,6 +280,94 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { return found; } +static int is_loader_option(const char *arg) { + return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0; +} + +static int is_exec_loader(const char *path) { + const char *base = strrchr(path, '/'); + return strcmp(base ? base + 1 : path, "libddexec.so") == 0; +} + +static size_t next_arg(const char *text, size_t pos) { + return pos + strlen(text + pos) + 1; +} + +static uintptr_t *execfn_entry(int argc, char **argv) { + if (argv[argc]) return NULL; + char **env = argv + argc + 1; + while (*env) env++; + for (uintptr_t *aux = (uintptr_t *)(env + 1); aux[0] != AT_NULL; aux += 2) { + if (aux[0] == AT_EXECFN) return aux + 1; + } + return NULL; +} + +static void compact_loader_args(int argc, char **argv) { + if (g_ddnatv_root[0] == '\0' || argc < 1 || !argv || !argv[0]) return; + size_t len; + int whole; + char *text = read_proc_file("/proc/self/cmdline", &len, &whole); + size_t *at = text && whole && len > 0 && text[len - 1] == '\0' ? malloc(sizeof(size_t) * (size_t)argc) : NULL; + size_t pos = 0, program = 0; + if (at && is_exec_loader(text)) { + pos = next_arg(text, pos); + if (pos < len) pos = next_arg(text, pos); + } + int ok = at && pos < len && is_ld_linux(text + pos), named = 0; + if (ok) pos = next_arg(text, pos); + while (ok && pos < len && is_loader_option(text + pos)) { + size_t value = next_arg(text, pos); + ok = value < len; + if (ok && strcmp(text + pos, "--argv0") == 0) { + at[0] = value; + named = 1; + } + if (ok) pos = next_arg(text, value); + } + int count = 0; + if (ok && named && pos < len) { + program = pos; + pos = next_arg(text, pos); + for (count = 1; pos < len && count < argc; count++) { + at[count] = pos; + pos = next_arg(text, pos); + } + } + char *base = count == argc && pos == len ? argv[0] - at[0] : NULL; + for (int i = 1; base && i < argc; i++) { + if (argv[i] != base + at[i]) base = NULL; + } + if (base && memcmp(base, text, len) != 0) base = NULL; + uintptr_t *execfn = base ? execfn_entry(argc, argv) : NULL; + char *execfn_text = NULL; + if (execfn && *execfn >= (uintptr_t)base && *execfn < (uintptr_t)base + len) { + execfn_text = strdup(text + (*execfn - (uintptr_t)base)); + if (!execfn_text) base = NULL; + } + if (base) { + char *old_name = argv[0]; + size_t name_len = strlen(old_name); + char *name = program_invocation_name, *short_name = program_invocation_short_name; + size_t used = 0; + for (int i = 0; i < argc; i++) { + size_t n = strlen(text + at[i]) + 1; + memcpy(base + used, text + at[i], n); + argv[i] = base + used; + used += n; + } + memset(base + used, 0, len - used); + if (name >= old_name && name <= old_name + name_len) program_invocation_name = argv[0] + (name - old_name); + if (short_name >= old_name && short_name <= old_name + name_len) { + program_invocation_short_name = argv[0] + (short_name - old_name); + } + if (g_real_exe[0] == '\0') ddnatv_copy_cstr(g_real_exe, sizeof(g_real_exe), text + program); + if (execfn_text) *execfn = (uintptr_t)execfn_text; + } + free(at); + free(text); +} + // Overlay filesystems report a different device to stat() than in /proc//maps; the path, as the // kernel resolved it, then stands in for the device. static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) { @@ -320,9 +423,7 @@ static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz) ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1); if (n <= 0) return -1; loader[n] = '\0'; - const char *base = strrchr(loader, '/'); - base = base ? base + 1 : loader; - if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1; + if (!is_exec_loader(loader) && !is_ld_linux(loader)) return -1; char real_exe[PATH_MAX] = ""; if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) { diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index 440c682cd8..4b2da89133 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -99,7 +99,7 @@ def required(): for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']] paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so', 'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard', - 'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', + 'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', 'usr/local/lib/droiddeck/dwarfsextract', 'usr/local/lib/droiddeck-pipewire.tzst']] for arch in ['x86_64', 'i386']: paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libddsession.so']] diff --git a/tools/tests/test_desktop_powervr.py b/tools/tests/test_desktop_powervr.py new file mode 100644 index 0000000000..ad91719803 --- /dev/null +++ b/tools/tests/test_desktop_powervr.py @@ -0,0 +1,42 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +DESKTOP = (Path(__file__).resolve().parents[1] / 'linuxfs/desktop/droiddeck-desktop').read_text() +START = 'if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then' +LAUNCH = 'dbus-run-session -- startplasma-wayland' +STUBS = ''' +pipewire() { return 0; } +dbus-run-session() { sh -c 'echo "kopper:${LIBGL_KOPPER_DISABLE:-on}"'; } +''' + + +class DesktopPowerVrTest(unittest.TestCase): + def kopper_at_plasma_launch(self, gl_present): + segment = DESKTOP[DESKTOP.index(START):DESKTOP.index(LAUNCH) + len(LAUNCH)] + with tempfile.TemporaryDirectory() as run: + segment = (segment.replace(START, 'if true; then') + .replace('/usr/local/bin/droiddeck-pipewire', 'pipewire') + .replace('/run/droiddeck', run)) + environment = {key: value for key, value in os.environ.items() + if key not in ('DD_STEAM_GL_PRESENT', 'LIBGL_KOPPER_DISABLE')} + if gl_present is not None: + environment['DD_STEAM_GL_PRESENT'] = gl_present + result = subprocess.run(['bash', '-c', STUBS + segment], env=environment, + capture_output=True, text=True, timeout=5) + self.assertEqual(0, result.returncode, result.stderr) + return result.stdout.strip().splitlines()[-1] + + def test_system_powervr_plasma_starts_with_kopper_off(self): + self.assertEqual('kopper:true', self.kopper_at_plasma_launch('1')) + + def test_other_drivers_start_plasma_with_kopper(self): + self.assertEqual('kopper:on', self.kopper_at_plasma_launch(None)) + self.assertEqual('kopper:on', self.kopper_at_plasma_launch('0')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 993d668d95..628fcd57ef 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1090,6 +1090,61 @@ class ExtractTest(FexTestCase): self.assertNotIn("no unsquashfs", said) self.assertFalse(os.path.lexists("squashfs-root")) + def runtime_elf(self): + head = bytearray(elf(183)) + struct.pack_into("&2\nexit 1\n") + with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(self.tmp / "rootfs")}), \ + mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \ + mock.patch("shutil.which", return_value=None): + status, said = self.quiet(FEX["extract"], "image.AppImage") + self.assertEqual(status, 0) + self.assertIn("uruntime could not extract it (status 1)", said) + self.assertNotIn("dwarfsextract could not", said) + self.assertTrue(Path("squashfs-root/AppRun").is_file()) + self.assertFalse((self.home / ".config/droiddeck/fex-wanted").exists()) + + def test_a_dwarfs_image_the_runtime_unpacks_never_runs_dwarfsextract(self): + reader = self.dwarfs("touch squashfs-root/AppRun\n") + tool = self.uruntime("mkdir -p AppDir && touch AppDir/AppRun\n") + with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}): + status, said = self.quiet(FEX["extract"], "image.AppImage") + self.assertEqual((status, said), (0, "")) + self.assertFalse(self.ran.exists()) + + def test_a_dwarfsextract_failure_leaves_nothing_unpacked(self): + reader = self.dwarfs("mkdir -p squashfs-root/usr\nexit 3\n") + tool = self.uruntime("exit 1\n") + with mock.patch.dict(G, {"URUNTIME": tool, "DWARFSEXTRACT": reader}), \ + mock.patch("shutil.which", return_value=None): + status, said = self.quiet(FEX["extract"], "image.AppImage") + self.assertEqual(status, 1) + self.assertTrue(self.ran.exists()) + self.assertIn("dwarfsextract could not extract it (status 3)", said) + self.assertFalse(os.path.lexists("squashfs-root")) + + def test_a_squashfs_image_still_goes_to_unsquashfs(self): + reader = self.dwarfs("exit 0\n") + self.write(self.image, self.runtime_elf() + b"hsqs" + b"payload", 0o755) + tool = self.uruntime("exit 1\n") + with mock.patch.dict(G, {"DWARFSEXTRACT": reader}): + status, said, commands = self.seven_zip(tool, {"unsquashfs": "/usr/bin/unsquashfs", "7z": "/usr/bin/7z"}) + self.assertEqual(status, 0) + self.assertNotIn("dwarfsextract", said) + self.assertEqual(["/usr/bin/unsquashfs", "/usr/bin/7z"], [c[0] for c in commands]) + class LaunchTest(FexTestCase): def test_the_guest_environment(self): diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index d17fc737b7..453346281d 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -1,3 +1,4 @@ +import contextlib import hashlib import io import json @@ -1548,6 +1549,65 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(MODULE["engine_fixes"](game, [], "42"), ({}, [], [])) self.assertEqual(MODULE["engine_fixes"](game, []), ({}, [], [])) + def test_dragon_quest_monsters_4_writes_full_detail_mesh_settings(self): + apply = MODULE["dragon_quest_monsters_4_mesh_detail"] + wanted = "r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n" + for exe, project in (("DragonQuestMonsters4Demo.exe", "DragonQuestMonsters4Demo"), + ("DragonQuestMonsters4-Win64-Shipping.exe", "DragonQuestMonsters4")): + with self.subTest(exe=exe), tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "pfx").mkdir() + config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local" / project / "Saved/Config/Windows/Engine.ini" + with contextlib.redirect_stderr(io.StringIO()): + apply("/game/" + exe, {"STEAM_COMPAT_DATA_PATH": tmp}) + self.assertEqual(config.read_text(), "[SystemSettings]\n" + wanted) + + def test_dragon_quest_monsters_4_keeps_other_engine_settings(self): + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "pfx").mkdir() + config = Path(tmp) / "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini" + config.parent.mkdir(parents=True) + config.write_text("[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\nr.SkeletalMeshLODBias=0\n\n[Other]\nKey=1\n") + config.chmod(0o444) + with contextlib.redirect_stderr(io.StringIO()): + MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": tmp}) + self.assertEqual(config.read_text(), "[Core.Log]\nLogTemp=Log\n\n[SystemSettings]\nr.Fog=0\n" + "r.SkeletalMeshLODBias=-4\nr.SkeletalMeshLODRadiusScale=0.25\n\n[Other]\nKey=1\n") + self.assertEqual(config.stat().st_mode & 0o777, 0o444) + + def test_dragon_quest_monsters_4_settings_use_the_game_profile_prefix(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + exe = home / "game/DragonQuestMonsters4Demo.exe" + exe.parent.mkdir() + exe.touch() + proton = home / "fake-proton" + proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n") + proton.chmod(0o755) + inherited, chosen = home / "compatdata/42", home / "profile/42" + for data in (inherited, chosen): + (data / "pfx").mkdir(parents=True) + config = home / ".config/droiddeck/game-environment.json" + config.parent.mkdir(parents=True) + config.write_text(json.dumps({"version": 1, "games": {"42": {"STEAM_COMPAT_DATA_PATH": str(chosen)}}})) + subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "waitforexitandrun", str(exe)], + env=dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH=str(inherited)), + text=True, capture_output=True, check=True) + engine = "pfx/drive_c/users/steamuser/AppData/Local/DragonQuestMonsters4Demo/Saved/Config/Windows/Engine.ini" + self.assertIn("r.SkeletalMeshLODBias=-4", (chosen / engine).read_text()) + self.assertFalse((inherited / engine).exists()) + + def test_dragon_quest_monsters_4_prefix_errors_do_not_stop_the_launch(self): + errors = io.StringIO() + with mock.patch.object(Path, "is_dir", side_effect=PermissionError("denied")), contextlib.redirect_stderr(errors): + MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters4Demo.exe", {"STEAM_COMPAT_DATA_PATH": "/compatdata/42"}) + self.assertIn("left as is", errors.getvalue()) + + def test_other_games_do_not_get_the_dragon_quest_monsters_4_settings(self): + with tempfile.TemporaryDirectory() as tmp: + (Path(tmp) / "pfx").mkdir() + MODULE["dragon_quest_monsters_4_mesh_detail"]("/game/DragonQuestMonsters3.exe", {"STEAM_COMPAT_DATA_PATH": tmp}) + self.assertEqual(list((Path(tmp) / "pfx").iterdir()), []) + def test_arkham_city_gets_full_x87_precision_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32" diff --git a/tools/tests/test_gamescope_disabled_touch_mouse.py b/tools/tests/test_gamescope_disabled_touch_mouse.py new file mode 100644 index 0000000000..8dc144c9c5 --- /dev/null +++ b/tools/tests/test_gamescope_disabled_touch_mouse.py @@ -0,0 +1,76 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCH = ROOT / "tools/gamescope/patches/0141-nested-mouse-moves-when-touch-is-disabled.patch" + + +def patched_source(): + return "\n".join(line[1:] for line in PATCH.read_text().splitlines() + if line[:1] in (" ", "+") and not line.startswith("+++")) + + +def branch(text, start): + begin = text.index(start) + depth = 0 + for i in range(text.index("{", begin), len(text)): + depth += {"{": 1, "}": -1}.get(text[i], 0) + if depth == 0: + return text[begin:i + 1] + raise ValueError(start) + + +PREAMBLE = r''' +#include +#include +namespace gamescope { enum class TouchClickModes { Hover, Left, Right, Middle, Passthrough, Disabled, Trackpad }; } +static int warps, bumps, warp_from_touch = -1; +static double warp_x, warp_y; +static void wlserver_mousewarp( double x, double y, uint32_t, bool, bool bFromTouch = false ) { warps++; warp_x = x; warp_y = y; warp_from_touch = bFromTouch; } +static void bump_input_counter() { bumps++; } + +static void touchmotion( double tx, double ty, uint32_t time, bool bAlwaysWarpCursor ) +{ + gamescope::TouchClickModes eMode = gamescope::TouchClickModes::Disabled; + if ( eMode == gamescope::TouchClickModes::Passthrough ) + { + } +''' + +MAIN = r''' + bump_input_counter(); +} + +int main() { + touchmotion( 0.0, 0.0, 1, false ); + assert( warps == 0 && bumps == 0 ); + + touchmotion( 640.5, 360.25, 2, true ); + assert( warps == 1 && warp_x == 640.5 && warp_y == 360.25 ); + assert( warp_from_touch == 0 ); + assert( bumps == 1 ); + return 0; +} +''' + + +class GamescopeDisabledTouchMouseTest(unittest.TestCase): + def test_the_nested_mouse_moves_the_pointer_while_fingers_stay_ignored(self): + compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++") + if not compiler: + self.skipTest("no C++ compiler") + disabled = branch(patched_source(), "else if ( eMode == gamescope::TouchClickModes::Disabled )") + with tempfile.TemporaryDirectory() as tmp: + src = Path(tmp) / "disabled_touch_mouse.cpp" + exe = Path(tmp) / "disabled_touch_mouse" + src.write_text(PREAMBLE + "\t" + disabled + "\n" + MAIN) + subprocess.run([compiler, "-std=c++17", "-Wall", "-Werror", "-UNDEBUG", str(src), "-o", str(exe)], check=True) + subprocess.run([str(exe)], check=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_inputudev_preload.py b/tools/tests/test_inputudev_preload.py index 7cb96a91d5..68d55403fe 100644 --- a/tools/tests/test_inputudev_preload.py +++ b/tools/tests/test_inputudev_preload.py @@ -650,9 +650,11 @@ class InputUdevPreloadTest(unittest.TestCase): "nothing added scan -1", ]) - def test_only_the_steam_client_runtime_path_gets_the_real_libudev(self): - for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/steam-probe", 1), - ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), ("steamrt/steam", 1)): + def test_only_the_steam_client_and_its_remote_play_client_get_the_real_libudev(self): + for path, pad in (("steamrt64/steam", 0), ("steamrtarm64/steam", 0), ("steamrt64/streaming_client", 0), + ("steamrtarm64/streaming_client", 0), ("steamrt64/steam-probe", 1), + ("steamrt64/streaming_client2", 1), ("xsteamrt64/steam", 1), ("steamrt64/xsteam", 1), + ("steamrt/steam", 1), ("steamrt/streaming_client", 1)): with self.subTest(path=path): client = self.dir / "clients" / path client.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/tests/test_native_hook_cmdline.py b/tools/tests/test_native_hook_cmdline.py new file mode 100644 index 0000000000..81ff864e7c --- /dev/null +++ b/tools/tests/test_native_hook_cmdline.py @@ -0,0 +1,179 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +HOOK_BUILD = REPO / "tools/nativeguest/build.sh" +DDEXEC = REPO / "app/src/main/cpp/ddexec/ddexec.c" +DDEXEC_FLAGS = ["-shared", "-fPIC", "-O2", "-ffreestanding", "-fno-builtin", "-fno-stack-protector", + "-fno-asynchronous-unwind-tables", "-nostdlib", "-Wl,-e,_start", "-Wl,-z,noexecstack", + "-Wl,--no-undefined", "-Wl,-Bsymbolic"] + +WINDOWS_PROGRAM = "C:\\Program Files (x86)\\Battle.net\\Battle.net.exe" + +PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static void show_cmdline(const char *label) { + static char buf[1 << 20]; + int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY); + ssize_t len = 0, n; + while (fd >= 0 && (n = read(fd, buf + len, sizeof(buf) - len)) > 0) len += n; + if (fd >= 0) close(fd); + while (len > 0 && buf[len - 1] == '\0') len--; + printf("%s", label); + for (ssize_t at = 0; at < len; at += (ssize_t)strlen(buf + at) + 1) printf("\t%s", buf + at); + printf("\n"); +} + +int main(int argc, char **argv) { + int contiguous = 1; + for (int i = 1; i < argc; i++) { + if (argv[i] != argv[i - 1] + strlen(argv[i - 1]) + 1) contiguous = 0; + } + printf("execfn\t%s\n", (const char *)getauxval(AT_EXECFN)); + printf("contiguous\t%d\n", contiguous); + printf("argv"); + for (int i = 0; i < argc; i++) printf("\t%s", argv[i]); + printf("\n"); + printf("name\t%s\t%s\n", program_invocation_name, program_invocation_short_name); + show_cmdline("cmdline"); + if (argc > 1 && contiguous) { + size_t offset = (size_t)(argv[1] - argv[0]); + char *end = argv[argc - 1] + strlen(argv[argc - 1]) + 1; + memmove(argv[0], argv[1], (size_t)(end - argv[1])); + memset(end - offset, 0, offset); + show_cmdline("shifted"); + } + return 0; +} +""" + + +class NativeHookCmdlineTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.ddexec = tmp / "lib/libddexec.so" + cls.ddexec.parent.mkdir() + subprocess.run([cls.cc, *DDEXEC_FLAGS, "-o", str(cls.ddexec), str(DDEXEC)], check=True) + cls.ddexec_runs = subprocess.run(list(cls.prefix) + [str(cls.ddexec), str(cls.probe), str(cls.probe)], + capture_output=True, timeout=120).returncode == 0 + cls.root = tmp / "root" + cls.root.mkdir() + if cls.prefix: + libs = Path(cls.prefix[cls.prefix.index("-L") + 1]) / "lib" + else: + libs = next(Path(p) for p in ("/lib/aarch64-linux-gnu", "/usr/lib/aarch64-linux-gnu", "/lib64") + if (Path(p) / "libc.so.6").exists()) + cls.ld_so = next(str(p) for p in (libs / "ld-linux-aarch64.so.1", Path("/lib/ld-linux-aarch64.so.1")) + if p.exists()) + cls.libs = str(libs) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_probe(self, argv, root=True, preload=False): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")} + if root: + env["DDNATV_ROOT"] = str(self.root) + runner_args = list(self.prefix) + if preload and self.prefix: + runner_args += ["-E", f"LD_PRELOAD={self.hook}"] + elif preload: + env["LD_PRELOAD"] = str(self.hook) + out = subprocess.run(runner_args + argv, env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()} + + def loader_argv(self, *args, name="/usr/bin/wine"): + named = ["--argv0", name] if name else [] + return [self.ld_so, "--preload", str(self.hook), "--library-path", self.libs, *named, str(self.probe), *args] + + def test_a_program_its_loader_starts_has_its_arguments_together(self): + seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray")) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["argv"]) + self.assertEqual(["1"], seen["contiguous"]) + self.assertEqual(["/usr/bin/wine", "wine"], seen["name"]) + + @unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments") + def test_the_command_line_shows_the_arguments_the_program_was_started_with(self): + seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray")) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"]) + self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"]) + + @unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments") + def test_the_app_loader_in_front_of_the_loader_is_left_out(self): + if not self.ddexec_runs: + self.skipTest("libddexec.so does not start a program on this host") + seen = self.run_probe([str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM)) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"]) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["cmdline"]) + self.assertEqual([WINDOWS_PROGRAM], seen["shifted"]) + + @unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments") + def test_a_program_its_loader_starts_still_finds_its_own_path(self): + unchanged = self.run_probe(self.loader_argv(WINDOWS_PROGRAM), root=False) + self.assertEqual([str(self.probe)], unchanged["execfn"]) + seen = self.run_probe(self.loader_argv(WINDOWS_PROGRAM, "--in-tray")) + self.assertEqual([WINDOWS_PROGRAM, "--in-tray"], seen["shifted"]) + self.assertEqual(unchanged["execfn"], seen["execfn"]) + + @unittest.skipIf(runner()[1], "qemu answers AT_EXECFN from its own copy of the arguments") + def test_a_program_the_app_loader_starts_still_finds_its_own_path(self): + if not self.ddexec_runs: + self.skipTest("libddexec.so does not start a program on this host") + argv = [str(self.ddexec), self.ld_so] + self.loader_argv(WINDOWS_PROGRAM) + unchanged = self.run_probe(argv, root=False) + seen = self.run_probe(argv) + self.assertEqual([WINDOWS_PROGRAM], seen["shifted"]) + self.assertEqual(unchanged["execfn"], seen["execfn"]) + self.assertNotEqual([""], seen["execfn"]) + + def test_a_loader_run_without_a_program_name_keeps_its_command_line(self): + argv = self.loader_argv(WINDOWS_PROGRAM, name=None) + seen = self.run_probe(argv) + self.assertEqual([str(self.probe), WINDOWS_PROGRAM], seen["argv"]) + self.assertEqual(["1"], seen["contiguous"]) + if not self.prefix: + self.assertEqual(argv, seen["cmdline"]) + + def test_outside_the_native_userland_the_command_line_is_unchanged(self): + argv = self.loader_argv(WINDOWS_PROGRAM) + seen = self.run_probe(argv, root=False) + self.assertEqual(["/usr/bin/wine", WINDOWS_PROGRAM], seen["argv"]) + self.assertEqual(["0"], seen["contiguous"]) + if not self.prefix: + self.assertEqual(argv, seen["cmdline"]) + + def test_a_program_started_directly_is_unchanged(self): + seen = self.run_probe([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], preload=True) + self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["argv"]) + self.assertEqual(["1"], seen["contiguous"]) + if not self.prefix: + self.assertEqual([str(self.probe), WINDOWS_PROGRAM, "--in-tray"], seen["cmdline"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_proc_exe.py b/tools/tests/test_native_hook_proc_exe.py index 59b60d9af4..479c78109d 100644 --- a/tools/tests/test_native_hook_proc_exe.py +++ b/tools/tests/test_native_hook_proc_exe.py @@ -74,8 +74,8 @@ class NativeHookProcExeTest(unittest.TestCase): shutil.copy(shutil.which(cls.prefix[0]), cls.loader) cls.loader_args = list(cls.prefix[1:]) else: - ld = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p)) - shutil.copy(ld, cls.loader) + cls.ld_so = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p)) + shutil.copy(cls.ld_so, cls.loader) cls.loader_args = [] @classmethod @@ -83,11 +83,13 @@ class NativeHookProcExeTest(unittest.TestCase): cls.tmp.cleanup() def start(self, loader, real_exe=None, program=None): - env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_REAL_EXE")} - if real_exe: - env["DDNATV_REAL_EXE"] = real_exe program = program or Path(self.tmp.name) / "sleeper" cmd = ([str(self.loader), *self.loader_args] if loader else list(self.prefix)) + [str(program)] + return self.spawn(cmd, {"DDNATV_REAL_EXE": real_exe} if real_exe else {}) + + def spawn(self, cmd, extra_env): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT", "DDNATV_REAL_EXE")} + env.update(extra_env) child = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True) self.addCleanup(child.stdout.close) self.addCleanup(child.wait) @@ -141,6 +143,14 @@ class NativeHookProcExeTest(unittest.TestCase): link = f"/proc/{pid}/exe" self.assertEqual(os.readlink(link), self.readlink(link)[link]) + @unittest.skipIf(runner()[1], "qemu answers /proc/self/cmdline from its own copy of the arguments") + def test_a_program_whose_hook_moved_its_arguments_is_still_named(self): + cmd = [self.ld_so, "--preload", str(self.hook), "--argv0", self.kwin.name, str(self.kwin)] + pid = self.spawn(cmd, {"DDNATV_ROOT": str(self.root), "DDNATV_REAL_EXE": str(self.kwin)}) + self.assertEqual(b"kwin_wayland", Path(f"/proc/{pid}/cmdline").read_bytes().rstrip(b"\0")) + link = f"/proc/{pid}/exe" + self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link]) + def test_a_loader_without_a_known_program_keeps_the_kernel_link(self): pid = self.start(loader=True) link = f"/proc/{pid}/exe" diff --git a/tools/tests/test_preload_wrapper_stack.py b/tools/tests/test_preload_wrapper_stack.py new file mode 100644 index 0000000000..409799921e --- /dev/null +++ b/tools/tests/test_preload_wrapper_stack.py @@ -0,0 +1,39 @@ +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" +LIMIT = 1024 +WRAPPERS = { + "descriptor.c": ("dd_descriptor_unlink", "dd_descriptor_rmdir", "dd_descriptor_remove", "dd_descriptor_rename"), + "tracer.c": ("dd_status_without_tracer",), +} + + +def frames(source, build): + obj = build / (source + ".o") + subprocess.run(["cc", "-c", "-fPIC", "-O2", "-Wall", "-fstack-usage", "-o", str(obj), str(PRELOAD / source)], + check=True) + sizes = {} + for line in obj.with_suffix(".su").read_text().splitlines(): + place, size, _ = line.split("\t") + sizes[place.rsplit(":", 1)[-1]] = int(size) + return sizes + + +@unittest.skipUnless(shutil.which("cc"), "needs a C compiler") +class PreloadWrapperStackTest(unittest.TestCase): + def test_wrappers_keep_path_buffers_off_their_frames(self): + with tempfile.TemporaryDirectory() as build: + for source, names in WRAPPERS.items(): + sizes = frames(source, Path(build)) + for name in names: + with self.subTest(function=name): + self.assertIn(name, sizes) + self.assertLess(sizes[name], LIMIT) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index 08ffc90935..6218bf3be0 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -261,6 +261,27 @@ class ImportsTest(unittest.TestCase): imports.watch(str(self.steam), str(listing)) identify.assert_not_called() + def test_another_program_of_a_steam_install_stays_a_shortcut_beside_the_steam_app(self): + game, library = self.steam_install() + other = dict(game, name='Mod Launcher', exe=str(Path(game['folder']) / 'ModLauncher.exe'), + appid=0x87654322, route=False) + Path(other['exe']).write_bytes(b'mod') + imports.save_json(self.acct / 'config' / imports.STATE, + dict(account='123', owned={'42': True}, candidates={game['folder']: 42}, + sources={game['folder']: imports.source_stamp(game)})) + games, routes = imports.route(self.steam, self.acct, [game, other]) + self.assertEqual([other], games) + self.assertEqual({str(game['appid']): 42}, routes) + link = self.steam / 'steamapps/compatdata' / str(other['appid'] & 0xFFFFFFFF) + self.assertEqual(library / 'steamapps/compatdata/42', link.resolve()) + + def test_watch_never_looks_up_programs_that_are_not_the_steam_apps_own(self): + listing = self.root / 'games.json' + listing.write_text(json.dumps([dict(self.game, route=False)])) + with patch.object(imports, 'identify') as identify: + imports.watch(str(self.steam), str(listing)) + identify.assert_not_called() + def test_native_programs_stay_shortcuts_and_are_never_looked_up(self): self.snapshot() game = dict(self.game, native=True) @@ -692,6 +713,21 @@ class ImportsTest(unittest.TestCase): self.assert_not_imported_as(480) self.assertEqual(b'game', self.exe.read_bytes()) + def test_spacewar_import_is_released_for_a_program_that_is_not_the_steam_apps_own(self): + self.import_as(480) + other = dict(self.game, appid=0x87654322, route=False) + with patch('builtins.print'): + self.assertEqual(([other], {}), imports.route(self.steam, self.acct, [other])) + self.assert_not_imported_as(480) + self.assertEqual(b'game', self.exe.read_bytes()) + + def test_a_steam_import_stays_when_another_program_of_the_install_is_listed(self): + self.snapshot() + imports.route(self.steam, self.acct, [self.game]) + other = dict(self.game, appid=0x87654322, route=False) + imports.route(self.steam, self.acct, [other]) + self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file()) + def test_import_follows_the_app_the_files_name_now(self): self.snapshot() imports.route(self.steam, self.acct, [self.game]) diff --git a/tools/tests/test_stretch_game_screen.py b/tools/tests/test_stretch_game_screen.py new file mode 100644 index 0000000000..0c2a2eef37 --- /dev/null +++ b/tools/tests/test_stretch_game_screen.py @@ -0,0 +1,56 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' +OUTPUT = '2184x1968' +GAME = '3498x1968' + + +class StretchGameScreenTest(unittest.TestCase): + def call(self, value): + source = SESSION.read_text() + start = source.index('dd_stretch_game_screen() {') + end = source.index('\n}\n', start) + 3 + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / 'xprop.log' + fake = Path(directory) / 'xprop' + fake.write_text('#!/bin/bash\nprintf "%s\\n" "$*" >> "$XPROP_LOG"\n') + fake.chmod(0o755) + env = dict(os.environ, XPROP_LOG=str(log), PATH=directory + os.pathsep + os.environ['PATH']) + script = source[start:end] + f'dd_stretch_game_screen "{value}" {OUTPUT} {GAME}\n' + result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=5) + written = log.read_text().splitlines() if log.exists() else [] + return result.returncode, written + + def test_the_game_screen_the_client_sizes_to_the_output_is_given_the_stretched_size(self): + status, written = self.call('1, 2184, 1968, 0') + self.assertEqual(0, status) + self.assertEqual(['-root -f GAMESCOPE_XWAYLAND_MODE_CONTROL 32c -set GAMESCOPE_XWAYLAND_MODE_CONTROL 1, 3498, 1968, 1'], written) + + def test_a_game_resolution_chosen_in_steam_is_kept(self): + status, written = self.call('1, 1280, 720, 0') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + def test_the_clients_own_screen_is_left_alone(self): + status, written = self.call('0, 2184, 1968, 0') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + def test_the_stretched_size_is_not_rewritten_again(self): + status, written = self.call('1, 3498, 1968, 1') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + def test_a_missing_property_is_ignored(self): + status, written = self.call('') + self.assertNotEqual(0, status) + self.assertEqual([], written) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_unwrap_dwarfs.py b/tools/tests/test_unwrap_dwarfs.py new file mode 100644 index 0000000000..0c2676eaa9 --- /dev/null +++ b/tools/tests/test_unwrap_dwarfs.py @@ -0,0 +1,45 @@ +import struct +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/unwrap-dwarfs.sh" + + +class UnwrapDwarfsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.output = self.dir / "dwarfsextract" + + def wrapper(self, payload, magic=b"SQUEEZE!", packed=None): + compressed = subprocess.run(["zstd", "-q", "-c"], input=payload, capture_output=True, check=True).stdout + size = len(compressed) if packed is None else packed + path = self.dir / "wrapper" + path.write_bytes(b"\x7fELF stub" * 100 + compressed + magic + struct.pack(" +#include +#include + +#define VKP_VENDOR_QUALCOMM 0x5143 +static int dev_state; +static uint32_t g_vendor_id; +static char *g_library_name; +static int g_ahb_import; +static struct { void *GetAndroidHardwareBufferPropertiesANDROID; } g_vk; +static int dev_init(void) { return dev_state; } +static int properties_stub; + +%(can_import)s + +static int can(uint32_t vendor, char *library, int ext) { + dev_state = 0; + g_vendor_id = vendor; + g_library_name = library; + g_ahb_import = ext; + g_vk.GetAndroidHardwareBufferPropertiesANDROID = ext ? &properties_stub : NULL; + return vkp_can_import_ahb(); +} + +int main(void) { + char radv[] = "libvulkan_radeon.so"; + char panvk[] = "libvulkan_panfrost.so"; + const uint32_t samsung = 0x144d, arm = 0x13b5, imagination = 0x1010; + + assert(can(samsung, NULL, 1)); + assert(can(arm, NULL, 1)); + assert(can(imagination, NULL, 1)); + + assert(!can(samsung, radv, 1)); + assert(!can(arm, panvk, 1)); + + assert(!can(VKP_VENDOR_QUALCOMM, NULL, 1)); + assert(!can(samsung, NULL, 0)); + + dev_state = -1; + g_vendor_id = samsung; g_library_name = NULL; g_ahb_import = 1; + g_vk.GetAndroidHardwareBufferPropertiesANDROID = &properties_stub; + assert(!vkp_can_import_ahb()); + return 0; +} +''' + + +POOL_HARNESS = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#define FOURCC(a, b, c, d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24)) +#define DRM_ABGR8888 FOURCC('A', 'B', '2', '4') +#define DRM_ABGR2101010 FOURCC('A', 'B', '3', '0') +#define AHB_RGBA8 1u +#define AHB_RGB10A2 0x2bu +#define MOD_LINEAR 0ULL +#define MOD_QCOM_COMPRESSED 0x0500000000000001ULL +#define SC_MOD_GRALLOC (~0ULL - 1) +#define SC_LAYER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) +#define AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT (1ULL << 9) +#define AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE (1ULL << 8) +#define AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY (1ULL << 11) +#define AHARDWAREBUFFER_USAGE_CPU_READ_RARELY 2ULL + +typedef struct AHardwareBuffer AHardwareBuffer; +typedef struct { + uint32_t width, height, layers, format; + uint64_t usage; + uint32_t stride, rfu0; + uint64_t rfu1; +} AHardwareBuffer_Desc; +struct droiddeck_native_handle { int version; int numFds; int numInts; int data[4]; }; +struct vkp_image { int unused; }; +struct slot { AHardwareBuffer *ahb; struct vkp_image *img; int w, h; uint32_t fmt; int release_fd; int busy; }; +struct layer { + const char *name; + int pool_n; + int alloc_tier; + unsigned import_failed_fmts; + uint64_t pool_modifier; + int logged_w, logged_h, logged_tier; + uint32_t logged_fmt; + uint64_t logged_mod; +}; + +enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR }; +static int g_alloc_failed; +static uint32_t g_hdr_pool_fmt = AHB_RGB10A2; + +static struct droiddeck_native_handle handle = {.numFds = 1, .data = {3}}; +static AHardwareBuffer *buffer = (AHardwareBuffer *)&handle; +static struct vkp_image image; +static int allocations, imports_10_bit, imports_8_bit, accept_10_bit, accept_8_bit; + +static int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *d, AHardwareBuffer **out) { + (void)d; allocations++; *out = buffer; return 0; +} +static void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) { + (void)b; d->stride = 1920; d->usage = 0; +} +static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; } +static const void *native_handle(const AHardwareBuffer *b) { (void)b; return &handle; } +static struct { const void *(*getNativeHandle)(const AHardwareBuffer *); } api = {native_handle}; +static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) { (void)h; (void)mod; return 0; } +static int vkp_can_import_ahb(void) { return 0; } +static struct vkp_image *vkp_image_import_ahb(AHardwareBuffer *b, char *info, size_t n) { + (void)b; (void)info; (void)n; return NULL; +} +static struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm, uint64_t mod, int w, int h, uint32_t pitch, + uint32_t offset, int planes) { + (void)fd; (void)mod; (void)w; (void)h; (void)pitch; (void)offset; (void)planes; + if (drm == DRM_ABGR2101010) { imports_10_bit++; return accept_10_bit ? &image : NULL; } + imports_8_bit++; + return accept_8_bit ? &image : NULL; +} +static int handle_fd(const struct droiddeck_native_handle *h, off_t need, int *which) { + (void)need; *which = 0; return h->data[0]; +} +static void describe_handle(const struct droiddeck_native_handle *h, char *out, size_t n) { (void)h; snprintf(out, n, "-"); } +static const char *pool_kind(uint64_t mod) { return mod == SC_MOD_GRALLOC ? "gralloc-laid-out" : "linear"; } +static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; } + +%(tier_name)s +%(alloc_slot)s + +static int take_free_slot(struct layer *l, int w, int h, uint32_t fmt, int *wait_fd) { + struct slot s = {0}; + *wait_fd = -1; + g_alloc_failed = 0; + return alloc_slot(l, &s, w, h, fmt) == 0 ? 0 : -1; +} + +%(take_hdr_slot)s + +static int frame(struct layer *l) { + int fd; + return take_hdr_slot(l, 1920, 1080, &fd); +} + +static void reset(int ten, int eight) { + g_hdr_pool_fmt = AHB_RGB10A2; + allocations = imports_10_bit = imports_8_bit = 0; + accept_10_bit = ten; + accept_8_bit = eight; +} + +int main(void) { + struct layer ten_bit_refused = {.name = "game", .pool_n = 3}; + reset(0, 1); + assert(frame(&ten_bit_refused) == 0); + assert(g_hdr_pool_fmt == AHB_RGBA8); + assert(imports_10_bit == 1 && imports_8_bit == 1); + assert(ten_bit_refused.alloc_tier == TIER_LINEAR); + assert(frame(&ten_bit_refused) == 0); + assert(imports_10_bit == 1 && imports_8_bit == 2); + + struct layer ten_bit_works = {.name = "game", .pool_n = 3}; + reset(1, 1); + assert(frame(&ten_bit_works) == 0); + assert(g_hdr_pool_fmt == AHB_RGB10A2); + assert(imports_10_bit == 1 && imports_8_bit == 0); + + struct layer nothing_imports = {.name = "game", .pool_n = 3}; + reset(0, 0); + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(imports_10_bit == 1 && imports_8_bit == 1); + const int tried = allocations; + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(frame(¬hing_imports) == -1 && g_alloc_failed); + assert(allocations == tried); + assert(imports_10_bit == 1 && imports_8_bit == 1); + return 0; +} +''' + +class LayerAhbImportTest(unittest.TestCase): + def test_only_the_system_driver_imports_gralloc_layouts(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the layer AHardwareBuffer import test") + body = function((SRC / "vk_present.c").read_text(), "vkp_can_import_ahb") + with tempfile.TemporaryDirectory(prefix="droiddeck-layer-ahb-") as tmp: + source = Path(tmp) / "layer_ahb_import_test.c" + source.write_text(HARNESS % {"can_import": body}) + program = Path(tmp) / "layer-ahb-import" + built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-UNDEBUG", str(source), + "-o", str(program)], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + + def test_a_failed_10_bit_pool_still_falls_back_to_8_bit_and_failures_are_latched_per_format(self): + compiler = shutil.which(os.environ.get("CC", "cc")) + if not compiler: + self.fail("A C compiler is required for the layer pool fallback test") + text = (SRC / "sc_layer.c").read_text() + functions = {name: function(text, name) for name in ("tier_name", "alloc_slot", "take_hdr_slot")} + with tempfile.TemporaryDirectory(prefix="droiddeck-layer-pool-") as tmp: + source = Path(tmp) / "layer_pool_fallback_test.c" + source.write_text(POOL_HARNESS % functions) + program = Path(tmp) / "layer-pool-fallback" + built = subprocess.run([compiler, "-std=c11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", + "-UNDEBUG", str(source), "-o", str(program)], capture_output=True, text=True) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + ran = subprocess.run([str(program)], capture_output=True, text=True, timeout=30) + self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) + +if __name__ == "__main__": + unittest.main()