From f75cb387eb5f80cf1f7564684aca0a55137dee5e Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:21:26 -0500 Subject: [PATCH 1/8] Render the Steam home tab at 60 FPS (#3647) Raise the shared Steam home idle animation cadence from 30 to 60 FPS without changing mixed-refresh displays or in-game frame limits. --- .../com/droiddeck/launcher/ui/SteamHome.kt | 16 ++++++-- .../droiddeck/launcher/ui/IdleFramesTest.kt | 38 ++++++++++++++----- 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index 6ea5b16cab..95a4ece552 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -82,17 +82,25 @@ import kotlinx.coroutines.withContext private const val WALL_MIN_GAMES = 4 private const val WALL_DISTINCT = 40 -private const val IDLE_FRAME_NS = 30_000_000L +internal val IdleFrames = IdleFrameGate() -internal object IdleFrames { - private var shown = 0L +internal class IdleFrameGate { + private var next = Long.MIN_VALUE + private var shown = Long.MIN_VALUE fun due(nanos: Long): Boolean { if (nanos == shown) return true - if (nanos - shown < IDLE_FRAME_NS) return false + // Allow sub-ms vsync jitter; carry the phase on panels whose refresh isn't a multiple of 60. + if (nanos + VSYNC_TOLERANCE_NS < next) return false + next = if (next == Long.MIN_VALUE || nanos - next >= FRAME_NS) nanos + FRAME_NS else next + FRAME_NS shown = nanos return true } + + private companion object { + const val FRAME_NS = 1_000_000_000L / 60 + const val VSYNC_TOLERANCE_NS = 500_000L + } } @Composable diff --git a/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt index 860fcc9665..27f1e553c5 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/IdleFramesTest.kt @@ -1,19 +1,37 @@ package com.droiddeck.launcher.ui import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class IdleFramesTest { - @Test - fun idleLoopsDrawThirtyFramesASecondAndShareEachOne() { - val start = 5_000_000_000L - val frame = 8_333_333L - val drawn = (0 until 120).count { IdleFrames.due(start + it * frame) } - assertEquals(30, drawn) + private val start = 5_000_000_000L - val later = start + 1_000_000_000L - assertEquals(listOf(true, true, true), List(3) { IdleFrames.due(later) }) - assertEquals(listOf(false, false), List(2) { IdleFrames.due(later + frame) }) - assertEquals(listOf(true, true), List(2) { IdleFrames.due(later + 4 * frame) }) + @Test + fun idleLoopsDrawAtSixtyOrThePanelRateIfLower() { + for (hz in listOf(30, 60, 90, 120, 144)) { + val gate = IdleFrameGate() + val drawn = (0 until 10 * hz).count { gate.due(start + it * 1_000_000_000L / hz) } + assertEquals("panel at $hz Hz", 10 * minOf(hz, 60), drawn) + } + } + + @Test + fun idleLoopsShareTheDecisionForEachVsync() { + val gate = IdleFrameGate() + assertEquals(List(3) { true }, List(3) { gate.due(start) }) + assertEquals(List(2) { false }, List(2) { gate.due(start + 8_333_333) }) + assertEquals(List(2) { true }, List(2) { gate.due(start + 16_666_666) }) + } + + @Test + fun aLongPauseDoesNotCauseCatchUpDraws() { + val gate = IdleFrameGate() + assertTrue(gate.due(start)) + val resumed = start + 1_000_000_000L + assertTrue(gate.due(resumed)) + assertFalse(gate.due(resumed + 8_333_333)) + assertTrue(gate.due(resumed + 16_666_666)) } } From 811e28583413b2e17eefc99c1d0909bdf25f7ceb Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:45:14 -0500 Subject: [PATCH 2/8] Remove manual Lossless Scaling DLL import (#3654) Remove the picker and import paths. Ignore manually imported caches; keep LSFG from Steam installations. --- README.md | 2 +- .../droiddeck/launcher/ui/PreviewSupport.kt | 4 +- .../droiddeck/launcher/FrontEndActivity.kt | 17 ----- .../com/droiddeck/launcher/SessionActivity.kt | 20 ----- .../com/droiddeck/launcher/gpu/FrameGen.kt | 2 +- .../com/droiddeck/launcher/gpu/Lossless.kt | 73 +++++++------------ .../stores/xbox/XboxCloudSettingsPanel.kt | 2 +- .../stores/xbox/XboxNativePlayerActivity.kt | 4 +- .../com/droiddeck/launcher/ui/DevPreview.kt | 1 - .../com/droiddeck/launcher/ui/FrameGenMenu.kt | 41 +---------- .../droiddeck/launcher/ui/FrontEndScreen.kt | 1 - .../droiddeck/launcher/ui/FrontEndSetup.kt | 3 +- .../droiddeck/launcher/ui/SessionOverlay.kt | 3 +- .../com/droiddeck/launcher/ui/SheetRows.kt | 4 - app/src/main/res/values-ar/strings.xml | 11 --- app/src/main/res/values-b+es+419/strings.xml | 11 --- app/src/main/res/values-bg/strings.xml | 11 --- app/src/main/res/values-cs/strings.xml | 11 --- app/src/main/res/values-da/strings.xml | 11 --- app/src/main/res/values-de/strings.xml | 11 --- app/src/main/res/values-el/strings.xml | 11 --- app/src/main/res/values-es/strings.xml | 11 --- app/src/main/res/values-fi/strings.xml | 11 --- app/src/main/res/values-fr/strings.xml | 11 --- app/src/main/res/values-hi/strings.xml | 11 --- app/src/main/res/values-hu/strings.xml | 11 --- app/src/main/res/values-in/strings.xml | 11 --- app/src/main/res/values-it/strings.xml | 11 --- app/src/main/res/values-ja/strings.xml | 11 --- app/src/main/res/values-ko/strings.xml | 11 --- app/src/main/res/values-ms/strings.xml | 11 --- app/src/main/res/values-nb/strings.xml | 11 --- app/src/main/res/values-nl/strings.xml | 11 --- app/src/main/res/values-pl/strings.xml | 11 --- app/src/main/res/values-pt-rPT/strings.xml | 11 --- app/src/main/res/values-pt/strings.xml | 11 --- app/src/main/res/values-ro/strings.xml | 11 --- app/src/main/res/values-ru/strings.xml | 11 --- app/src/main/res/values-sv/strings.xml | 11 --- app/src/main/res/values-th/strings.xml | 11 --- app/src/main/res/values-tr/strings.xml | 11 --- app/src/main/res/values-uk/strings.xml | 11 --- app/src/main/res/values-vi/strings.xml | 11 --- app/src/main/res/values-zh-rCN/strings.xml | 11 --- app/src/main/res/values-zh-rHK/strings.xml | 11 --- app/src/main/res/values-zh-rTW/strings.xml | 11 --- app/src/main/res/values/strings.xml | 11 --- .../droiddeck/launcher/gpu/LosslessTest.kt | 38 +++++++++- .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 2 +- .../launcher/ui/DesktopUninstallTest.kt | 2 +- .../droiddeck/launcher/ui/FlathubFocusTest.kt | 2 +- .../launcher/ui/GamesClientTagTest.kt | 2 +- .../launcher/ui/GlobalGlassesSettingsTest.kt | 2 +- .../launcher/ui/InputUiLayoutTest.kt | 2 +- .../ui/LaunchSettingsComponentsTest.kt | 2 +- .../launcher/ui/LibraryVisibilityTest.kt | 2 +- .../com/droiddeck/launcher/ui/NavTabsTest.kt | 2 +- .../launcher/ui/NavigationSelectionTest.kt | 2 +- .../launcher/ui/PenSettingsGroupTest.kt | 2 +- .../launcher/ui/PortraitLayoutTest.kt | 2 +- .../launcher/ui/SessionSecondScreenTest.kt | 2 +- .../launcher/ui/SteamHomeHeadsetTest.kt | 2 +- .../launcher/ui/StoreRestorationTest.kt | 2 +- 63 files changed, 88 insertions(+), 520 deletions(-) diff --git a/README.md b/README.md index 576cf61c59..4a15571419 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Steam audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink`. - The DroidDeck HUD is [@The412Banner](https://github.com/The412Banner)'s [FusionHUD](https://github.com/The412Banner/FusionHUD) (GPL-3.0 with an attribution term). Its readings match Valve's [MangoHud](https://github.com/flightlessmango/MangoHud) build (MIT), with frame times from gamescope patch 0125. - The HUD's CPU, GPU load, thermal and battery readers come from [@xXJSONDeruloXx](https://github.com/xXJSONDeruloXx)'s work. -- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. +- LSFG frame generation comes from Camille LaVey and the [Eden](https://eden-emu.dev) project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported by [@maxjivi05](https://github.com/maxjivi05). It requires [Lossless Scaling](https://store.steampowered.com/app/993090/) installed through Steam and ships none of its shaders. - Black frame insertion follows the design of [@artzox](https://github.com/artzox)'s [BFI Presenter](https://github.com/artzox/BFI-Presenter) (GPL-3.0): the strobe runs on the display's refresh clock and the game is paced to the lit refresh. Both build on [Blur Busters](https://blurbusters.com)' research on MPRT and motion blur. No BFI Presenter code is used. - Remote Play decodes through Android's MediaCodec or the [FFmpeg](https://ffmpeg.org) (LGPL-2.1-or-later) in Steam's runtime. Qualcomm low latency settings follow [Moonlight](https://github.com/moonlight-stream/moonlight-android) (GPL-3.0). - [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) sockets use the settings in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions. diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt index 96a958e719..8a7da4c5d0 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/PreviewSupport.kt @@ -59,7 +59,7 @@ internal fun sampleState( internal val sampleActions: FrontEndActions = FrontEndActions( onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, - onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, + onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, ) @@ -82,7 +82,7 @@ internal fun sampleDrawerActions( secondScreenDisplays = listOfNotNull(secondScreen?.let { SecondScreenDisplay(2, "Built-in · 1240×1080") }), selectedSecondScreenDisplay = if (secondScreen != null) 2 else -1, onSecondScreenDisplay = {}, gameSwapAvailable = secondScreen != null, dashboardAvailable = secondScreen != null, - onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, + onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {}, ) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 9192d4371f..c4057101c7 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -304,9 +304,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet protons.installExperimental { progress -> com.droiddeck.launcher.session.ExperimentalProtons.installFromFile(this, zip, progress) } } } - private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> - if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } - } private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then) @@ -517,17 +514,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet bootMovieCustomName = com.droiddeck.launcher.session.BootMovie.customName(this) } - private fun importLossless(dll: File) { - Thread({ - val message = Lossless.message(this, Lossless.import(this, dll)) - val state = Lossless.state(this) - ui.post { - lossless = state - android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show() - } - }, "lossless-import").start() - } - private fun importSaves(name: String, game: () -> GameSaves.Game) { if (SessionState.running) { android.widget.Toast.makeText(this, R.string.main_saves_close_session, android.widget.Toast.LENGTH_LONG).show() @@ -1658,9 +1644,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet FrameGen.set(this, mode) frameGenLabel = FrameGen.label(this) }, - onImportLossless = { - pickLossless.launch(InAppFilePicker.buildIntent(this, listOf("dll"), getString(R.string.lsfg_pick_title))) - }, onProtons = { openProtons() }, onComponents = { focusContent -> openComponents(focusContent) }, onGameComponents = { game -> openComponents(gameKey = game.profileKey) }, diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 2c8f179349..eeb48aacb3 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -717,9 +717,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerTextureAnisotropy by mutableStateOf(null) private var drawerTextureLodBias by mutableStateOf(null) private var lossless by mutableStateOf(Lossless.State.NONE) - private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> - if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } - } private var frameGen by mutableStateOf(FrameGen.Mode.OFF) private var frameGenActiveGameId by mutableStateOf(null) private var frameGenActiveGameName by mutableStateOf(null) @@ -1902,10 +1899,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde readPrefs() applyFrameGen(force = true) }, - onImportLossless = { - pickLossless.launch(InAppFilePicker.buildIntent( - this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title))) - }, onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() }, onHardwareKeyboard = ::togglePcKeyboard, wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram), @@ -3587,19 +3580,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, "lossless-sync").start() } - private fun importLossless(dll: File) { - Thread({ - val result = Lossless.import(this, dll) - val message = Lossless.message(this, result) - val state = Lossless.state(this) - runOnUiThread { - lossless = state - Toast.makeText(this, message, Toast.LENGTH_LONG).show() - applyFrameGen(force = result == Lossless.ImportResult.UPDATED) - } - }, "lossless-import").start() - } - private fun watchSession() { val handler = Handler(Looper.getMainLooper()) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt index 25124a6a52..9f08a424a1 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -111,7 +111,7 @@ object FrameGen { if (status != LsfgNative.STATUS_OK || cachePath == null) { WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) val problem = context.getString( - if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_problem_missing else R.string.lsfg_problem_failed, + if (status == LsfgNative.STATUS_NOT_INSTALLED) R.string.lsfg_needs_steam else R.string.lsfg_problem_failed, ) Log.w(TAG, "$problem (status $status)") return problem diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt b/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt index f78cb629ee..352885f558 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/Lossless.kt @@ -2,22 +2,16 @@ package com.droiddeck.launcher.gpu import android.content.Context import android.util.Log -import com.droiddeck.launcher.R import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.GameStorage -import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.security.DigestOutputStream import java.security.MessageDigest object Lossless { - enum class Source { NONE, STEAM, IMPORT } - - enum class ImportResult { UPDATED, UNCHANGED, NOT_OWNED, INVALID, FAILED } - - data class State(val owned: Boolean, val ready: Boolean, val source: Source) { + data class State(val owned: Boolean, val ready: Boolean) { companion object { - val NONE = State(owned = false, ready = false, source = Source.NONE) + val NONE = State(owned = false, ready = false) } } @@ -26,15 +20,13 @@ object Lossless { private const val KEY_OWNED = "owned" private const val KEY_ID = "id" private const val KEY_SOURCE = "source" + private const val SOURCE_STEAM = "STEAM" private const val KEY_STEAM_STAMP = "steamStamp" + private const val STEAM_MANIFEST = "steamapps/appmanifest_993090.acf" private const val STEAM_DLL = "steamapps/common/Lossless Scaling/Lossless.dll" private const val UNCHANGED = -1 - fun state(context: Context): State { - val source = prefs(context).getString(KEY_SOURCE, null) - ?.let { name -> Source.entries.firstOrNull { it.name == name } } ?: Source.NONE - return State(owned(context), cacheFile(context)?.isFile == true, source) - } + fun state(context: Context) = State(owned(context), cacheFile(context)?.isFile == true) fun owned(context: Context): Boolean { if (prefs(context).getBoolean(KEY_OWNED, false)) return true @@ -43,61 +35,46 @@ object Lossless { return true } - fun cacheFile(context: Context): File? = prefs(context).getString(KEY_ID, null)?.let { cacheFor(context, it) } + fun cacheFile(context: Context): File? = steamCacheId(context)?.let { cacheFor(context, it) } + + private fun steamCacheId(context: Context): String? = prefs(context).let { + if (it.getString(KEY_SOURCE, null) == SOURCE_STEAM) it.getString(KEY_ID, null) else null + } @Synchronized fun sync(context: Context): Int { + val settings = prefs(context) + if (steamCacheId(context) == null && settings.contains(KEY_ID)) { + settings.edit().remove(KEY_ID).remove(KEY_SOURCE).remove(KEY_STEAM_STAMP).apply() + } val steam = steamDll(context) if (steam != null) { markOwned(context) val stamp = "${steam.length()}:${steam.lastModified()}" - if (stamp != prefs(context).getString(KEY_STEAM_STAMP, null)) { - val status = adopt(context, steam, Source.STEAM) + if (stamp != settings.getString(KEY_STEAM_STAMP, null)) { + val status = adoptSteamDll(context, steam) if (status != LsfgNative.STATUS_OK && status != UNCHANGED) { Log.w(TAG, "Steam copy $steam not taken: ${statusName(status)}") } - prefs(context).edit().putString(KEY_STEAM_STAMP, stamp).apply() + settings.edit().putString(KEY_STEAM_STAMP, stamp).apply() } } return ensureBuilt(context) } - @Synchronized - fun import(context: Context, dll: File): ImportResult { - if (!owned(context)) return ImportResult.NOT_OWNED - return when (adopt(context, dll, Source.IMPORT)) { - UNCHANGED -> ImportResult.UNCHANGED - LsfgNative.STATUS_OK -> ImportResult.UPDATED - LsfgNative.STATUS_UNREADABLE_FILE, LsfgNative.STATUS_NOT_PORTABLE_EXECUTABLE, - LsfgNative.STATUS_MISSING_SHADERS -> ImportResult.INVALID - else -> ImportResult.FAILED - } - } - - fun message(context: Context, result: ImportResult): String = context.getString( - when (result) { - ImportResult.UPDATED -> R.string.lsfg_imported - ImportResult.UNCHANGED -> R.string.lsfg_import_unchanged - ImportResult.NOT_OWNED -> R.string.lsfg_import_not_owned - ImportResult.INVALID -> R.string.lsfg_import_invalid - ImportResult.FAILED -> R.string.lsfg_import_failed - }, - ) - private fun ensureBuilt(context: Context): Int { - val id = prefs(context).getString(KEY_ID, null) ?: return LsfgNative.STATUS_NOT_INSTALLED - val cache = cacheFor(context, id) + val cache = cacheFile(context) ?: return LsfgNative.STATUS_NOT_INSTALLED if (usable(cache)) return LsfgNative.STATUS_OK val dll = storedDll(context) if (!dll.isFile) return LsfgNative.STATUS_NOT_INSTALLED return build(dll, cache) } - private fun adopt(context: Context, source: File, from: Source): Int { + private fun adoptSteamDll(context: Context, source: File): Int { val staged = File(dir(context).apply { mkdirs() }, "Lossless.dll.staged") try { val id = copyHashing(source, staged) - if (id == prefs(context).getString(KEY_ID, null) && usable(cacheFor(context, id))) return UNCHANGED + if (id == steamCacheId(context) && usable(cacheFor(context, id))) return UNCHANGED val cache = cacheFor(context, id) var status = LsfgNative.nativeValidateDll(staged.path) if (status == LsfgNative.STATUS_OK) status = build(staged, cache) @@ -109,9 +86,9 @@ object Lossless { cache.delete() return LsfgNative.STATUS_CACHE_UNUSABLE } - prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, from.name).apply() + prefs(context).edit().putString(KEY_ID, id).putString(KEY_SOURCE, SOURCE_STEAM).apply() removeStale(context, id) - Log.i(TAG, "Lossless.dll from $source ($from) ready as $id") + Log.i(TAG, "Steam Lossless.dll from $source ready as $id") return LsfgNative.STATUS_OK } catch (e: java.io.IOException) { Log.w(TAG, "could not copy $source", e) @@ -158,9 +135,13 @@ object Lossless { GameStorage.effective(context)?.path?.let(::File), GameStorage.x64CardLibrary(context), ) + com.droiddeck.launcher.frontend.AddedGames.roots(context).map { it.host } - return libraries.map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() } + return installedSteamDll(libraries) } + internal fun installedSteamDll(libraries: List): File? = + libraries.asSequence().filter { File(it, STEAM_MANIFEST).isFile } + .map { File(it, STEAM_DLL) }.filter { it.isFile }.maxByOrNull { it.lastModified() } + private fun markOwned(context: Context) { if (!prefs(context).getBoolean(KEY_OWNED, false)) prefs(context).edit().putBoolean(KEY_OWNED, true).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt index b4f9ab9cb3..c1ddd7d704 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCloudSettingsPanel.kt @@ -106,7 +106,7 @@ private fun PanelContent( onChange(settings.copy(frameGen = it)) } Text("Native engine (experimental): Google's WebRTC and DroidDeck's own compositor, so DroidDeck frame generation " + - "(DDFG) or LSFG can add frames. LSFG uses the Lossless.dll DroidDeck already uses for games. Screen effects " + + "(DDFG) or LSFG can add frames. LSFG requires Lossless Scaling installed through Steam. Screen effects " + "apply to the web engine.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 8.dp, bottom = 6.dp)) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt index b4d12ba922..346a65d9b4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxNativePlayerActivity.kt @@ -623,11 +623,11 @@ class XboxNativePlayerActivity : ComponentActivity() { XboxMenuEntry((if (current.frameGen == mode) "✓ " else "") + fgName(mode), when (mode) { XboxNativeVideo.FG_DDFG -> "DroidDeck's own frame generation (DDFG); doubles the shown frame rate" XboxNativeVideo.FG_LSFG, XboxNativeVideo.FG_LSFG3, XboxNativeVideo.FG_LSFG4 -> - "Lossless Scaling frame generation (the Lossless.dll DroidDeck uses for games); the frame-rate target caps the output" + "Lossless Scaling frame generation from the Steam installation; the frame-rate target caps the output" else -> "Show the stream's own frames only" }, choices[i]) { current = current.copy(frameGen = mode); setFrameGen(mode) } } - if (!lsfg) androidx.compose.material3.Text("LSFG appears here once DroidDeck has the Lossless.dll (frame generation settings).", + if (!lsfg) androidx.compose.material3.Text("LSFG appears here once Lossless Scaling is installed through Steam.", style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = cs.onSurfaceVariant, modifier = androidx.compose.ui.Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) if (current.zeroCopy) androidx.compose.material3.Text( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt index 6745afaa01..3e8b6b1d1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DevPreview.kt @@ -199,7 +199,6 @@ internal fun SessionDrawerPreview(secondScreens: List) { secondScreenDisplays = secondScreens, selectedSecondScreenDisplay = secondScreens.firstOrNull()?.id ?: -1, onSecondScreenDisplay = {}, - onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = if (steam) ({}) else null, onQam = if (steam) ({}) else null, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt index 2ebf1d07b8..9e6667a28c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -24,18 +24,13 @@ internal fun FrameGenMenu( mode: FrameGen.Mode, lossless: Lossless.State, onPick: (FrameGen.Mode) -> Unit, - onImportLossless: () -> Unit, gameProfileId: String? = null, hasGameOverride: Boolean = false, onResetGame: () -> Unit = {}, focusModifier: Modifier = Modifier, legacyButtons: Boolean = false, ) { - val need = when { - lossless.ready -> null - lossless.owned -> stringResource(R.string.lsfg_needs_install) - else -> stringResource(R.string.lsfg_needs_steam) - } + val need = stringResource(R.string.lsfg_needs_steam) val selectedEngine = mode.engine.takeIf { it != FrameGen.ENGINE_OFF } val offLabel = FrameGen.label(LocalContext.current, FrameGen.Mode.OFF) val colors = MaterialTheme.colorScheme @@ -70,7 +65,7 @@ internal fun FrameGenMenu( } if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { Text( - need.orEmpty(), + need, color = colors.onSurfaceVariant, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(top = 6.dp), @@ -87,21 +82,6 @@ internal fun FrameGenMenu( Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") } } - if (lossless.owned) { - val using = when (lossless.source) { - Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam) - Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import) - Lossless.Source.NONE -> null - } - OutlinedButton( - onClick = onImportLossless, - modifier = Modifier.fillMaxWidth().padding(top = 6.dp) - .controllerConfirm(onClick = onImportLossless), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - ) { - Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: "")) - } - } } return } @@ -200,7 +180,7 @@ internal fun FrameGenMenu( } if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { - Text(need.orEmpty(), color = colors.onSurfaceVariant, + Text(need, color = colors.onSurfaceVariant, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(top = 6.dp)) } @@ -217,20 +197,5 @@ internal fun FrameGenMenu( } } - if (lossless.owned) { - val using = when (lossless.source) { - Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam) - Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import) - Lossless.Source.NONE -> null - } - OutlinedButton( - onClick = onImportLossless, - modifier = Modifier.fillMaxWidth().padding(top = 8.dp) - .controllerConfirm(onClick = onImportLossless), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - ) { - Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: "")) - } - } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 868d911534..917a46e71d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -246,7 +246,6 @@ class FrontEndActions( val onVkBridgeSafe: (Boolean) -> Unit = {}, val onBridgeProtonDxvk: (Boolean) -> Unit = {}, val onFrameGenPick: (FrameGen.Mode) -> Unit, - val onImportLossless: () -> Unit, val onProtons: () -> Unit, val onComponents: (focusContent: Boolean) -> Unit, val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) }, 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 5fe2b12fec..3bec0c50aa 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -860,7 +860,7 @@ internal fun ReadinessCard( @Composable private fun FrameGenMenu(s: FrontEndState, a: FrontEndActions, host: MenuHost) { - FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless, legacyButtons = true) + FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, legacyButtons = true) } @Composable @@ -901,7 +901,6 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost gameFrameGenOverride = true } }, - onImportLossless = a.onImportLossless, legacyButtons = true, gameProfileId = frameGenProfileKey, hasGameOverride = gameFrameGenOverride, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 861ece858d..8791d880d2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -316,7 +316,6 @@ class DrawerActions( val hdr: Boolean = false, val hdrAvailable: Boolean = false, val onHdr: (Boolean) -> Unit = {}, - val onImportLossless: () -> Unit, val onKeyboard: () -> Unit, val onHardwareKeyboard: () -> Unit, val wowChatShown: Boolean = false, @@ -906,7 +905,7 @@ private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) SettingsGroup(stringResource(R.string.frame_gen_title), compact = true, key = "frame-generation", detail = summary(fgLabel, scope)) { SettingsRow(stringResource(R.string.frame_gen_title), scope, stacked = true, tightControlSpacing = true) { FrameGenMenu( - a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless, + a.frameGen, a.lossless, a.onFrameGenPick, gameProfileId = a.frameGenTargetGameId, hasGameOverride = a.hasGameOverride, onResetGame = a.onFrameGenReset, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt index 0917f56d8a..af9136fba4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt @@ -31,10 +31,6 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) { a.onFrameGenPick(mode) host.open = null }, - onImportLossless = { - a.onImportLossless() - host.open = null - }, focusModifier = Modifier.focusRequester(firstItemFocus), legacyButtons = true, ) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 8e3855073f..754bd58c81 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG تكيّفي %1$d يتطلب Lossless Scaling على Steam - ثبّت Lossless Scaling في Steam أو استورد Lossless.dll - استيراد Lossless.dll… - يتم استخدام النسخة الموجودة في Steam - يتم استخدام نسخة مستوردة - اختر Lossless.dll - تم استيراد Lossless.dll - ملف Lossless.dll هذا قيد الاستخدام بالفعل - حساب Steam هذا لا يملك Lossless Scaling - هذا الملف ليس Lossless.dll الخاص بـ Lossless Scaling - تعذّر تجهيز LSFG من ملف Lossless.dll هذا - يتطلب LSFG برنامج Lossless Scaling من Steam أو ملف Lossless.dll مستوردًا تعذّر على LSFG تجهيز أدوات التظليل من Lossless.dll %1$s: غير مدعوم %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 2b8c9a4afe..f6780a5bd2 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptativo %1$d Requiere Lossless Scaling en Steam - Instala Lossless Scaling en Steam o importa Lossless.dll - Importar Lossless.dll… - Usando la copia de Steam - Usando una copia importada - Elegir Lossless.dll - Lossless.dll importado - Este Lossless.dll ya está en uso - Lossless Scaling no está en esta cuenta de Steam - Este archivo no es el Lossless.dll de Lossless Scaling - No se pudo preparar LSFG con este Lossless.dll - LSFG necesita Lossless Scaling de Steam o un Lossless.dll importado LSFG no pudo preparar sus shaders desde Lossless.dll %1$s: no compatible %1$s: falló el motor diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index b8e3bf6443..ad5942ef4e 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Адаптивно %1$d Изисква Lossless Scaling в Steam - Инсталирайте Lossless Scaling в Steam или импортирайте Lossless.dll - Импортиране на Lossless.dll… - Използва се копието от Steam - Използва се импортирано копие - Изберете Lossless.dll - Lossless.dll е импортиран - Този Lossless.dll вече се използва - Lossless Scaling не е закупен за този акаунт в Steam - Този файл не е Lossless.dll на Lossless Scaling - LSFG не можа да се подготви от този Lossless.dll - LSFG изисква Lossless Scaling от Steam или импортиран Lossless.dll LSFG не можа да подготви шейдърите си от Lossless.dll %1$s: не се поддържа %1$s: грешка в двигателя diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 0a07d4b77d..dc6d83dcc3 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptivní %1$d Vyžaduje Lossless Scaling na Steamu - Nainstalujte Lossless Scaling ve Steamu nebo naimportujte Lossless.dll - Importovat Lossless.dll… - Používá se kopie ze Steamu - Používá se importovaná kopie - Vyberte Lossless.dll - Lossless.dll byl importován - Tento Lossless.dll se už používá - Tento účet Steamu nevlastní Lossless Scaling - Tento soubor není Lossless.dll aplikace Lossless Scaling - Z tohoto souboru Lossless.dll se nepodařilo připravit LSFG - LSFG vyžaduje Lossless Scaling ze Steamu nebo importovaný Lossless.dll LSFG se nepodařilo připravit shadery z Lossless.dll %1$s: nepodporováno %1$s: chyba enginu diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 5024a32b3d..62ba81b634 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Kræver Lossless Scaling på Steam - Installer Lossless Scaling via Steam, eller importer Lossless.dll - Importer Lossless.dll… - Bruger kopien fra Steam - Bruger en importeret kopi - Vælg Lossless.dll - Lossless.dll importeret - Denne Lossless.dll er allerede i brug - Lossless Scaling ejes ikke på denne Steam-konto - Denne fil er ikke Lossless Scalings Lossless.dll - Kunne ikke forberede LSFG fra denne Lossless.dll - LSFG kræver Lossless Scaling fra Steam eller en importeret Lossless.dll LSFG kunne ikke forberede sine shadere fra Lossless.dll %1$s: ikke understøttet %1$s: motoren fejlede diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 9e7d0b6eea..b3cef5f653 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Benötigt Lossless Scaling auf Steam - Installiere Lossless Scaling in Steam oder importiere Lossless.dll - Lossless.dll importieren… - Kopie aus Steam wird verwendet - Importierte Kopie wird verwendet - Lossless.dll auswählen - Lossless.dll importiert - Diese Lossless.dll wird bereits verwendet - Dieses Steam-Konto besitzt Lossless Scaling nicht - Diese Datei ist nicht die Lossless.dll von Lossless Scaling - LSFG konnte aus dieser Lossless.dll nicht vorbereitet werden - LSFG benötigt Lossless Scaling aus Steam oder eine importierte Lossless.dll LSFG konnte seine Shader nicht aus Lossless.dll vorbereiten %1$s: nicht unterstützt %1$s: Engine-Fehler diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4785a0a435..2c0bc9f686 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG προσαρμοστικό %1$d Απαιτεί το Lossless Scaling στο Steam - Εγκαταστήστε το Lossless Scaling στο Steam ή εισαγάγετε το Lossless.dll - Εισαγωγή Lossless.dll… - Χρήση του αντιγράφου από το Steam - Χρήση ενός εισαγμένου αντιγράφου - Επιλογή Lossless.dll - Το Lossless.dll εισήχθη - Αυτό το Lossless.dll χρησιμοποιείται ήδη - Αυτός ο λογαριασμός Steam δεν κατέχει το Lossless Scaling - Αυτό το αρχείο δεν είναι το Lossless.dll του Lossless Scaling - Δεν ήταν δυνατή η προετοιμασία του LSFG από αυτό το Lossless.dll - Το LSFG απαιτεί το Lossless Scaling από το Steam ή ένα εισαγμένο Lossless.dll Το LSFG δεν μπόρεσε να προετοιμάσει τα shaders του από το Lossless.dll %1$s: μη υποστηριζόμενο %1$s: αποτυχία μηχανής diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 78eccb5bed..b7d9fc9715 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptativo %1$d Requiere Lossless Scaling en Steam - Instala Lossless Scaling en Steam o importa Lossless.dll - Importar Lossless.dll… - Usando la copia de Steam - Usando una copia importada - Elegir Lossless.dll - Lossless.dll importado - Este Lossless.dll ya está en uso - Lossless Scaling no está en esta cuenta de Steam - Este archivo no es el Lossless.dll de Lossless Scaling - No se pudo preparar LSFG con este Lossless.dll - LSFG necesita Lossless Scaling de Steam o un Lossless.dll importado LSFG no pudo preparar sus shaders desde Lossless.dll %1$s: no compatible %1$s: falló el motor diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 1108badf1a..72b6e1bf8b 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Mukautuva %1$d Vaatii Lossless Scalingin Steamista - Asenna Lossless Scaling Steamista tai tuo Lossless.dll - Tuo Lossless.dll… - Käytössä on Steamin kopio - Käytössä on tuotu kopio - Valitse Lossless.dll - Lossless.dll tuotu - Tämä Lossless.dll on jo käytössä - Lossless Scaling ei ole tämän Steam-tilin omistuksessa - Tämä tiedosto ei ole Lossless Scalingin Lossless.dll - LSFG:n valmistelu tästä Lossless.dll-tiedostosta epäonnistui - LSFG tarvitsee Lossless Scalingin Steamista tai tuodun Lossless.dll-tiedoston LSFG ei pystynyt valmistelemaan sävyttimiään Lossless.dll-tiedostosta %1$s: ei tuettu %1$s: moottori epäonnistui diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 3182517c3e..e45c8eaeb6 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptatif %1$d Nécessite Lossless Scaling sur Steam - Installez Lossless Scaling sur Steam ou importez Lossless.dll - Importer Lossless.dll… - Utilise la version sur Steam - Utilise la version importée - Sélectionner le fichier Lossless.dll - Lossless.dll importé - Ce Lossless.dll est déjà utilisé - Ce compte Steam ne possède pas Lossless Scaling - Ce fichier n\'est pas le Lossless.dll de Lossless Scaling - Impossible de préparer LSFG à partir de ce Lossless.dll - LSFG nécessite Lossless Scaling depuis Steam, ou un fichier Lossless.dll importé LSFG ne peut pas préparer ses shaders à partir de ce Lossless.dll %1$s : non pris en charge %1$s : échec du moteur diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index edf9cad53c..264f4ec9a3 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG एडैप्टिव %1$d Steam पर Lossless Scaling की ज़रूरत है - Steam में Lossless Scaling इंस्टॉल करें या Lossless.dll इंपोर्ट करें - Lossless.dll इंपोर्ट करें… - Steam वाली कॉपी का उपयोग हो रहा है - इंपोर्ट की गई कॉपी का उपयोग हो रहा है - Lossless.dll चुनें - Lossless.dll इंपोर्ट हो गई - यह Lossless.dll पहले से उपयोग में है - इस Steam खाते में Lossless Scaling नहीं है - यह फ़ाइल Lossless Scaling की Lossless.dll नहीं है - इस Lossless.dll से LSFG तैयार नहीं हो सका - LSFG को Steam से Lossless Scaling या इंपोर्ट की गई Lossless.dll चाहिए LSFG अपने शेडर Lossless.dll से तैयार नहीं कर सका %1$s: असमर्थित %1$s: इंजन विफल diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 83f27827ab..8fbbda9dc7 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptív %1$d A Lossless Scaling szükséges a Steamen - Telepítse a Lossless Scalinget a Steamen, vagy importálja a Lossless.dll fájlt - Lossless.dll importálása… - A Steamről származó másolat használatban - Egy importált másolat használatban - Válassza ki a Lossless.dll fájlt - A Lossless.dll importálva - Ez a Lossless.dll már használatban van - A Lossless Scaling nincs a tulajdonában ezen a Steam-fiókon - Ez a fájl nem a Lossless Scaling Lossless.dll fájlja - Nem sikerült előkészíteni az LSFG-t ebből a Lossless.dll fájlból - Az LSFG-hez szükséges a Lossless Scaling a Steamről vagy egy importált Lossless.dll Az LSFG nem tudta előkészíteni a shadereket a Lossless.dll fájlból %1$s: nem támogatott %1$s: a motor hibát jelzett diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 917f200f35..b31983df6a 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptif %1$d Memerlukan Lossless Scaling di Steam - Instal Lossless Scaling di Steam atau impor Lossless.dll - Impor Lossless.dll… - Menggunakan salinan dari Steam - Menggunakan salinan yang diimpor - Pilih Lossless.dll - Lossless.dll diimpor - Lossless.dll ini sudah digunakan - Lossless Scaling tidak dimiliki di akun Steam ini - File ini bukan Lossless.dll milik Lossless Scaling - Tidak dapat menyiapkan LSFG dari Lossless.dll ini - LSFG memerlukan Lossless Scaling dari Steam atau Lossless.dll yang diimpor LSFG tidak dapat menyiapkan shader-nya dari Lossless.dll %1$s: tidak didukung %1$s: mesin gagal diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index ca5fe6244b..9b21a504f5 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adattivo %1$d Richiede Lossless Scaling su Steam - Installa Lossless Scaling in Steam o importa Lossless.dll - Importa Lossless.dll… - In uso la copia di Steam - In uso una copia importata - Scegli Lossless.dll - Lossless.dll importato - Questo Lossless.dll è già in uso - Questo account Steam non possiede Lossless Scaling - Questo file non è il Lossless.dll di Lossless Scaling - Impossibile preparare LSFG da questo Lossless.dll - LSFG richiede Lossless Scaling da Steam o un Lossless.dll importato LSFG non è riuscito a preparare gli shader da Lossless.dll %1$s: non supportato %1$s: errore del motore diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 9af7084b49..1e37e3fd19 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG アダプティブ %1$d Steam版のLossless Scalingが必要です - SteamでLossless Scalingをインストールするか、Lossless.dllをインポートしてください - Lossless.dllをインポート… - Steam版を使用中 - インポート版を使用中 - Lossless.dllファイルを選択 - Lossless.dllをインポートしました - このLossless.dllはすでに使用されています - このSteamアカウントはLossless Scalingを所有していません - このファイルはLossless ScalingのLossless.dllではありません - このLossless.dllからLSFGを準備できませんでした - LSFGにはSteam版のLossless Scaling、またはインポートされたLossless.dllファイルが必要です LSFGはこのLossless.dllからシェーダーを準備できませんでした %1$s:サポート外 %1$s:エンジンエラー diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 1603ed7eb2..4265a93915 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 적응형 %1$d Steam에서 Lossless Scaling이 필요합니다 - Steam에서 Lossless Scaling을 설치하거나 Lossless.dll을 가져오세요 - Lossless.dll 가져오기… - Steam 버전 사용 중 - 가져온 버전 사용 중 - Lossless.dll 파일 선택 - Lossless.dll을 가져왔습니다 - 이 Lossless.dll은 이미 사용 중입니다 - 이 Steam 계정에는 Lossless Scaling이 없습니다 - 이 파일은 Lossless Scaling의 Lossless.dll이 아닙니다 - 이 Lossless.dll에서 LSFG를 준비할 수 없습니다 - LSFG에는 Steam의 Lossless Scaling 또는 가져온 Lossless.dll 파일이 필요합니다 LSFG가 이 Lossless.dll에서 셰이더를 준비할 수 없습니다 %1$s: 지원되지 않음 %1$s: 엔진 실패 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 5728d85712..d756db11c2 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptif %1$d Memerlukan Lossless Scaling pada Steam - Pasang Lossless Scaling dalam Steam atau import Lossless.dll - Import Lossless.dll… - Menggunakan salinan daripada Steam - Menggunakan salinan yang diimport - Pilih Lossless.dll - Lossless.dll diimport - Lossless.dll ini sudah digunakan - Lossless Scaling tidak dimiliki pada akaun Steam ini - Fail ini bukan Lossless.dll milik Lossless Scaling - Tidak dapat menyediakan LSFG daripada Lossless.dll ini - LSFG memerlukan Lossless Scaling daripada Steam atau Lossless.dll yang diimport LSFG tidak dapat menyediakan shadernya daripada Lossless.dll %1$s: tidak disokong %1$s: enjin gagal diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index ce52e5ffb2..19ef1fb16e 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Krever Lossless Scaling på Steam - Installer Lossless Scaling via Steam, eller importer Lossless.dll - Importer Lossless.dll… - Bruker kopien fra Steam - Bruker en importert kopi - Velg Lossless.dll - Lossless.dll importert - Denne Lossless.dll-filen er allerede i bruk - Lossless Scaling eies ikke av denne Steam-kontoen - Denne filen er ikke Lossless Scalings Lossless.dll - Kunne ikke forberede LSFG fra denne Lossless.dll-filen - LSFG krever Lossless Scaling fra Steam eller en importert Lossless.dll LSFG kunne ikke forberede shaderne sine fra Lossless.dll %1$s: ikke støttet %1$s: motoren feilet diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 59c533f657..bcf4b8e01b 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptief %1$d Vereist Lossless Scaling op Steam - Installeer Lossless Scaling in Steam of importeer Lossless.dll - Lossless.dll importeren… - De kopie uit Steam wordt gebruikt - Een geïmporteerde kopie wordt gebruikt - Kies Lossless.dll - Lossless.dll geïmporteerd - Deze Lossless.dll wordt al gebruikt - Lossless Scaling staat niet op dit Steam-account - Dit bestand is niet de Lossless.dll van Lossless Scaling - Kan LSFG niet voorbereiden met deze Lossless.dll - LSFG vereist Lossless Scaling uit Steam of een geïmporteerde Lossless.dll LSFG kan zijn shaders niet voorbereiden uit Lossless.dll %1$s: niet ondersteund %1$s: engine mislukt diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 7f0506bd7e..a5600f8599 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptacyjne %1$d Wymaga Lossless Scaling ze Steam - Zainstaluj Lossless Scaling w Steam lub zaimportuj Lossless.dll - Importuj Lossless.dll… - Używana jest kopia ze Steam - Używana jest zaimportowana kopia - Wybierz Lossless.dll - Zaimportowano Lossless.dll - Ten plik Lossless.dll jest już używany - To konto Steam nie ma Lossless Scaling - Ten plik to nie Lossless.dll z Lossless Scaling - Nie udało się przygotować LSFG z tego pliku Lossless.dll - LSFG wymaga Lossless Scaling ze Steam lub zaimportowanego pliku Lossless.dll Nie udało się przygotować shaderów LSFG z pliku Lossless.dll %1$s: nieobsługiwane %1$s: błąd silnika diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 6eb5f0849a..e4a63e898e 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptativo %1$d Requer o Lossless Scaling no Steam - Instale o Lossless Scaling no Steam ou importe o Lossless.dll - Importar Lossless.dll… - A utilizar a cópia do Steam - A utilizar uma cópia importada - Escolher Lossless.dll - Lossless.dll importado - Este Lossless.dll já está a ser utilizado - Esta conta Steam não possui o Lossless Scaling - Este ficheiro não é o Lossless.dll do Lossless Scaling - Não foi possível preparar o LSFG a partir deste Lossless.dll - O LSFG requer o Lossless Scaling do Steam ou um Lossless.dll importado O LSFG não conseguiu preparar os shaders a partir do Lossless.dll %1$s: não suportado %1$s: falha do motor diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 93d4bc6eec..86bf64d7b3 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptativo %1$d Requer o Lossless Scaling na Steam - Instale o Lossless Scaling na Steam ou importe o Lossless.dll - Importar Lossless.dll… - Usando a cópia da Steam - Usando uma cópia importada - Escolha o Lossless.dll - Lossless.dll importado - Este Lossless.dll já está em uso - Esta conta Steam não tem o Lossless Scaling - Este arquivo não é o Lossless.dll do Lossless Scaling - Não foi possível preparar o LSFG com este Lossless.dll - O LSFG requer o Lossless Scaling da Steam ou um Lossless.dll importado O LSFG não conseguiu preparar os shaders a partir do Lossless.dll %1$s: sem suporte %1$s: falha no mecanismo diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 9e105d493c..8b546406e7 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Adaptiv %1$d Necesită Lossless Scaling pe Steam - Instalează Lossless Scaling în Steam sau importă Lossless.dll - Importă Lossless.dll… - Se folosește copia din Steam - Se folosește o copie importată - Alege Lossless.dll - Lossless.dll importat - Acest Lossless.dll este deja în uz - Lossless Scaling nu este deținut pe acest cont Steam - Acest fișier nu este Lossless.dll al Lossless Scaling - Nu s-a putut pregăti LSFG din acest Lossless.dll - LSFG are nevoie de Lossless Scaling din Steam sau de un Lossless.dll importat LSFG nu a putut pregăti shaderele din Lossless.dll %1$s: neacceptat %1$s: motor eșuat diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index b3b0450459..ba81437f53 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Адаптивный %1$d Требуется Lossless Scaling из Steam - Установите Lossless Scaling в Steam или импортируйте Lossless.dll - Импорт Lossless.dll… - Используется копия из Steam - Используется импортированная копия - Выберите файл Lossless.dll - Lossless.dll импортирован - Этот Lossless.dll уже используется - В этой учетной записи Steam нет Lossless Scaling - Этот файл не является Lossless.dll от Lossless Scaling - Не удалось подготовить LSFG из этого Lossless.dll - Для LSFG требуется Lossless Scaling из Steam или импортированный файл Lossless.dll LSFG не удалось подготовить шейдеры из Lossless.dll %1$s: не поддерживается %1$s: сбой движка diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 23d08a1e84..6a807c9cf6 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG adaptiv %1$d Kräver Lossless Scaling på Steam - Installera Lossless Scaling i Steam eller importera Lossless.dll - Importera Lossless.dll… - Använder kopian från Steam - Använder en importerad kopia - Välj Lossless.dll - Lossless.dll har importerats - Den här Lossless.dll används redan - Lossless Scaling ägs inte på det här Steam-kontot - Filen är inte Lossless.dll från Lossless Scaling - Kunde inte förbereda LSFG från den här Lossless.dll - LSFG kräver Lossless Scaling från Steam eller en importerad Lossless.dll LSFG kunde inte förbereda sina shaders från Lossless.dll %1$s: stöds inte %1$s: motorn misslyckades diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 637f355e55..1e740d1d48 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG แบบปรับอัตโนมัติ %1$d ต้องมี Lossless Scaling บน Steam - ติดตั้ง Lossless Scaling ใน Steam หรือนำเข้า Lossless.dll - นำเข้า Lossless.dll… - ใช้ชุดที่มาจาก Steam - ใช้ชุดที่นำเข้ามา - เลือก Lossless.dll - นำเข้า Lossless.dll แล้ว - Lossless.dll นี้ถูกใช้งานอยู่แล้ว - บัญชี Steam นี้ไม่ได้เป็นเจ้าของ Lossless Scaling - ไฟล์นี้ไม่ใช่ Lossless.dll ของ Lossless Scaling - ไม่สามารถเตรียม LSFG จาก Lossless.dll นี้ได้ - LSFG ต้องใช้ Lossless Scaling จาก Steam หรือ Lossless.dll ที่นำเข้ามา LSFG ไม่สามารถเตรียมเชดเดอร์จาก Lossless.dll ได้ %1$s: ไม่รองรับ %1$s: เอนจินล้มเหลว diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 589d37181b..360505b6e6 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG Uyarlanabilir %1$d Steam\'de Lossless Scaling gerekli - Lossless Scaling\'i Steam\'den yükleyin veya Lossless.dll dosyasını içe aktarın - Lossless.dll içe aktar… - Steam\'deki kopya kullanılıyor - İçe aktarılan kopya kullanılıyor - Lossless.dll seçin - Lossless.dll içe aktarıldı - Bu Lossless.dll zaten kullanılıyor - Bu Steam hesabı Lossless Scaling\'e sahip değil - Bu dosya Lossless Scaling\'in Lossless.dll dosyası değil - Bu Lossless.dll ile LSFG hazırlanamadı - LSFG için Steam\'den Lossless Scaling veya içe aktarılmış bir Lossless.dll gerekir LSFG, gölgelendiricilerini Lossless.dll dosyasından hazırlayamadı %1$s: desteklenmiyor %1$s: motor hatası diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 170c957af6..fe153bb8d9 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG адаптивний %1$d Потрібен Lossless Scaling зі Steam - Установіть Lossless Scaling у Steam або імпортуйте Lossless.dll - Імпортувати Lossless.dll… - Використовується копія зі Steam - Використовується імпортована копія - Виберіть Lossless.dll - Lossless.dll імпортовано - Цей Lossless.dll уже використовується - У цьому обліковому записі Steam немає Lossless Scaling - Цей файл не є Lossless.dll від Lossless Scaling - Не вдалося підготувати LSFG із цього Lossless.dll - Для LSFG потрібен Lossless Scaling зі Steam або імпортований Lossless.dll LSFG не вдалося підготувати шейдери з Lossless.dll %1$s: не підтримується %1$s: збій рушія diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 731a804078..89f173d547 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG thích ứng %1$d Cần Lossless Scaling trên Steam - Cài Lossless Scaling trong Steam hoặc nhập Lossless.dll - Nhập Lossless.dll… - Đang dùng bản sao từ Steam - Đang dùng bản đã nhập - Chọn Lossless.dll - Đã nhập Lossless.dll - Lossless.dll này đã đang được dùng - Tài khoản Steam này không sở hữu Lossless Scaling - Tệp này không phải là Lossless.dll của Lossless Scaling - Không thể chuẩn bị LSFG từ Lossless.dll này - LSFG cần Lossless Scaling từ Steam hoặc một Lossless.dll đã nhập LSFG không thể chuẩn bị shader từ Lossless.dll %1$s: không hỗ trợ %1$s: engine lỗi diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 9f180077ae..faca08c4fa 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 自适应 %1$d 需要 Steam 上的 Lossless Scaling - 请在 Steam 中安装 Lossless Scaling,或导入 Lossless.dll - 导入 Lossless.dll… - 正在使用 Steam 中的副本 - 正在使用已导入的副本 - 选择 Lossless.dll - Lossless.dll 已导入 - 该 Lossless.dll 已在使用中 - 此 Steam 账户未拥有 Lossless Scaling - 该文件不是 Lossless Scaling 的 Lossless.dll - 无法由此 Lossless.dll 准备 LSFG - LSFG 需要 Steam 上的 Lossless Scaling 或已导入的 Lossless.dll LSFG 无法从 Lossless.dll 准备其着色器 %1$s:不支持 %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 5d7fb121c1..dad8b25c85 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 自適應 %1$d 需要 Steam 上的 Lossless Scaling - 請在 Steam 安裝 Lossless Scaling,或匯入 Lossless.dll - 匯入 Lossless.dll… - 正在使用 Steam 上的版本 - 正在使用匯入的版本 - 選擇 Lossless.dll - 已匯入 Lossless.dll - 此 Lossless.dll 已在使用中 - 此 Steam 帳戶未擁有 Lossless Scaling - 此檔案不是 Lossless Scaling 的 Lossless.dll - 無法從此 Lossless.dll 準備 LSFG - LSFG 需要 Steam 上的 Lossless Scaling 或已匯入的 Lossless.dll LSFG 無法從 Lossless.dll 準備著色器 %1$s:不支援 %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 0b0757d78b..dbe4020e01 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -55,17 +55,6 @@ LSFG %1$d× LSFG 自適應 %1$d 需要 Steam 上的 Lossless Scaling - 在 Steam 中安裝 Lossless Scaling,或匯入 Lossless.dll - 匯入 Lossless.dll… - 正在使用 Steam 上的版本 - 正在使用匯入的版本 - 選擇 Lossless.dll 檔案 - 已匯入 Lossless.dll - 這個 Lossless.dll 已經在使用中了 - 此 Steam 帳號沒有 Lossless Scaling - 此檔案不是 Lossless Scaling 的 Lossless.dll - 無法從此 Lossless.dll 準備 LSFG - LSFG 需要來自 Steam 的 Lossless Scaling,或是匯入的 Lossless.dll 檔案 LSFG 無法從此 Lossless.dll 準備其著色器 %1$s:不支援 %1$s:引擎失敗 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bbbbd62661..8e2be5a9f9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -83,17 +83,6 @@ LSFG %1$d× LSFG Adaptive %1$d Needs Lossless Scaling on Steam - Install Lossless Scaling in Steam or import Lossless.dll - Import Lossless.dll… - Using the copy from Steam - Using an imported copy - Choose Lossless.dll - Lossless.dll imported - This Lossless.dll is already in use - Lossless Scaling is not owned on this Steam account - This file is not Lossless Scaling\'s Lossless.dll - Could not prepare LSFG from this Lossless.dll - LSFG needs Lossless Scaling from Steam or an imported Lossless.dll LSFG could not prepare its shaders from Lossless.dll %1$s: unsupported %1$s: engine failed diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt index 1583514770..23098cc9c0 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/LosslessTest.kt @@ -40,9 +40,39 @@ class LosslessTest { assertTrue(Lossless.owned(context)) } - @Test fun importIsRefusedWithoutOwnership() { - val dll = File(context.cacheDir, "Lossless.dll").apply { writeText("not a dll") } - assertFalse(Lossless.owned(context)) - assertEquals(Lossless.ImportResult.NOT_OWNED, Lossless.import(context, dll)) + @Test fun anOldManualImportCannotBeUsedOrRebuiltEvenWhenOwned() { + val prefs = context.getSharedPreferences("lossless", Context.MODE_PRIVATE) + prefs.edit().putBoolean("owned", true).putString("source", "IMPORT").putString("id", "legacy") + .putString("steamStamp", "old stamp").commit() + val dir = File(context.filesDir, "lsfg").apply { mkdirs() } + File(dir, "Lossless.dll").writeText("legacy DLL") + File(dir, "shaders-legacy.cache").writeText("legacy cache") + + assertFalse(Lossless.state(context).ready) + assertNull(Lossless.cacheFile(context)) + assertEquals(LsfgNative.STATUS_NOT_INSTALLED, Lossless.sync(context)) + assertFalse(prefs.contains("steamStamp")) + assertTrue(Lossless.owned(context)) + } + + @Test fun aPreviouslyPreparedSteamCacheRemainsAvailable() { + val prefs = context.getSharedPreferences("lossless", Context.MODE_PRIVATE) + prefs.edit().putBoolean("owned", true).putString("source", "STEAM").putString("id", "steam").commit() + val cache = File(File(context.filesDir, "lsfg").apply { mkdirs() }, "shaders-steam.cache") + cache.writeText("cache") + + assertEquals(cache, Lossless.cacheFile(context)) + assertTrue(Lossless.state(context).ready) + } + + @Test fun looseDllWithoutAnInstallManifestDoesNotCountAsASteamInstall() { + val library = File(context.cacheDir, "library") + val dll = File(library, "steamapps/common/Lossless Scaling/Lossless.dll") + dll.parentFile!!.mkdirs() + dll.writeText("fixture") + + assertNull(Lossless.installedSteamDll(listOf(library))) + File(library, "steamapps/appmanifest_993090.acf").writeText("fixture") + assertEquals(dll, Lossless.installedSteamDll(listOf(library))) } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt index b16a03071b..186a6c7e4b 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -300,7 +300,7 @@ class CurseLinkTabTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt index 641de899ac..b8e35d27aa 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/DesktopUninstallTest.kt @@ -85,7 +85,7 @@ class DesktopUninstallTest { ), FrontEndActions( onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, - onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, + onRuntime = {}, onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = { removals++ }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt index b685aac7ec..3891479800 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/FlathubFocusTest.kt @@ -65,7 +65,7 @@ class FlathubFocusTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt index 97d1d95094..404cf23731 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamesClientTagTest.kt @@ -56,7 +56,7 @@ class GamesClientTagTest { onPlay = {}, onPlaySteamVr = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt index cdc52f5e28..1a0404f748 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GlobalGlassesSettingsTest.kt @@ -165,7 +165,7 @@ class GlobalGlassesSettingsTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt index 508e2ed4b6..7adbbfacc4 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -98,7 +98,7 @@ class InputUiLayoutTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, controller = ControllerActions({}), diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt index 65eef5d38f..4fd6e49737 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt @@ -63,7 +63,7 @@ class LaunchSettingsComponentsTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = { defaultOpens++ }, + onProtons = {}, onComponents = { defaultOpens++ }, onGameComponents = { openedGame = it }, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt index 87e1d0bbb3..3ed1e0763c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -249,7 +249,7 @@ class LibraryVisibilityTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index ecf3f6528e..3205eddb63 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -286,7 +286,7 @@ class NavTabsTest { private fun actions() = FrontEndActions( onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, - onRuntime = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, + onRuntime = {}, onFrameGenPick = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, onRemoveDesktop = {}, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt index 004fe8cd64..6fba8b7e8c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavigationSelectionTest.kt @@ -92,7 +92,7 @@ class NavigationSelectionTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt index f791b1af8e..fd650cf014 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PenSettingsGroupTest.kt @@ -95,7 +95,7 @@ class PenSettingsGroupTest { suspendPolicy = "auto", backActionsInverted = false, touchMode = "auto", touchAuto = "touchpad", pen = pen, onPen = onPen, fexPreset = "default", secondScreenMode = SecondScreenMode.NONE, secondScreenDisplays = emptyList(), selectedSecondScreenDisplay = 1, - onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, + onHud = {}, onFrameGenPick = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {}, onTouch = {}, onFexPreset = {}, onSecondScreenMode = {}, onSecondScreenDisplay = {}, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {}) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt index f5988c0b80..42603b4571 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -150,7 +150,7 @@ class PortraitLayoutTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt index 83c5e1a0d3..4fed06c1c4 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -416,7 +416,7 @@ class SessionSecondScreenTest { suspendPolicy = "auto", backActionsInverted = false, touchMode = "auto", touchAuto = "trackpad", fexPreset = "default", secondScreenMode = mode, secondScreenDisplays = displays, selectedSecondScreenDisplay = 1, gameSwapAvailable = gameSwap, - onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {}, + onHud = {}, onFrameGenPick = {}, onKeyboard = {}, onHardwareKeyboard = {}, onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {}, onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {}, onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = onClose) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt index f4c4688f4a..1f30f896af 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SteamHomeHeadsetTest.kt @@ -99,7 +99,7 @@ class SteamHomeHeadsetTest { onPlay = {}, onPlaySteamVr = { vrStarts++ }, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt index 97f5c16ae9..f2afa15029 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt @@ -143,7 +143,7 @@ class StoreRestorationTest { onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, - onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, onSetPhantomProcessLimit = { _, _ -> }, From 59eaa0eb063dbf849f80bb59ff782eb29fdd96b4 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:53:28 -0500 Subject: [PATCH 3/8] fix(agent): after agent setup, Gradle and git work on the device (#3642) --- app/src/main/assets/agent/dd-gh-login | 17 ++++++++++++ .../droiddeck/launcher/agent/AgentSetup.kt | 13 +++++++++- tools/agent/AGENTS.md | 4 ++- tools/agent/dd-gh-login | 17 ++++++++++++ tools/agent/setup | 26 +++++++++++++++++++ 5 files changed, 75 insertions(+), 2 deletions(-) diff --git a/app/src/main/assets/agent/dd-gh-login b/app/src/main/assets/agent/dd-gh-login index f9b0b7734a..e02054ffc1 100644 --- a/app/src/main/assets/agent/dd-gh-login +++ b/app/src/main/assets/agent/dd-gh-login @@ -28,6 +28,19 @@ float_code() { [ "$result" = ok ] } +# git pushes through gh's sign-in and commits as the signed-in account, with its no-reply address. +configure_git() { + gh auth setup-git || return 1 + [ -n "$(git config --global user.name)" ] && [ -n "$(git config --global user.email)" ] && return 0 + local user id login name + user=$(gh api user -q '"\(.id) \(.login) \(.name // .login)"') || return 1 + read -r id login name <<<"$user" + [ -n "$id" ] && [ -n "$login" ] || return 1 + [ -n "$(git config --global user.name)" ] || git config --global user.name "${name:-$login}" + [ -n "$(git config --global user.email)" ] || git config --global user.email "$id+$login@users.noreply.github.com" +} +if [ "${1:-}" = --git ]; then configure_git; exit; fi + coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; } gh_pid=$GH_PID exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}" @@ -48,5 +61,9 @@ while IFS= read -r line <&"$ghout"; do done wait "$gh_pid" status=$? +if [ $status = 0 ] && ! configure_git; then + echo "Signed in, but git could not be set up: run dd-gh-login --git" + status=1 +fi [ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code" exit $status diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index aa2ad40ae7..ad78dd3d44 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -226,7 +226,18 @@ object AgentSetup { /** The whole output of a step's last run; the card shows only its last line. */ fun logFile(app: Context, step: Step) = File(app.filesDir, "agent/setup-${step.name.lowercase()}.log") - fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") + /** + * An install set up before setup wrote the Gradle init script gets the step again, but only + * once the checkout's setup writes it: the step runs that script, and an older one never would. + */ + fun buildToolsInstalled(app: Context) = AgentHost.guestFileExists(app, "/root/aapt2/aapt2") && AgentHost.guestFileExists(app, "$CHECKOUT/.git") && + (AgentHost.guestFileExists(app, GRADLE_INIT) || !setupWritesGradleInit(app)) + + private const val GRADLE_INIT = "/root/.gradle/init.d/droiddeck-device.gradle" + + private fun setupWritesGradleInit(app: Context) = runCatching { + File(LinuxRuntime.rootDir(app), "$CHECKOUT/tools/agent/setup".removePrefix("/")).readText().contains(GRADLE_INIT.substringAfterLast('/')) + }.getOrDefault(false) /** dd-lab-build compiled this install's commit, so a Lab build compiles only what changed. */ private fun prepared(app: Context) = runCatching { diff --git a/tools/agent/AGENTS.md b/tools/agent/AGENTS.md index 20b1736bd7..d9b7deb09e 100644 --- a/tools/agent/AGENTS.md +++ b/tools/agent/AGENTS.md @@ -59,7 +59,9 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools process, and the conversation continues on the new build. - Python tests run from the repository root: `python3 -m unittest tools.tests.test_x`. Some fail on the device on `origin/main` too; run them on a worktree of `origin/main` before blaming a change. -- Gradle unit tests rarely run on the device. Leave them to CI and say so rather than retrying. +- Gradle runs on the device once the build tools are set up, but slowly: run the test classes that cover + your change, and leave full suites and native builds to CI. `PreviewRenderTest` cannot run here + (Robolectric's native graphics has no aarch64 Linux build). - If `git push` asks for credentials, run `gh auth setup-git` once. - Commits and pull requests you make are the user's own: no co-author line, AI credit or generated-by note. diff --git a/tools/agent/dd-gh-login b/tools/agent/dd-gh-login index f9b0b7734a..e02054ffc1 100755 --- a/tools/agent/dd-gh-login +++ b/tools/agent/dd-gh-login @@ -28,6 +28,19 @@ float_code() { [ "$result" = ok ] } +# git pushes through gh's sign-in and commits as the signed-in account, with its no-reply address. +configure_git() { + gh auth setup-git || return 1 + [ -n "$(git config --global user.name)" ] && [ -n "$(git config --global user.email)" ] && return 0 + local user id login name + user=$(gh api user -q '"\(.id) \(.login) \(.name // .login)"') || return 1 + read -r id login name <<<"$user" + [ -n "$id" ] && [ -n "$login" ] || return 1 + [ -n "$(git config --global user.name)" ] || git config --global user.name "${name:-$login}" + [ -n "$(git config --global user.email)" ] || git config --global user.email "$id+$login@users.noreply.github.com" +} +if [ "${1:-}" = --git ]; then configure_git; exit; fi + coproc GH { BROWSER=true gh auth login --hostname github.com --git-protocol https --web 2>&1; } gh_pid=$GH_PID exec {ghout}<&"${GH[0]}" {ghin}>&"${GH[1]}" @@ -48,5 +61,9 @@ while IFS= read -r line <&"$ghout"; do done wait "$gh_pid" status=$? +if [ $status = 0 ] && ! configure_git; then + echo "Signed in, but git could not be set up: run dd-gh-login --git" + status=1 +fi [ -n "$shown" ] && [ -n "$inbox" ] && [ -d "$inbox" ] && : > "$inbox/device-code" exit $status diff --git a/tools/agent/setup b/tools/agent/setup index e3b649db5e..45ad8144f7 100755 --- a/tools/agent/setup +++ b/tools/agent/setup @@ -16,6 +16,9 @@ command -v claude >/dev/null || [ -x "$HOME/.local/bin/claude" ] || mkdir -p "$HOME/.local/bin" for tool in dd-agent dd-lab-build dd-gh-login android-open; do install -m755 "$here/$tool" "$HOME/.local/bin/$tool"; done +if gh auth status >/dev/null 2>&1 && ! "$here/dd-gh-login" --git; then + echo "setup: git could not use the GitHub sign-in; run dd-gh-login --git" >&2 +fi # DroidDeck passes the live loopback adb port; a fixed one here would go stale whenever wireless debugging is toggled. sed -i 's|ADB_SERIAL=127.0.0.1:5555 |ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" |' "$HOME/.bashrc" 2>/dev/null || true grep -q 'droiddeck-agent-path' "$HOME/.bashrc" 2>/dev/null || @@ -63,6 +66,29 @@ if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then mv "$sdk/cmdline-tools/cmdline-tools" "$sdk/cmdline-tools/latest" fi export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64 +# Ubuntu's default JDK can be newer than the Gradle wrapper supports, so every shell and Gradle run +# here uses 17, the SDK above and the qemu-wrapped aapt2, not only dd-lab-build's. +sed -i '/^# droiddeck-agent-gradle$/,+1d' "$HOME/.bashrc" 2>/dev/null || true +printf '# droiddeck-agent-gradle\nexport JAVA_HOME=%s ANDROID_HOME="$HOME/android-sdk"\n' "$JAVA_HOME" >> "$HOME/.bashrc" +mkdir -p "$HOME/.gradle" +touch "$HOME/.gradle/gradle.properties" +# Gradle's own settings carry the SDK too, for shells that do not read ~/.bashrc. +for setting in "org.gradle.java.home=$JAVA_HOME" "android.aapt2FromMavenOverride=$HOME/aapt2/aapt2" "systemProp.android.home=$sdk"; do + sed -i "/^${setting%%=*}=/d" "$HOME/.gradle/gradle.properties" + echo "$setting" >> "$HOME/.gradle/gradle.properties" +done +# The NDK's compilers are x86-64 only, so DroidDeck's native code is left to CI, as dd-lab-build does, +# and Conscrypt ships no aarch64 Linux library for Robolectric to load. +mkdir -p "$HOME/.gradle/init.d" +cat > "$HOME/.gradle/init.d/droiddeck-device.gradle" <<'GRADLE' +settingsEvaluated { settings -> + if (settings.rootProject.name != 'DroidDeck') return + gradle.startParameter.excludedTaskNames += ':app:buildVkBridgeServer' + gradle.allprojects { + tasks.withType(org.gradle.api.tasks.testing.Test).configureEach { systemProperty 'robolectric.conscryptMode', 'OFF' } + } +} +GRADLE (set +o pipefail; yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null) "$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null From 3988f524806901d910c54504893df3aa4c083a77 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:53:59 -0500 Subject: [PATCH 4/8] feat(updates): lead with the installed build, one-row channel picker, clearer offer; agent images in chat (#3643) --- .../com/droiddeck/launcher/agent/AgentHost.kt | 4 +- .../com/droiddeck/launcher/ui/AgentEntries.kt | 2 +- .../droiddeck/launcher/ui/AgentMarkdown.kt | 100 +++++ .../com/droiddeck/launcher/ui/AgentPage.kt | 2 +- .../com/droiddeck/launcher/ui/UpdatesPage.kt | 348 ++++++++++++------ app/src/main/res/values/strings.xml | 16 + .../droiddeck/launcher/ui/AgentReplyTest.kt | 37 ++ 7 files changed, 395 insertions(+), 114 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index 566cfde355..87188e34d7 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -75,7 +75,9 @@ object AgentHost { "Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " + "Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " + "To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " + - "and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message." + "and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message. " + + "To show the user an image (a screenshot, a mockup, a chart), put ![what it shows](/absolute/path.png) on a line of its own: " + + "DroidDeck draws the file in the chat." val entries = mutableStateListOf() val queue = mutableStateListOf() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt index ff282615f5..800a829cb8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt @@ -78,7 +78,7 @@ internal fun AgentEntry( is Entry.Said -> { val reply = remember(entry.text) { choices(entry.text) } Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - if (reply.text.isNotBlank()) SelectionContainer { AgentMarkdown(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) } + if (reply.text.isNotBlank()) SelectionContainer { AgentReply(reply.text, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) } if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt index 0d85087f85..2a13c4119b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt @@ -37,6 +37,106 @@ import org.commonmark.ext.gfm.tables.TableRow import org.commonmark.node.AbstractVisitor import org.commonmark.node.CustomNode import org.commonmark.node.Node +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import coil.compose.AsyncImage +import com.droiddeck.launcher.runtime.LinuxRuntime +import java.io.File + +/** Part of an agent's reply: Markdown text, or an image the agent named on a line of its own. */ +internal sealed interface ReplyPart { + data class Prose(val text: String) : ReplyPart + data class Picture(val alt: String, val path: String) : ReplyPart +} + +private val PICTURE_LINE = Regex("""^\s*!\[([^\]]*)]\(\s*(?:<(?:file://)?(/[^>]*)>|(?:file://)?(/[^)<>]*?))\s*\)\s*$""") +private val FENCE = Regex("""^ {0,3}(`{3,}|~{3,})(.*)$""") + +/** Splits [text] at lines that hold only an image of a local absolute path, outside code fences. */ +internal fun replyParts(text: String): List { + val parts = mutableListOf() + val prose = StringBuilder() + fun flush() { + if (prose.isNotBlank()) parts += ReplyPart.Prose(prose.toString().trimEnd('\n')) + prose.clear() + } + var fence: String? = null + for (line in text.lines()) { + val marker = FENCE.matchEntire(line) + val picture = if (fence == null) PICTURE_LINE.matchEntire(line) else null + val open = fence + when { + picture != null -> { + flush() + val path = picture.groupValues[2].ifEmpty { picture.groupValues[3] } + parts += ReplyPart.Picture(picture.groupValues[1].trim(), path.trim()) + continue + } + marker == null -> Unit + open == null -> fence = marker.groupValues[1] + marker.groupValues[1].let { it[0] == open[0] && it.length >= open.length } && marker.groupValues[2].isBlank() -> fence = null + } + prose.append(line).append('\n') + } + flush() + return parts +} + +/** + * Where the app reads a file the agent named by its guest path: the app's own folders and shared + * storage are bound at the same paths in the guest, everything else lives in the rootfs. + */ +internal fun agentHostFile(context: Context, guestPath: String): File { + val app = context.applicationContext + val same = listOfNotNull(app.filesDir.path, app.cacheDir.path, LinuxRuntime.sharedStorage(app)?.path) + return if (same.any { guestPath == it || guestPath.startsWith("$it/") }) File(guestPath) + else File(LinuxRuntime.rootDir(app), guestPath.removePrefix("/")) +} + +/** An agent's reply, with the images it names shown in place. */ +@Composable +internal fun AgentReply(text: String, modifier: Modifier) { + val parts = remember(text) { replyParts(text) } + if (parts.size == 1 && parts[0] is ReplyPart.Prose) { + AgentMarkdown(text, modifier) + return + } + Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { + parts.forEach { part -> + when (part) { + is ReplyPart.Prose -> AgentMarkdown(part.text, Modifier) + is ReplyPart.Picture -> AgentPicture(part) + } + } + } +} + +@Composable +private fun AgentPicture(picture: ReplyPart.Picture) { + val context = LocalContext.current + val file = remember(picture.path) { agentHostFile(context, picture.path) } + var full by remember(picture.path) { mutableStateOf(false) } + if (!file.isFile) { + Text(stringResource(R.string.agent_image_missing, picture.alt.ifBlank { picture.path }), color = MaterialTheme.colorScheme.onSurfaceVariant) + return + } + AsyncImage( + model = file, contentDescription = picture.alt.ifBlank { file.name }, contentScale = ContentScale.Fit, + modifier = Modifier.widthIn(max = 560.dp).then(if (full) Modifier else Modifier.heightIn(max = 420.dp)) + .clip(Shape12).clickable { full = !full }, + ) +} @Composable internal fun AgentMarkdown(text: String, modifier: Modifier) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index 429db30258..439422fee7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -532,7 +532,7 @@ private fun AgentLive() { val pal = LocalPalette.current Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { if (AgentHost.liveThinking.isNotBlank()) AgentThought(AgentHost.liveThinking, live = true) - if (AgentHost.live.isNotBlank()) AgentMarkdown(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) + if (AgentHost.live.isNotBlank()) AgentReply(AgentHost.live, Modifier.widthIn(max = 760.dp).padding(horizontal = 4.dp)) val running = AgentHost.running() Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.padding(4.dp)) { CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = pal.primary) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt index 92478a6cd2..c454dfe2db 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -9,7 +9,6 @@ import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background -import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.hoverable @@ -25,6 +24,9 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size @@ -44,6 +46,7 @@ import androidx.compose.material.icons.outlined.Science import androidx.compose.material.icons.outlined.SwapHoriz import androidx.compose.material.icons.outlined.Sync import androidx.compose.material.icons.outlined.Verified +import androidx.compose.material.icons.outlined.WarningAmber import androidx.compose.material3.Icon import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.vector.ImageVector @@ -109,50 +112,37 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie val me = remember { AppUpdates.installed() } val colors = MaterialTheme.colorScheme Column(modifier = modifier) { - Row( - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp), - ) { - Text( - stringResource(R.string.upd_build, me.version, s.buildLabel), fontSize = 12.5.sp, color = colors.onSurfaceVariant, - maxLines = 1, modifier = Modifier.weight(1f) - .basicMarquee(iterations = Int.MAX_VALUE, initialDelayMillis = 700, velocity = 40.dp), - ) - val checked = u.catalog?.checkedAt?.takeIf { it > 0 } - if (!LocalNarrowPane.current) Text( - if (u.checking) stringResource(R.string.common_checking) else if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked), - fontSize = 13.sp, color = colors.onSurfaceVariant, - ) - val clipboard = LocalClipboardManager.current - val context = LocalContext.current - val details = buildDetails(me, s.buildLabel) - ToolIcon(Icons.Outlined.ContentCopy, stringResource(R.string.upd_copy_build)) { - clipboard.setText(AnnotatedString(details)) - android.widget.Toast.makeText(context, context.getString(R.string.upd_copied), android.widget.Toast.LENGTH_SHORT).show() - } - ToolIcon(Icons.Outlined.Refresh, stringResource(R.string.store_check_updates), busy = u.checking, enabled = !u.checking && u.stage == null, onClick = ua.onCheck) - } BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val stacked = LocalNarrowPane.current || maxWidth < 600.dp Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + SectionLabel(stringResource(R.string.upd_installed_label)) + InstalledCard(s, u, me) + CheckRow(u, ua) + SectionLabel(stringResource(R.string.upd_channel)) if (stacked) { + ChannelPicker(u, ua) + Box(Modifier.height(14.dp)) StatusPanel(s, u, ua, me) - Box(Modifier.height(18.dp)) - ChannelLabel() - ChannelPicker(u, ua, s.sessionRunning) } else { - ChannelLabel() Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) { - Box(Modifier.weight(1f)) { ChannelPicker(u, ua, s.sessionRunning) } + Box(Modifier.weight(1f)) { ChannelPicker(u, ua) } Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) } } } - Box(Modifier.padding(top = 18.dp)) { - ToggleRow( - host, "build-watermark", stringResource(R.string.setup_build_watermark), - stringResource(R.string.setup_build_watermark_hint), s.buildWatermark, - ) { a.onBuildWatermark() } - } + SectionLabel(stringResource(R.string.upd_testers), top = 22.dp) + ToggleRow( + host, "build-watermark", stringResource(R.string.setup_build_watermark), + stringResource(R.string.setup_build_watermark_hint), s.buildWatermark, + ) { a.onBuildWatermark() } + val context = LocalContext.current + val agentReady = com.droiddeck.launcher.agent.AgentHost.installed && + (com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context)) + LabBuilds(s.sessionRunning, onRebuild = if (agentReady) { info -> + com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label)) + context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java) + .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent") + .addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) + } else null) } } } @@ -169,6 +159,112 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie ) } +private val TEST_TINT = Color(0xFF9B6CFF) + +@Composable +private fun SectionLabel(text: String, top: androidx.compose.ui.unit.Dp = 4.dp) { + Text( + text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = top, bottom = 10.dp), + ) +} + +/** What is installed: which kind of build, its version and versionCode, and its commit, as the first thing on the page. */ +@Composable +private fun InstalledCard(s: FrontEndState, u: UpdatesState, me: AppUpdates.Installed) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val catalog = u.catalog + val lab = com.droiddeck.launcher.lab.LabOverlay.active + val basePr = if (me.pr > 0) me.pr else Regex("""\bpr(\d+)\b""").find(s.buildLabel)?.groupValues?.get(1)?.toIntOrNull() ?: 0 + val kind = when { + lab != null -> stringResource(R.string.upd_kind_lab) + me.pr > 0 -> stringResource(R.string.upd_kind_test) + catalog?.stable?.let { AppUpdates.isRunning(it, me) } == true -> stringResource(R.string.upd_stable) + catalog?.preview?.let { AppUpdates.isRunning(it, me) } == true -> stringResource(R.string.upd_preview) + else -> null + } + val tint = if (lab != null || me.pr > 0) TEST_TINT else pal.signal + val title = when { + lab != null -> lab.label + me.pr > 0 -> stringResource(R.string.upd_pr, me.pr) + else -> stringResource(R.string.upd_droiddeck_version, me.version) + } + val subtitle = when { + lab != null && basePr > 0 -> stringResource(R.string.upd_lab_on_pr, basePr) + lab != null -> stringResource(R.string.upd_lab_on_version, me.version) + me.pr > 0 -> catalog?.tests?.firstOrNull { it.pr == me.pr }?.title?.takeIf { it.isNotBlank() }?.let(::changeTitle) + else -> null + } + val built = lab?.built?.takeIf { it > 0 } ?: me.committedAt + val meta = listOfNotNull( + me.version.takeIf { lab != null || me.pr > 0 }, + stringResource(R.string.upd_version_code, me.versionCode), + me.commit.take(7).takeIf { it.length == 7 }, + built.takeIf { it > 0 }?.let { stringResource(R.string.upd_built_ago, ago(it).replaceFirstChar { c -> c.lowercase() }) }, + ).joinToString(" · ") + val clipboard = LocalClipboardManager.current + val context = LocalContext.current + val details = buildDetails(me, s.buildLabel) + Row( + verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(start = 18.dp, end = 12.dp, top = 14.dp, bottom = 16.dp), + ) { + Column(Modifier.weight(1f).padding(top = 2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + if (kind != null) Text( + kind.uppercase(), fontSize = 10.5.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.6.sp, color = tint, maxLines = 1, + modifier = Modifier.clip(CircleShape).background(tint.copy(alpha = 0.16f)).padding(horizontal = 8.dp, vertical = 3.dp), + ) + Text(title, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (subtitle != null) Text(subtitle, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, maxLines = 2, + overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 6.dp)) + Text(meta, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 4.dp)) + } + ToolIcon(Icons.Outlined.ContentCopy, stringResource(R.string.upd_copy_build)) { + clipboard.setText(AnnotatedString(details)) + android.widget.Toast.makeText(context, context.getString(R.string.upd_copied), android.widget.Toast.LENGTH_SHORT).show() + } + } +} + +@Composable +private fun CheckRow(u: UpdatesState, ua: UpdatesActions) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val enabled = !u.checking && u.stage == null + val checked = u.catalog?.checkedAt?.takeIf { it > 0 } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp, bottom = 14.dp), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.offset(x = (-6).dp).paneItem("updates:check").heightIn(min = 40.dp).clip(Shape12) + .background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .glideBorder(hot, Shape12, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.Button, onClick = ua.onCheck) + .controllerConfirm(enabled = enabled, onClick = ua.onCheck) + .padding(horizontal = 6.dp), + ) { + if (u.checking) androidx.compose.material3.CircularProgressIndicator(Modifier.size(16.dp), color = pal.signal, strokeWidth = 2.dp) + else Icon(Icons.Outlined.Refresh, contentDescription = null, tint = pal.signal.copy(alpha = if (enabled) 1f else 0.5f), modifier = Modifier.size(18.dp)) + Text( + if (u.checking) stringResource(R.string.common_checking) else stringResource(R.string.upd_check_now), + fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal.copy(alpha = if (enabled || u.checking) 1f else 0.5f), + ) + } + Box(Modifier.weight(1f)) + Text( + if (checked != null) stringResource(R.string.upd_checked, ago(checked).replaceFirstChar { it.lowercase() }) else stringResource(R.string.upd_not_checked), + fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, + ) + } +} + @Composable private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) { val colors = MaterialTheme.colorScheme @@ -201,12 +297,18 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) { Box(Modifier.size(7.dp).clip(CircleShape).background(look.tint)) Text(look.status, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = look.tint) - if (offered) Text(stringResource(R.string.upd_dot_ago, ago(release!!.publishedAt)), fontSize = 13.sp, color = colors.onSurfaceVariant) } Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp)) if (offered) { - ReleaseNotes(changeTitle(release!!.title.ifBlank { release.tag }), release.summary, release.tag) - ReleaseFacts(release) + val size = release!!.apk?.size?.takeIf { it > 0 }?.let { megabytes(it) } + Text( + listOfNotNull(stringResource(R.string.upd_released_ago, ago(release.publishedAt)), size).joinToString(" · "), + fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp), + ) + val older = (release.committedAt.takeIf { it > 0 } ?: release.publishedAt).let { it > 0 && me.committedAt > 0 && it < me.committedAt } + if (offer == Offer.SWITCH && older) OlderNote(me.committedAt) + val title = changeTitle(release.title.ifBlank { release.tag }) + ReleaseNotes(title.takeUnless { it == look.headline || (release.version != null && it.endsWith(release.version)) }, release.summary, release.tag) } if (release != null && u.follow.channel == Channel.TEST && catalog != null) { androidx.compose.runtime.LaunchedEffect(release.tag, release.commit, release.apk?.sha256) { ua.onSeen(release) } @@ -228,8 +330,10 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(6.dp).clip(CircleShape)) } offered && installBlock != null -> Unit - offer == Offer.UPDATE -> PrimaryButton(stringResource(R.string.upd_update_button, button), enabled = installable, main = true) { ua.onInstall(release!!) } - offer == Offer.SWITCH -> PrimaryButton(stringResource(R.string.upd_install_button, button), enabled = installable, main = true) { ua.onInstall(release!!) } + offer == Offer.UPDATE -> PrimaryButton(stringResource(R.string.upd_update_button, button), enabled = installable, main = true, fill = true, + modifier = Modifier.fillMaxWidth()) { ua.onInstall(release!!) } + offer == Offer.SWITCH -> PrimaryButton(stringResource(R.string.upd_switch_to_button, channelTitle(u.follow), button), enabled = installable, main = true, + fill = true, modifier = Modifier.fillMaxWidth()) { ua.onInstall(release!!) } offer == Offer.AHEAD && u.follow.channel == Channel.STABLE && installBlock == null -> SecondaryButton(stringResource(R.string.upd_install_anyway, release?.version.orEmpty()), enabled = installable) { ua.onInstall(release!!) } offer == Offer.GONE -> PrimaryButton(stringResource(R.string.upd_follow_preview), main = true) { ua.onFollow(Follow(Channel.NIGHTLY)) } @@ -238,25 +342,53 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m if (s.sessionRunning && (offered || offer == Offer.AHEAD)) { Text(stringResource(R.string.upd_stop_session), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp)) } + if (offered) ReleaseFacts(release!!) if (u.follow.channel == Channel.NIGHTLY) { PreviewHistory(catalog, me, s, u, ua) } } } +/** A switch that installs a build made before the installed one; Android keeps the app's data across it. */ @Composable -private fun ReleaseNotes(title: String, notes: String, key: String) { +private fun OlderNote(installedAt: Long) { + val context = LocalContext.current + val date = android.text.format.DateUtils.formatDateTime(context, installedAt, + android.text.format.DateUtils.FORMAT_SHOW_DATE or android.text.format.DateUtils.FORMAT_ABBREV_MONTH) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.padding(top = 12.dp).fillMaxWidth().clip(Shape12).background(AttentionAmber.copy(alpha = 0.12f)) + .padding(horizontal = 12.dp, vertical = 10.dp), + ) { + Icon(Icons.Outlined.WarningAmber, contentDescription = null, tint = AttentionAmber, modifier = Modifier.size(20.dp)) + Column { + Text(stringResource(R.string.upd_older_than_installed, date), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = AttentionAmber) + Text(stringResource(R.string.upd_data_stays), fontSize = 12.5.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +@Composable +private fun channelTitle(f: Follow) = when (f.channel) { + Channel.STABLE -> stringResource(R.string.upd_stable) + Channel.NIGHTLY -> stringResource(R.string.upd_preview) + Channel.TEST -> stringResource(R.string.upd_pr, f.pr) +} + +@Composable +private fun ReleaseNotes(title: String?, notes: String, key: String) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current var open by rememberSaveable(key) { mutableStateOf(false) } var cut by remember(key) { mutableStateOf(false) } - Text( + if (title != null) Text( title, fontSize = 15.sp, color = colors.onBackground, maxLines = if (open) Int.MAX_VALUE else 2, overflow = TextOverflow.Ellipsis, onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 10.dp), ) if (notes.isNotBlank()) Text( - notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else 1, overflow = TextOverflow.Ellipsis, - onTextLayout = { if (it.hasVisualOverflow) cut = true }, modifier = Modifier.padding(top = 4.dp), + notes, fontSize = 13.5.sp, color = colors.onSurfaceVariant, maxLines = if (open) Int.MAX_VALUE else if (title == null) 3 else 1, + overflow = TextOverflow.Ellipsis, onTextLayout = { if (it.hasVisualOverflow) cut = true }, + modifier = Modifier.padding(top = if (title == null) 10.dp else 4.dp), ) if (cut || open) { val src = remember { MutableInteractionSource() } @@ -287,47 +419,76 @@ private fun changeTitle(t: String): String = private fun megabytes(bytes: Long) = stringResource(R.string.upd_mb, ((bytes + 524_288) / 1_048_576).toInt()) @Composable -private fun ChannelLabel() { - Text( - stringResource(R.string.upd_channel), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, - color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp), - ) -} - -@Composable -private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, sessionRunning: Boolean) { +private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) { val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current val catalog = u.catalog val tests = catalog?.tests.orEmpty() val me = remember { AppUpdates.installed() } val ready = tests.count { AppUpdates.installable(it, me) } var showTests by rememberSaveable { mutableStateOf(false) } + val listing = (showTests || u.follow.channel == Channel.TEST) && tests.isNotEmpty() + val shown = if (listing || showTests) Channel.TEST else u.follow.channel Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - ChannelCard( - Icons.Outlined.Verified, stringResource(R.string.upd_stable), stringResource(R.string.upd_stable_hint), - catalog?.stable?.let { stringResource(R.string.upd_version_ago, it.version ?: it.tag, ago(it.publishedAt)) }, u.follow.channel == Channel.STABLE, - ) { ua.onFollow(Follow(Channel.STABLE)) } - ChannelCard( - Icons.Outlined.Bolt, stringResource(R.string.upd_preview), stringResource(R.string.upd_preview_hint), - catalog?.preview?.let { ago(it.publishedAt) }, u.follow.channel == Channel.NIGHTLY, - ) { ua.onFollow(Follow(Channel.NIGHTLY)) } - ChannelCard( - Icons.Outlined.Science, stringResource(R.string.upd_tests), stringResource(R.string.upd_tests_hint), - if (tests.isEmpty()) stringResource(R.string.upd_tests_none) else pluralStringResource(R.plurals.upd_tests_count, ready, ready), - u.follow.channel == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST, - ) { showTests = !showTests } - AnimatedVisibility((showTests || u.follow.channel == Channel.TEST) && tests.isNotEmpty(), enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) { + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.fillMaxWidth().clip(CircleShape).background(colors.surface).border(1.dp, pal.line, CircleShape) + .padding(4.dp).selectableGroup(), + ) { + ChannelSegment(Icons.Outlined.Verified, stringResource(R.string.upd_stable), null, shown == Channel.STABLE) { + showTests = false; ua.onFollow(Follow(Channel.STABLE)) + } + ChannelSegment(Icons.Outlined.Bolt, stringResource(R.string.upd_preview), null, shown == Channel.NIGHTLY) { + showTests = false; ua.onFollow(Follow(Channel.NIGHTLY)) + } + ChannelSegment( + Icons.Outlined.Science, stringResource(R.string.upd_tests_short), ready.takeIf { it > 0 }?.toString(), + shown == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST, + ) { showTests = !showTests } + } + val hint = when { + listing || u.follow.channel == Channel.TEST -> stringResource(R.string.upd_tests_hint) + u.follow.channel == Channel.NIGHTLY -> stringResource(R.string.upd_preview_hint) + + (catalog?.preview?.let { " · " + stringResource(R.string.upd_latest_ago, ago(it.publishedAt)) } ?: "") + else -> stringResource(R.string.upd_stable_hint) + + (catalog?.stable?.let { " · " + stringResource(R.string.upd_version_ago, it.version ?: it.tag, ago(it.publishedAt)) } ?: "") + } + Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp)) + if (tests.isEmpty() && catalog != null && showTests) Text(stringResource(R.string.upd_tests_none), fontSize = 12.5.sp, color = colors.onSurfaceVariant) + AnimatedVisibility(listing, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) { TestList(tests, me, u, ua) } - val context = androidx.compose.ui.platform.LocalContext.current - val agentReady = com.droiddeck.launcher.agent.AgentHost.installed && - (com.droiddeck.launcher.agent.AgentSetup.ready || com.droiddeck.launcher.agent.AgentSetup.completed(context)) - LabBuilds(sessionRunning, onRebuild = if (agentReady) { info -> - com.droiddeck.launcher.agent.AgentHost.send(context, context.getString(R.string.agent_rebuild_lab, info.label)) - context.startActivity(android.content.Intent(context, com.droiddeck.launcher.FrontEndActivity::class.java) - .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "agent") - .addFlags(android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP or android.content.Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)) - } else null) + } +} + +@Composable +private fun RowScope.ChannelSegment( + icon: ImageVector, title: String, badge: String?, selected: Boolean, + enabled: Boolean = true, onClick: () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally), + modifier = Modifier.weight(1f).heightIn(min = 44.dp).paneItem("channel:$title") + .clip(CircleShape) + .background(if (selected) pal.signal.copy(alpha = 0.16f) else if (hot) pal.signal.copy(alpha = 0.10f) else Color.Transparent) + .glideBorder(hot, CircleShape, pal.signal, if (selected) pal.signal else Color.Transparent) + .alpha(if (enabled) 1f else 0.5f) + .hoverable(src) + .selectable(selected = selected, interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) + .padding(horizontal = 6.dp), + ) { + Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(18.dp)) + Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = if (selected) colors.onBackground else colors.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + if (badge != null) Text( + badge, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant, + modifier = Modifier.clip(CircleShape).background(colors.surfaceVariant).padding(horizontal = 6.dp, vertical = 1.dp), + ) } } @@ -542,41 +703,6 @@ private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesS } } -@Composable -private fun ChannelCard( - icon: ImageVector, title: String, hint: String, latest: String?, selected: Boolean, - enabled: Boolean = true, onClick: () -> Unit, -) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - val src = remember { MutableInteractionSource() } - val hot = rememberHot(src) - val fill = if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(14.dp), - modifier = Modifier.fillMaxWidth().paneItem("channel:$title") - .clip(Shape14).background(colors.surface).background(fill).glideBorder(hot, Shape14, pal.signal, pal.line) - .alpha(if (enabled) 1f else 0.55f) - .hoverable(src) - .clickable(interactionSource = src, indication = null, enabled = enabled, role = Role.RadioButton, onClick = onClick) - .controllerConfirm(enabled = enabled, onClick = onClick) - .padding(horizontal = 14.dp, vertical = 10.dp), - ) { - Box(contentAlignment = Alignment.Center, modifier = Modifier.size(38.dp).clip(Shape12).background(if (selected) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)) { - Icon(icon, contentDescription = null, tint = if (selected) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) - } - Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text(title, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) - if (latest != null) Text(latest, fontSize = 12.sp, fontWeight = FontWeight.Medium, color = if (selected) pal.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) - } - RadioDot(selected) - } -} - @Composable private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.dp) { val pal = LocalPalette.current diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8e2be5a9f9..0c2bc79eaa 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1170,6 +1170,21 @@ PR #%1$d test build %1$d MB UPDATE CHANNEL + INSTALLED + FOR TESTERS + Test build + Lab build + On the PR #%1$d test build + On DroidDeck %1$s + DroidDeck %1$s + built %1$s + Check now + Tests + latest %1$s + Released %1$s + Switch to %1$s%2$s + Older than your installed build (%1$s) + Your games and settings stay. Stable Tested releases, for most people %1$s · %2$s @@ -4375,6 +4390,7 @@ Volume No audio files found in this soundtrack Launch unavailable + Image not found: %1$s No web browser is available to open this link. Grab Drop diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt new file mode 100644 index 0000000000..9069c6b292 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentReplyTest.kt @@ -0,0 +1,37 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertEquals +import org.junit.Test + +class AgentReplyTest { + @Test + fun anImageOnItsOwnLineSplitsTheReply() { + val parts = replyParts("Here it is:\n\n![Proposed Updates tab](/tmp/updates.png)\n\nWant changes?") + assertEquals( + listOf( + ReplyPart.Prose("Here it is:"), + ReplyPart.Picture("Proposed Updates tab", "/tmp/updates.png"), + ReplyPart.Prose("\nWant changes?"), + ), + parts, + ) + } + + @Test + fun fileUrlsAndAngleBracketsNameTheSamePath() { + assertEquals(listOf(ReplyPart.Picture("", "/root/a b.png")), replyParts("![]()")) + assertEquals(listOf(ReplyPart.Picture("chart", "/root/chart (1).png")), replyParts("![chart]()")) + } + + @Test + fun imagesInCodeInlineOrRemoteStayText() { + val fenced = "```\n![x](/tmp/x.png)\n```" + assertEquals(listOf(ReplyPart.Prose(fenced)), replyParts(fenced)) + val inline = "See ![x](/tmp/x.png) here" + assertEquals(listOf(ReplyPart.Prose(inline)), replyParts(inline)) + val nested = "````\n```\n![x](/tmp/x.png)\n```python\n![y](/tmp/y.png)\n````" + assertEquals(listOf(ReplyPart.Prose(nested)), replyParts(nested)) + val remote = "![x](https://example.com/x.png)" + assertEquals(listOf(ReplyPart.Prose(remote)), replyParts(remote)) + } +} From 312069603abe82b19c175baeac89bd79f499d99a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:54:27 -0500 Subject: [PATCH 5/8] Put the VR session page in More by default (#3655) --- .../launcher/ui/SessionDrawerPage.kt | 12 +++++++--- .../launcher/ui/SessionDrawerPageTest.kt | 23 ++++++++++++++----- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index 3520944963..f9e8924c8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -22,7 +22,12 @@ internal enum class SessionDrawerPage(val firstControl: String) { } internal object DrawerPages { - var order by mutableStateOf(SessionDrawerPage.entries.toList()) + private val defaultOrder = SessionDrawerPage.entries.toMutableList().apply { + remove(SessionDrawerPage.VR) + add(indexOf(SessionDrawerPage.MORE) + 1, SessionDrawerPage.VR) + }.toList() + + var order by mutableStateOf(defaultOrder) private set var hidden by mutableStateOf(emptySet()) private set @@ -39,6 +44,7 @@ internal object DrawerPages { } fun arrange(saved: List): List { + if (saved.isEmpty()) return defaultOrder val all = SessionDrawerPage.entries val out = saved.mapNotNull { name -> all.firstOrNull { it.name == name } }.distinct().toMutableList() for (page in all.filterNot { it in out }) { @@ -62,14 +68,14 @@ internal object DrawerPages { } fun reset(context: Context) { - order = SessionDrawerPage.entries.toList() + order = defaultOrder hidden = emptySet() if (DevPreview.drawer != null) return SessionPrefs.setDrawerPageOrder(context, order.map { it.name }) SessionPrefs.setDrawerPageHidden(context, emptySet()) } - fun isDefault() = order == SessionDrawerPage.entries.toList() && hidden.isEmpty() + fun isDefault() = order == defaultOrder && hidden.isEmpty() } internal fun offeredDrawerPages( diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index e8097745bc..ad54fdd9eb 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -4,20 +4,22 @@ import org.junit.Assert.* import org.junit.Test class SessionDrawerPageTest { - @Test fun navigationRunsControllerPerformanceDisplayEffectsGameVrSession() { + @Test fun navigationRunsControllerPerformanceFrameGenDisplayEffectsGameSessionMore() { val pages = sessionDrawerPages(hasAgent = false) + assertEquals(DrawerPages.arrange(emptyList()).strip(), pages.strip()) assertEquals( listOf(SessionDrawerPage.CONTROLLER, SessionDrawerPage.HUD, SessionDrawerPage.FRAMEGEN, SessionDrawerPage.DISPLAY, SessionDrawerPage.EFFECTS, SessionDrawerPage.GAMES, - SessionDrawerPage.VR, SessionDrawerPage.SESSION, SessionDrawerPage.MORE), + SessionDrawerPage.SESSION, SessionDrawerPage.MORE), pages.strip(), ) - assertEquals(SessionDrawerPage.MORE, pages.step(SessionDrawerPage.CONTROLLER, -1)) + assertEquals(SessionDrawerPage.MORE, pages.strip().step(SessionDrawerPage.CONTROLLER, -1)) } - @Test fun achievementsAndTheAgentStartInsideMore() { + @Test fun vrAchievementsAndTheAgentStartInsideMore() { val pages = sessionDrawerPages(hasAchievements = true, hasAgent = true) - assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.AGENT), pages.inMore()) + assertEquals(listOf(SessionDrawerPage.VR, SessionDrawerPage.ACHIEVEMENTS, SessionDrawerPage.AGENT), pages.inMore()) + assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.VR)) assertEquals(SessionDrawerPage.MORE, pages.tabFor(SessionDrawerPage.ACHIEVEMENTS)) assertEquals(SessionDrawerPage.GAMES, pages.tabFor(SessionDrawerPage.GAMES)) val strip = pages.strip() @@ -27,7 +29,7 @@ class SessionDrawerPageTest { @Test fun achievementsAreOfferedOnlyForAGameThatHasThem() { assertFalse(SessionDrawerPage.ACHIEVEMENTS in sessionDrawerPages(hasAchievements = false, hasAgent = false)) assertFalse(SessionDrawerPage.AGENT in sessionDrawerPages(hasAgent = false)) - assertTrue(sessionDrawerPages(hasAgent = false).inMore().isEmpty()) + assertEquals(listOf(SessionDrawerPage.VR), sessionDrawerPages(hasAgent = false).inMore()) } @Test fun anOlderSavedOrderKeepsItsPagesAndGetsAMoreTabAfterSession() { @@ -37,6 +39,15 @@ class SessionDrawerPageTest { assertEquals(SessionDrawerPage.MORE, out[out.indexOf(SessionDrawerPage.SESSION) + 1]) assertEquals(listOf(SessionDrawerPage.ACHIEVEMENTS), out.inMore()) assertTrue(SessionDrawerPage.AGENT in out.strip()) + assertTrue(SessionDrawerPage.VR in out.strip()) + } + + @Test fun aSavedLayoutCanKeepVrOnTheTabStrip() { + val saved = listOf("CONTROLLER", "HUD", "VR", "FRAMEGEN", "DISPLAY", "EFFECTS", + "GAMES", "SESSION", "MORE", "ACHIEVEMENTS", "AGENT") + val out = DrawerPages.arrange(saved) + assertEquals(saved, out.map { it.name }) + assertEquals(SessionDrawerPage.VR, out.tabFor(SessionDrawerPage.VR)) } @Test fun sessionCanBeKeptInsideMore() { From d8bb4a8751f1043b8589d5a54d90e82b3aeca600 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Thu, 3 Dec 2026 16:26:00 -0500 Subject: [PATCH 6/8] fix(ea): signing out forgets the EA web session so another account can sign in (#3652) EA keeps its sign-in session in cookies scoped under the sign-in paths (/connect on accounts.ea.com, /p on signin.ea.com). Sign-out and the fresh sign-in only listed and expired cookies at /, so the old session survived and EA signed the previous account straight back in. Cookie expiry now also covers every path prefix of each sign-in URL, and the EA sign-in URLs name those paths. Closes #2457 --- .../com/droiddeck/launcher/stores/WebCookies.kt | 7 ++++++- .../com/droiddeck/launcher/stores/ea/EaBackend.kt | 12 +++++++----- .../droiddeck/launcher/stores/WebCookiesTest.kt | 15 +++++++++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt b/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt index b44a274c50..6077ebe327 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt @@ -14,9 +14,14 @@ internal object WebCookies { } } + fun scopes(url: String, paths: List): List { + val segments = runCatching { java.net.URI(url).path }.getOrNull().orEmpty().split('/').filter { it.isNotEmpty() } + return (paths + segments.indices.map { i -> "/" + segments.take(i + 1).joinToString("/") }).distinct() + } + fun expire(urls: List, domain: String, paths: List, done: (Int) -> Unit) { val cookies = CookieManager.getInstance() - val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, paths, Uri.parse(url).host).map { url to it } } + val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, scopes(url, paths), Uri.parse(url).host).map { url to it } } if (lines.isEmpty()) { done(0) return diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt index bd8d5c1212..3da83576bb 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaBackend.kt @@ -44,7 +44,7 @@ object EaBackend : StoreBackend { signOuts.incrementAndGet() StoresState.post { StoresState.shelves.remove(store) } EaUpdates.available.clear() - runCatching { WebCookies.expire(EaLogin.SIGN_IN_URLS, ".ea.com", listOf("/")) {} } + EaLogin.forget {} } override fun syncLibrary(context: Context, force: Boolean) { @@ -100,9 +100,7 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge override fun isRedirect(url: String): Boolean = url.startsWith("qrc:", ignoreCase = true) - override fun forgetSignIn(done: () -> Unit) { - runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() } - } + override fun forgetSignIn(done: () -> Unit) = forget(done) override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { val code = EaAuth.redirectValue(url, "code") ?: return activity.getString(R.string.stores_login_error_verification) @@ -116,7 +114,11 @@ internal class EaLogin(private val pending: EaAuth.Pending, override val userAge } companion object { - val SIGN_IN_URLS = listOf("https://accounts.ea.com", "https://signin.ea.com", "https://www.ea.com") + val SIGN_IN_URLS = listOf(EaAuth.AUTH_URL, "https://signin.ea.com/p/juno/login", "https://www.ea.com") + + fun forget(done: () -> Unit) { + runCatching { WebCookies.expire(SIGN_IN_URLS, ".ea.com", listOf("/")) { done() } }.onFailure { done() } + } } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt index ec8c63d100..b0c62a41e6 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt @@ -15,4 +15,19 @@ class WebCookiesTest { assertTrue(lines.none { it.startsWith("galaxy-login-al=c") }) assertEquals(emptyList(), WebCookies.expired(null, GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com")) } + + @Test fun cookiesScopedUnderTheSignInPathAreExpiredAtThatPath() { + val paths = WebCookies.scopes("https://accounts.ea.com/connect/auth", listOf("/")) + assertEquals(listOf("/", "/connect", "/connect/auth"), paths) + val lines = WebCookies.expired("sid=a; remid=b", ".ea.com", paths, "accounts.ea.com") + assertTrue(lines.contains("sid=; Max-Age=0; Path=/connect; Secure")) + assertTrue(lines.contains("remid=; Max-Age=0; Path=/connect; Secure; Domain=accounts.ea.com")) + assertEquals(listOf("/p", "/", "/p/juno", "/p/juno/login"), WebCookies.scopes("https://signin.ea.com/p/juno/login", listOf("/p", "/"))) + } + + @Test fun rootSignInUrlsKeepOnlyTheGivenPaths() { + assertEquals(listOf("/"), WebCookies.scopes("https://login.gog.com/", listOf("/"))) + assertEquals(listOf("/"), WebCookies.scopes("https://connect.ubisoft.com", listOf("/"))) + assertEquals(listOf("/", "/id", "/id/login"), WebCookies.scopes("https://www.epicgames.com/id/login", listOf("/", "/id"))) + } } From 68af03ac746ddaa8e47f9189f7a3c08d398b4e96 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:29:52 -0500 Subject: [PATCH 7/8] Negotiate verified producer fences for Steam game frames (#3651) Use the verified Gamescope component and preserve the safe copy fallback. Direct game frames remains experimental and off by default. --- app/src/main/cpp/waylandcomp/CMakeLists.txt | 5 + .../droiddeck-frame-acquire-v1-protocol.c | 35 + ...oiddeck-frame-acquire-v1-server-protocol.h | 128 ++++ .../protocols/droiddeck-frame-acquire-v1.xml | 45 ++ .../main/cpp/waylandcomp/src/ahb_swapchain.c | 55 +- .../main/cpp/waylandcomp/src/ahb_swapchain.h | 2 + app/src/main/cpp/waylandcomp/src/compositor.c | 239 +++++- .../main/cpp/waylandcomp/src/frame_acquire.h | 39 + .../cpp/waylandcomp/src/frame_worker_peer.h | 81 ++ .../cpp/waylandcomp/src/waylandcomp_jni.c | 39 + .../droiddeck/launcher/FrontEndActivity.kt | 11 + .../com/droiddeck/launcher/SessionActivity.kt | 1 + .../runtime/FrameAcquireWorkerProbe.kt | 271 +++++++ .../launcher/runtime/GuestWorkers.kt | 40 +- .../launcher/session/SessionPrefs.kt | 7 + .../launcher/session/SessionService.kt | 44 +- .../launcher/session/SettingsReset.kt | 2 +- .../launcher/ui/ModeSettingsDialog.kt | 7 + .../launcher/wayland/WaylandCompositor.java | 4 + app/src/main/res/values/strings.xml | 2 + .../runtime/FrameAcquireWorkerProbeTest.kt | 117 +++ docs/development/producer-acquire-fences.md | 19 + tools/gamescope/PATCHES.md | 12 + tools/gamescope/build-in-arch.sh | 8 + ...ard-verified-producer-acquire-fences.patch | 693 ++++++++++++++++++ tools/gamescope/release.env | 4 +- tools/gamescope/tests/producer-acquire.cpp | 36 + .../overlay/usr/local/bin/droiddeck-game-env | 2 +- tools/tests/frame_worker_peer_live_test.c | 51 ++ tools/tests/frame_worker_peer_test.c | 48 ++ tools/tests/subsurface_release_harness.c | 2 + .../test_commit_waits_for_client_writes.py | 7 + tools/tests/test_frame_acquire_peer_gate.py | 81 ++ tools/tests/test_frame_acquire_protocol.py | 166 +++++ tools/tests/test_game_environment.py | 10 + tools/tests/test_zero_copy_acquire_fence.py | 32 +- tools/tests/vk_dmabuf_quarantine_test.c | 2 + 37 files changed, 2305 insertions(+), 42 deletions(-) create mode 100644 app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c create mode 100644 app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h create mode 100644 app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml create mode 100644 app/src/main/cpp/waylandcomp/src/frame_acquire.h create mode 100644 app/src/main/cpp/waylandcomp/src/frame_worker_peer.h create mode 100644 app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt create mode 100644 docs/development/producer-acquire-fences.md create mode 100644 tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch create mode 100644 tools/gamescope/tests/producer-acquire.cpp create mode 100644 tools/tests/frame_worker_peer_live_test.c create mode 100644 tools/tests/frame_worker_peer_test.c create mode 100644 tools/tests/test_frame_acquire_peer_gate.py create mode 100644 tools/tests/test_frame_acquire_protocol.py diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index 5bdc1e8385..ca528afb88 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -42,6 +42,11 @@ add_library(droiddeckwayland SHARED src/hudframes.c src/hudframes_jni.c ) +option(DROIDDECK_FRAME_ACQUIRE_PROBE "Build opt-in signaled producer acquire protocol support" ON) +if (DROIDDECK_FRAME_ACQUIRE_PROBE) + target_sources(droiddeckwayland PRIVATE generated/droiddeck-frame-acquire-v1-protocol.c) + target_compile_definitions(droiddeckwayland PRIVATE DROIDDECK_FRAME_ACQUIRE_PROBE=1) +endif() target_compile_options(droiddeckwayland PRIVATE $<$:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>) target_include_directories(droiddeckwayland PRIVATE diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c new file mode 100644 index 0000000000..3d32474f56 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-protocol.c @@ -0,0 +1,35 @@ +/* Generated by wayland-scanner 1.22.0 */ + +#include +#include +#include "wayland-util.h" + +#ifndef __has_attribute +# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */ +#endif + +#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4) +#define WL_PRIVATE __attribute__ ((visibility("hidden"))) +#else +#define WL_PRIVATE +#endif + +extern const struct wl_interface wl_buffer_interface; +extern const struct wl_interface wl_surface_interface; + +static const struct wl_interface *droiddeck_frame_acquire_v1_types[] = { + &wl_surface_interface, + &wl_buffer_interface, + NULL, +}; + +static const struct wl_message droiddeck_frame_acquire_v1_requests[] = { + { "destroy", "", droiddeck_frame_acquire_v1_types + 0 }, + { "set_acquire_fence", "ooh", droiddeck_frame_acquire_v1_types + 0 }, +}; + +WL_PRIVATE const struct wl_interface droiddeck_frame_acquire_v1_interface = { + "droiddeck_frame_acquire_v1", 1, + 2, droiddeck_frame_acquire_v1_requests, + 0, NULL, +}; diff --git a/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h new file mode 100644 index 0000000000..18f9466487 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-frame-acquire-v1-server-protocol.h @@ -0,0 +1,128 @@ +/* Generated by wayland-scanner 1.22.0 */ + +#ifndef DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H +#define DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H + +#include +#include +#include "wayland-server.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct wl_client; +struct wl_resource; + +/** + * @page page_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 protocol + * @section page_ifaces_droiddeck_frame_acquire_v1 Interfaces + * - @subpage page_iface_droiddeck_frame_acquire_v1 - DroidDeck producer write completion for a single Wayland attachment + */ +struct droiddeck_frame_acquire_v1; +struct wl_buffer; +struct wl_surface; + +#ifndef DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE +#define DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE +/** + * @page page_iface_droiddeck_frame_acquire_v1 droiddeck_frame_acquire_v1 + * @section page_iface_droiddeck_frame_acquire_v1_desc Description + * + * Optional explicit acquire sideband independent of DRM syncobj and buffer + * allocation. Binding does not opt the client out of ordinary wl_buffer + * release or existing synchronization protocols. The server advertises it + * only when it implements all semantics for the selected display path. + * @section page_iface_droiddeck_frame_acquire_v1_api API + * See @ref iface_droiddeck_frame_acquire_v1. + */ +/** + * @defgroup iface_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 interface + * + * Optional explicit acquire sideband independent of DRM syncobj and buffer + * allocation. Binding does not opt the client out of ordinary wl_buffer + * release or existing synchronization protocols. The server advertises it + * only when it implements all semantics for the selected display path. + */ +extern const struct wl_interface droiddeck_frame_acquire_v1_interface; +#endif + +#ifndef DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM +#define DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM +enum droiddeck_frame_acquire_v1_error { + /** + * not the same client's pending DMA-BUF attachment + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT = 0, + /** + * that attachment already has an acquire fence + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE = 1, + /** + * not a real successfully signaled Linux sync_file + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE = 2, + /** + * not the paired test peer + */ + DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER = 3, +}; +#endif /* DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM */ + +/** + * @ingroup iface_droiddeck_frame_acquire_v1 + * @struct droiddeck_frame_acquire_v1_interface + */ +struct droiddeck_frame_acquire_v1_interface { + /** + */ + void (*destroy)(struct wl_client *client, + struct wl_resource *resource); + /** + * set a one-shot kernel sync_file for the pending attachment + * + * After wl_surface.attach of a non-null buffer, and before its + * next wl_surface.commit, send the producer's final writer fence + * for that exact attachment. This outer probe requires that fence + * to have already successfully signaled. The fence must be a real + * Linux sync_file, not a dma-buf, eventfd, or Vulkan OPAQUE_FD. + * The server consumes its received descriptor once for that + * attachment; the caller closes its local FD after marshalling. + * + * The receiver validates the matching pending surface and buffer + * and validates the descriptor. A duplicate, invalid, pending or + * mismatched request is a protocol error; it is never downgraded + * to implicit sync. Another attach (even the same wl_buffer), + * detach, surface/resource loss or supersession makes the old + * proof inapplicable. Metadata-only commits may amend + * receiver-side still-pending state but cannot introduce or re-use + * a fence themselves. If no request was made, the receiver keeps + * its established safe path. If a valid fence has been accepted + * and later the layer is ineligible, the buffer must not be + * copied/read before that fence is satisfied or imported as the + * source dependency. Transport never implies readiness on missed + * deadlines and never changes release/retirement requirements. + * @param fence producer's native acquire sync_file + */ + void (*set_acquire_fence)(struct wl_client *client, + struct wl_resource *resource, + struct wl_resource *surface, + struct wl_resource *buffer, + int32_t fence); +}; + + +/** + * @ingroup iface_droiddeck_frame_acquire_v1 + */ +#define DROIDDECK_FRAME_ACQUIRE_V1_DESTROY_SINCE_VERSION 1 +/** + * @ingroup iface_droiddeck_frame_acquire_v1 + */ +#define DROIDDECK_FRAME_ACQUIRE_V1_SET_ACQUIRE_FENCE_SINCE_VERSION 1 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml new file mode 100644 index 0000000000..ae4c26535b --- /dev/null +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-frame-acquire-v1.xml @@ -0,0 +1,45 @@ + + + + + Optional explicit acquire sideband independent of DRM syncobj and buffer + allocation. Binding does not opt the client out of ordinary wl_buffer + release or existing synchronization protocols. The server advertises it + only when it implements all semantics for the selected display path and + only to the test fixture's app-authorized Gamescope worker. + + + + + + + + + + + After wl_surface.attach of a non-null buffer, and before its next + wl_surface.commit, send the producer's final writer fence for that + exact attachment. This outer probe requires that fence to have already + successfully signaled. The fence must be a real Linux sync_file, not a + dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received + descriptor once for that attachment; the caller closes its local FD + after marshalling. + + The receiver validates the matching pending surface and buffer and + validates the descriptor. A duplicate, invalid, pending or mismatched + request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same + wl_buffer), detach, surface/resource loss or supersession makes the + old proof inapplicable. Metadata-only commits may amend receiver-side + still-pending state but cannot introduce or re-use a fence themselves. + If no request was made, the receiver keeps its established safe path. + If a valid fence has been accepted and later the layer is ineligible, + the buffer must not be copied/read before that fence is satisfied or + imported as the source dependency. Transport never implies readiness + on missed deadlines and never changes release/retirement requirements. + + + + + + + diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c index aaf12e5814..26618c67f6 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.c @@ -54,6 +54,7 @@ static struct wl_list g_clients; static uint64_t g_next_id = 1; static struct wl_event_loop *g_loop; static unsigned g_stat_zero_copy; +static unsigned g_stat_producer_fence; static int g_export_failed_logged, g_import_failed_logged; static int g_advertised; static int g_mode_sent = -1; @@ -201,31 +202,47 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_ struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL; if (!ab) return -1; int dmabuf_fd = droiddeck_dmabuf_fd(b); - int acquire = -1; - struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1}; - if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) { - acquire = exp.fd; - } else { - if (!g_export_failed_logged) { - g_export_failed_logged = 1; - droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s", - dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd", - draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU"); + int acquire = droiddeck_surface_dup_acquire(s, b); + if (acquire == -2) return -1; +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + const int explicit_acquire = acquire >= 0; +#endif + if (acquire < 0) { + struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1}; + if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) { + acquire = exp.fd; + } else { + if (!g_export_failed_logged) { + g_export_failed_logged = 1; + droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s", + dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd", + draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU"); + } + if (dmabuf_fd >= 0) { + struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN}; + int r; + do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); + } + if (draw) return -1; } - if (dmabuf_fd >= 0) { - struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN}; - int r; - do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR); - } - if (draw) return -1; } int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw, s ? droiddeck_surface_color(s) : NULL, ab->format); if (r < 0) return -1; if (r == 1) return 0; +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + static int explicit_logged; + if (explicit_acquire && !explicit_logged) { + explicit_logged = 1; + droiddeck_log("layer", "probe: SurfaceControl accepted a verified producer acquire fence"); + } +#endif if (!ab->on_layer) { ab->on_layer = 1; g_stat_zero_copy++; +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + if (explicit_acquire) g_stat_producer_fence++; +#endif g_last_zero_copy_ns = now_ns(); } if (s && g_announced != s) { @@ -265,6 +282,12 @@ unsigned ahb_swapchain_stats_take(void) { return n; } +unsigned ahb_swapchain_producer_fence_stats_take(void) { + unsigned n = g_stat_producer_fence; + g_stat_producer_fence = 0; + return n; +} + int ahb_swapchain_advertised(void) { return g_advertised; } uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) { diff --git a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h index 9002e6fc0a..95f1cd1418 100644 --- a/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h +++ b/app/src/main/cpp/waylandcomp/src/ahb_swapchain.h @@ -20,7 +20,9 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_ int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced); void ahb_swapchain_surface_gone(struct surface *s); unsigned ahb_swapchain_stats_take(void); +unsigned ahb_swapchain_producer_fence_stats_take(void); int ahb_swapchain_advertised(void); +int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b); uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b); void ahb_swapchain_layer_released(void *token, int release_fd); diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 9339617e27..112f731f5a 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -24,6 +24,14 @@ #include "linux-dmabuf-v1-server-protocol.h" #include "sc_layer.h" #include "ahb_swapchain.h" +#include "frame_acquire.h" +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE +#include "droiddeck-frame-acquire-v1-server-protocol.h" +#include +#include +#include +#include "frame_worker_peer.h" +#endif #include "display_buffers.h" #include "viewporter-server-protocol.h" #include "droiddeck-desktop-v1-server-protocol.h" @@ -211,6 +219,7 @@ struct surface { struct wl_list link; struct wl_resource *pending_buffer; + struct dd_frame_acquire pending_frame_acquire, frame_acquire; struct wl_listener pending_buffer_destroy; int pending_attach; int pending_src_set, pending_dst_set; @@ -827,6 +836,7 @@ static void unmap_toplevel(struct surface *s) { } static void drop_dmabuf(struct surface *s, int paced) { + dd_frame_acquire_clear(&s->frame_acquire); if (s->dmabuf) { wl_list_remove(&s->dmabuf_destroy.link); if (buffer_shown_elsewhere(s->dmabuf, s)) { @@ -842,18 +852,21 @@ static void drop_dmabuf(struct surface *s, int paced) { static void on_dmabuf_destroyed(struct wl_listener *l, void *data) { struct surface *s = wl_container_of(l, s, dmabuf_destroy); + dd_frame_acquire_clear(&s->frame_acquire); wl_list_remove(&s->dmabuf_destroy.link); s->dmabuf = NULL; } static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) { struct surface *s = wl_container_of(l, s, pending_buffer_destroy); + dd_frame_acquire_clear(&s->pending_frame_acquire); wl_list_remove(&s->pending_buffer_destroy.link); wl_list_init(&s->pending_buffer_destroy.link); s->pending_buffer = NULL; } struct surface_state { + struct dd_frame_acquire frame_acquire; struct wl_resource *buffer; struct wl_listener buffer_destroy; int attach; @@ -866,6 +879,7 @@ struct surface_state { static void on_state_buffer_destroyed(struct wl_listener *l, void *data) { struct surface_state *st = wl_container_of(l, st, buffer_destroy); + dd_frame_acquire_clear(&st->frame_acquire); wl_list_remove(&st->buffer_destroy.link); wl_list_init(&st->buffer_destroy.link); st->buffer = NULL; @@ -874,6 +888,8 @@ static void on_state_buffer_destroyed(struct wl_listener *l, void *data) { static void surface_state_take(struct surface *s, struct surface_state *st) { st->attach = s->pending_attach; + st->frame_acquire = s->pending_frame_acquire; + s->pending_frame_acquire.fd_plus_one = 0; st->buffer = s->pending_buffer; wl_list_init(&st->buffer_destroy.link); if (st->buffer) { @@ -1186,6 +1202,7 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r, if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link); wl_list_init(&s->pending_buffer_destroy.link); s->pending_buffer = buffer; + dd_frame_acquire_clear(&s->pending_frame_acquire); s->pending_attach = 1; if (buffer) { s->pending_buffer_destroy.notify = on_pending_buffer_destroyed; @@ -1451,6 +1468,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) { surface_drop_idle(s); buf_trace_attach(buffer); + dd_frame_acquire_clear(&s->frame_acquire); if (s->role == ROLE_CURSOR) { if (!buffer) { cursor_publish_hidden(); @@ -1462,6 +1480,8 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) { if (buffer) surface_hold_idle(s, buffer); } else if (db) { take_dmabuf(s, db, buffer); + s->frame_acquire = st->frame_acquire; + st->frame_acquire.fd_plus_one = 0; } else if (shm) { drop_dmabuf(s, 1); take_shm(s, shm, buffer); @@ -1474,6 +1494,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) { if (buffer) send_buffer_release(buffer); } } + dd_frame_acquire_clear(&st->frame_acquire); pending_releases_apply(s); wl_list_for_each(child, &s->children, child_link) { @@ -1538,6 +1559,7 @@ static void settle_unwaited(void) { } static void surface_state_discard(struct surface_state *st) { + dd_frame_acquire_clear(&st->frame_acquire); struct wl_resource *cb, *tmp; wl_list_remove(&st->buffer_destroy.link); wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb); @@ -1549,6 +1571,8 @@ static void surface_state_merge(struct surface_state *older, struct surface_stat if (older->attach && !newer->attach) { newer->attach = 1; newer->buffer = older->buffer; + newer->frame_acquire = older->frame_acquire; + older->frame_acquire.fd_plus_one = 0; wl_list_remove(&older->buffer_destroy.link); wl_list_init(&older->buffer_destroy.link); if (newer->buffer) { @@ -1700,6 +1724,210 @@ static const struct wl_surface_interface surface_impl = { .offset = surface_offset, }; +int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) { + return s && s->dmabuf && s->dmabuf_buf == b ? dd_frame_acquire_dup(&s->frame_acquire) : -1; +} + +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE +// Private signed fixture: only the app-owned worker decision may issue a grant. +static pthread_mutex_t frame_worker_lock = PTHREAD_MUTEX_INITIALIZER; +static char frame_worker_file[PATH_MAX]; +static struct dd_worker_grant frame_worker_grant; +static int frame_worker_pidfd = -1; +static bool frame_worker_map_reported; + +static enum dd_worker_stat_result frame_worker_starttime(pid_t pid, uint64_t *out) { + char proc[64], line[4096]; + snprintf(proc, sizeof(proc), "/proc/%d/stat", pid); + FILE *f = fopen(proc, "re"); + if (!f) return dd_worker_open_failure(errno); + // Proc writes one bounded line; truncation is a read failure, not invisibility. + bool read = fgets(line, sizeof(line), f) != NULL && strchr(line, '\n') != NULL; + fclose(f); + return read ? dd_worker_parse_start(line, out) : DD_WORKER_STAT_READ; +} + +void droiddeck_frame_worker_revoke(int owner, int pid) { + pthread_mutex_lock(&frame_worker_lock); + if (frame_worker_grant.owner == (uint32_t)owner && + (!pid || frame_worker_grant.pid == (uint32_t)pid)) { + if (frame_worker_pidfd >= 0) close(frame_worker_pidfd); + frame_worker_pidfd = -1; + frame_worker_grant = (struct dd_worker_grant){0}; + } + pthread_mutex_unlock(&frame_worker_lock); +} + +int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path, + uint64_t expected_dev, uint64_t expected_ino, uint64_t receipt) { + struct stat st; + if (owner <= 0 || pid <= 1 || !receipt || !path || + strlen(path) >= sizeof(frame_worker_file) || lstat(path, &st) < 0 || !S_ISREG(st.st_mode) || + (uint64_t)st.st_dev != expected_dev || (uint64_t)st.st_ino != expected_ino || + st.st_uid != getuid()) { + droiddeck_log("probe", "worker_admission=NATIVE_FILE"); + return 0; + } + int pidfd = syscall(__NR_pidfd_open, pid, 0); + if (pidfd < 0) { + droiddeck_log("probe", "worker_admission=NATIVE_PIDFD"); + return 0; // No fallback to a recyclable PID. + } + struct pollfd alive = {.fd = pidfd, .events = POLLIN}; + uint64_t raw_start = 0; + enum dd_worker_stat_result stat = frame_worker_starttime(pid, &raw_start); + switch (stat) { + case DD_WORKER_STAT_OK: + if (raw_start != receipt) droiddeck_log("probe", "worker_admission=NATIVE_STAT_MISMATCH"); + break; + case DD_WORKER_STAT_DENIED: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_DENIED"); break; + case DD_WORKER_STAT_HIDDEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_HIDDEN"); break; + case DD_WORKER_STAT_OPEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_OTHER"); break; + case DD_WORKER_STAT_READ: droiddeck_log("probe", "worker_admission=NATIVE_STAT_READ"); break; + case DD_WORKER_STAT_PARSE: droiddeck_log("probe", "worker_admission=NATIVE_STAT_PARSE"); break; + case DD_WORKER_STAT_ZERO: droiddeck_log("probe", "worker_admission=NATIVE_STAT_ZERO"); break; + } + if (!dd_worker_receipt_allows_reserve(stat, raw_start, receipt)) { close(pidfd); return 0; } + if (poll(&alive, 1, 0) != 0) { + droiddeck_log("probe", "worker_admission=NATIVE_PIDFD_NOT_LIVE"); + close(pidfd); + return 0; + } + pthread_mutex_lock(&frame_worker_lock); + if (frame_worker_pidfd < 0) { + strcpy(frame_worker_file, path); + frame_worker_grant = (struct dd_worker_grant){ + .owner = owner, .uid = getuid(), .pid = pid, .start_ticks = receipt, .expires = expires, + .dev_major = major(st.st_dev), .dev_minor = minor(st.st_dev), .ino = st.st_ino, + .canonical_file = frame_worker_file, .app_launch_verified = true, .final_go = true, + }; + frame_worker_map_reported = false; + frame_worker_pidfd = pidfd; + pidfd = -1; + } + pthread_mutex_unlock(&frame_worker_lock); + if (pidfd >= 0) { + droiddeck_log("probe", "worker_admission=NATIVE_ALREADY_RESERVED"); + close(pidfd); + return 0; + } + droiddeck_log("probe", "frame acquire reserved one app-verified worker"); + return 1; +} + +static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, uint64_t now) { + char proc[64], line[PATH_MAX + 128]; + const char *failure = "worker_admission=MAP_STARTTIME"; + uint64_t raw_start = 0; + if (frame_worker_starttime(g->pid, &raw_start) != DD_WORKER_STAT_OK || raw_start != g->start_ticks) + goto reject; + snprintf(proc, sizeof(proc), "/proc/%u/maps", g->pid); + FILE *f = fopen(proc, "re"); + failure = "worker_admission=MAP_OPEN"; + if (!f) goto reject; + bool matched = false; + size_t budget = 2 * 1024 * 1024; + while (budget && fgets(line, sizeof(line), f)) { + size_t n = strlen(line); + if (!n || line[n - 1] != '\n' || n > budget) break; + budget -= n; + if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, raw_start, now, line)) { + matched = true; + break; + } + } + fclose(f); + if (matched) return true; + failure = "worker_admission=MAP_IDENTITY"; +reject: + if (!frame_worker_map_reported) { + frame_worker_map_reported = true; + droiddeck_log("probe", "%s", failure); + } + return false; +} + +static int frame_acquire_peer_allowed(const struct wl_client *client, bool verify_exec, bool bind) { + pid_t pid = 0; + uid_t uid = (uid_t)-1; + wl_client_get_credentials(client, &pid, &uid, NULL); + struct timespec t; + if (clock_gettime(CLOCK_BOOTTIME, &t) < 0) return 0; + uint64_t now = (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000; + pthread_mutex_lock(&frame_worker_lock); + const struct dd_worker_grant *g = &frame_worker_grant; + struct pollfd alive = {.fd = frame_worker_pidfd, .events = POLLIN}; + bool allowed = frame_worker_pidfd >= 0 && uid == getuid() && pid > 1 && + g->pid == (uint32_t)pid && g->uid == uid && now < g->expires && + poll(&alive, 1, 0) == 0 && (!verify_exec || + (frame_worker_verified_exec_locked(g, now) && poll(&alive, 1, 0) == 0)); + // The short startup authorization may not be renewed by registry enumeration. + // Only an authenticated bind activates the grant for the lifetime of this live, + // unreplaced worker; session teardown revokes it independently of process exit. + if (allowed && bind) frame_worker_grant.expires = UINT64_MAX; + pthread_mutex_unlock(&frame_worker_lock); + return allowed; +} + +static bool frame_acquire_global_filter(const struct wl_client *client, const struct wl_global *global, void *data) { + return wl_global_get_interface(global) != &droiddeck_frame_acquire_v1_interface || + frame_acquire_peer_allowed(client, true, false); +} + +static void frame_acquire_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void frame_acquire_set(struct wl_client *client, struct wl_resource *resource, + struct wl_resource *surface, struct wl_resource *buffer, int32_t fd) { + if (!frame_acquire_peer_allowed(client, false, false)) { + close(fd); + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER, + "paired capture peer is not authorized"); + return; + } + struct surface *s = NULL; + if (surface && buffer && wl_resource_get_client(surface) == client && + wl_resource_get_client(buffer) == client && + wl_resource_instance_of(surface, &wl_surface_interface, &surface_impl) && + get_dmabuf(buffer)) + s = wl_resource_get_user_data(surface); + if (!s || !s->pending_attach || s->pending_buffer != buffer) { + close(fd); + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT, + "fence does not match pending DMA-BUF attachment"); + return; + } + enum dd_frame_acquire_result result = dd_frame_acquire_set(&s->pending_frame_acquire, fd); + if (result == DD_ACQUIRE_DUPLICATE) + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE, + "pending attachment already has a fence"); + else if (result == DD_ACQUIRE_INVALID) + wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE, + "expected an already signaled Linux sync_file"); +} + +static const struct droiddeck_frame_acquire_v1_interface frame_acquire_impl = { + .destroy = frame_acquire_destroy, + .set_acquire_fence = frame_acquire_set, +}; + +static void bind_frame_acquire(struct wl_client *client, void *data, uint32_t version, uint32_t id) { + if (!frame_acquire_peer_allowed(client, true, true)) { + wl_client_post_implementation_error(client, "paired capture peer is not authorized"); + return; + } + struct wl_resource *resource = + wl_resource_create(client, &droiddeck_frame_acquire_v1_interface, 1, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &frame_acquire_impl, NULL, NULL); + droiddeck_log("probe", "frame acquire bound to app-issued worker and exact executable map"); +} +#endif + static void detach_from_parent(struct surface *s) { if (!s->parent) return; wl_list_remove(&s->child_link); @@ -1709,6 +1937,7 @@ static void detach_from_parent(struct surface *s) { static void surface_resource_destroy(struct wl_resource *r) { struct surface *s = wl_resource_get_user_data(r); + dd_frame_acquire_clear(&s->pending_frame_acquire); struct surface *child, *tmp; struct wl_resource *cb, *cbtmp; @@ -4804,6 +5033,7 @@ static int on_stats_timer(void *data) { struct surface *s; wl_list_for_each(s, &g_toplevels, toplevel_link) windows++; unsigned zero_copy = ahb_swapchain_stats_take(); + unsigned verified = ahb_swapchain_producer_fence_stats_take(); unsigned layer_frames = sc_layer_frames_take(); g_zero_copy_last = zero_copy; unsigned generated = vkp_framegen_stats_take(); @@ -4812,7 +5042,8 @@ static int on_stats_timer(void *data) { int off = 0; if (g_zero_copy || zero_copy) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u zero-copy frames", zero_copy); if (layer_frames) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u layer frames", layer_frames); - if (generated) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated); + if (generated) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated); + if (verified) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u verified acquire frames", verified); droiddeck_log("stats", "last 10 s: %u frames on screen (%.1f fps) | %u GPU frames from games | %u window redraws | %d windows open%s", g_stat_frames + generated, (g_stat_frames + generated) / 10.0, g_stat_dmabuf, g_stat_shm, windows, extra); } @@ -5013,6 +5244,12 @@ int droiddeck_wayland_run(void) { wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager); droiddeck_ext_init(display); ahb_swapchain_init(display); +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + if (ahb_swapchain_advertised()) { + wl_display_set_global_filter(display, frame_acquire_global_filter, NULL); + wl_global_create(display, &droiddeck_frame_acquire_v1_interface, 1, NULL, bind_frame_acquire); + } +#endif display_buffers_init(display); diff --git a/app/src/main/cpp/waylandcomp/src/frame_acquire.h b/app/src/main/cpp/waylandcomp/src/frame_acquire.h new file mode 100644 index 0000000000..44ff28333a --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/frame_acquire.h @@ -0,0 +1,39 @@ +#ifndef DD_FRAME_ACQUIRE_H +#define DD_FRAME_ACQUIRE_H +#include +#include +#include +#include +#include + +/* A zero-initialized slot owns no descriptor. Only an already successful + * sync_file can enter this slot; display-side release ownership is separate. */ +struct dd_frame_acquire { int fd_plus_one; }; +enum dd_frame_acquire_result { DD_ACQUIRE_OK, DD_ACQUIRE_DUPLICATE, DD_ACQUIRE_INVALID }; + +static inline void dd_frame_acquire_clear(struct dd_frame_acquire *f) { + if (f->fd_plus_one) close(f->fd_plus_one - 1); + f->fd_plus_one = 0; +} + +static inline enum dd_frame_acquire_result +dd_frame_acquire_set(struct dd_frame_acquire *f, int fd) { + enum dd_frame_acquire_result result; + struct sync_file_info info = {0}; + if (f->fd_plus_one) result = DD_ACQUIRE_DUPLICATE; + else if (fd < 0 || fd == INT_MAX || ioctl(fd, SYNC_IOC_FILE_INFO, &info) != 0 || + info.status != 1 || info.num_fences == 0) result = DD_ACQUIRE_INVALID; + else { + f->fd_plus_one = fd + 1; + return DD_ACQUIRE_OK; + } + if (fd >= 0) close(fd); + return result; +} + +static inline int dd_frame_acquire_dup(const struct dd_frame_acquire *f) { + if (!f->fd_plus_one) return -1; /* Legacy: no explicit attachment proof. */ + int fd = fcntl(f->fd_plus_one - 1, F_DUPFD_CLOEXEC, 0); + return fd < 0 ? -2 : fd; /* Do not re-enter the legacy direct path. */ +} +#endif diff --git a/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h b/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h new file mode 100644 index 0000000000..989e59b336 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/frame_worker_peer.h @@ -0,0 +1,81 @@ +#ifndef DD_WORKER_PEER_H +#define DD_WORKER_PEER_H +#include +#include +#include +#include +#include +#include +#include + +/* Model of one app-issued, session-bound authorization record. No callers, + * property access, proc traversal, or authorization is installed by this file. */ +struct dd_worker_grant { + uint32_t owner, uid, pid, dev_major, dev_minor; + uint64_t start_ticks, ino, expires; + const char *canonical_file; + bool app_launch_verified, final_go; +}; + +enum dd_worker_stat_result { + DD_WORKER_STAT_OK, DD_WORKER_STAT_DENIED, DD_WORKER_STAT_HIDDEN, DD_WORKER_STAT_OPEN, + DD_WORKER_STAT_READ, DD_WORKER_STAT_PARSE, DD_WORKER_STAT_ZERO, +}; + +static inline enum dd_worker_stat_result dd_worker_parse_start(const char *line, uint64_t *out) { + const char *p = strrchr(line, ')'); + if (!p || p[1] != ' ' || !p[2] || p[3] != ' ') return DD_WORKER_STAT_PARSE; + p += 2; + // State is field 3. The starttime (22) is always followed by vsize (23). + for (int field = 3; field < 22; ++field) { + p = strchr(p, ' '); + if (!p) return DD_WORKER_STAT_PARSE; + while (*p == ' ') ++p; + } + char *end; + if (*p < '0' || *p > '9') return DD_WORKER_STAT_PARSE; + errno = 0; + uint64_t value = strtoull(p, &end, 10); + if (errno || end == p || *end != ' ') return DD_WORKER_STAT_PARSE; + if (!value) return DD_WORKER_STAT_ZERO; + *out = value; + return DD_WORKER_STAT_OK; +} + +static inline enum dd_worker_stat_result dd_worker_open_failure(int error) { + if (error == EACCES || error == EPERM) return DD_WORKER_STAT_DENIED; + if (error == ENOENT || error == ESRCH) return DD_WORKER_STAT_HIDDEN; + return DD_WORKER_STAT_OPEN; +} + +static inline bool dd_worker_receipt_allows_reserve(enum dd_worker_stat_result stat, + uint64_t raw, uint64_t receipt) { + if (!receipt) return false; + if (stat == DD_WORKER_STAT_OK) return raw == receipt; + // Only a visibility denial can defer the broker-side stat check, not any + // bad read, malformed record, mismatched timestamp, or other open error. + return stat == DD_WORKER_STAT_DENIED || stat == DD_WORKER_STAT_HIDDEN; +} + +static inline bool dd_worker_map_matches(const struct dd_worker_grant *g, const char *line) { + unsigned major, minor; + uint64_t lo, hi, off, ino; + int prefix = 0; + char mode[5]; + if (!g->canonical_file || !*g->canonical_file || + sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %" SCNx64 " %x:%x %" SCNu64 " %n", + &lo,&hi,mode,&off,&major,&minor,&ino,&prefix)!=7 || + prefix <= 0 || hi <= lo || strlen(mode)!=4 || mode[2]!='x' || + major!=g->dev_major || minor!=g->dev_minor || !ino || ino!=g->ino) + return false; + size_t path_len=strcspn(line+prefix,"\r\n"); + return strlen(g->canonical_file)==path_len && !memcmp(line+prefix,g->canonical_file,path_len); +} + +static inline bool dd_worker_grant_matches(const struct dd_worker_grant *g, uint32_t owner, + uint32_t uid, uint32_t pid, uint64_t start, uint64_t now, const char *executable_map) { + return g && g->app_launch_verified && g->final_go && owner && owner==g->owner && + uid==g->uid && pid>1 && pid==g->pid && start && start==g->start_ticks && + nowexpires && executable_map && dd_worker_map_matches(g,executable_map); +} +#endif diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index f1a8243d06..6d8754e4e5 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -916,3 +916,42 @@ JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) { return (jint)droiddeck_stream_frames(); } + + +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE +extern int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path, + uint64_t dev, uint64_t ino, uint64_t receipt); +extern void droiddeck_frame_worker_revoke(int owner, int pid); +#endif + +JNIEXPORT jboolean JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeEnabled(JNIEnv *env, jclass c) { +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + return JNI_TRUE; +#else + return JNI_FALSE; +#endif +} + +JNIEXPORT jboolean JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeGrant(JNIEnv *env, jclass c, + jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino, jlong start_ticks) { +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + if (!path || expires <= 0 || ino <= 0 || start_ticks <= 0) return JNI_FALSE; + const char *name = (*env)->GetStringUTFChars(env, path, NULL); + if (!name) return JNI_FALSE; + int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino, (uint64_t)start_ticks); + (*env)->ReleaseStringUTFChars(env, path, name); + return granted ? JNI_TRUE : JNI_FALSE; +#else + return JNI_FALSE; +#endif +} + +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeRevoke(JNIEnv *env, jclass c, + jint owner, jint pid) { +#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE + droiddeck_frame_worker_revoke(owner, pid); +#endif +} diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index c4057101c7..e8993cff66 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -611,6 +611,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var hdrOn by mutableStateOf(false) private var zeroCopyOn by mutableStateOf(true) + private var producerAcquireFences by mutableStateOf(false) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) private var hdrReason by mutableStateOf(null) @@ -1086,6 +1087,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } else { putExtra(SessionService.EXTRA_STEAM_URL, com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl(game.gameIdString)) + putExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, true) } } .playing(game), steamSession = true) @@ -2904,6 +2906,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait, panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn, + producerAcquireFences = producerAcquireFences.takeIf { + mode == SessionService.MODE_STEAM && + com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe.available(this) + }, upscaler = upscaler, upscaleSharpness = upscaleSharpness, gpuDrivers = drivers.summary(), touchMode = touchMode, @@ -2968,6 +2974,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode)) com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on) }, + onProducerAcquireFences = { + SessionPrefs.setProducerAcquireFences(this, it) + producerAcquireFences = it + }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, @@ -3329,6 +3339,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet loadBootMovie() hdrOn = SessionPrefs.hdr(this, mode) zeroCopyOn = SessionPrefs.zeroCopy(this, mode) + producerAcquireFences = SessionPrefs.producerAcquireFences(this) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index eeb48aacb3..e8ac7f836e 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -3112,6 +3112,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), intent.getStringExtra(SessionService.EXTRA_GAME_ID), sessionActivityDisplayId, + frontendSteamGame = intent.getBooleanExtra(SessionService.EXTRA_FRONTEND_STEAM_GAME, false), ) intent.getStringExtra(EXTRA_PLAYED_GAME)?.let { com.droiddeck.launcher.frontend.Library.recordPlayed(this, it) } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt b/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt new file mode 100644 index 0000000000..403a8c59cc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbe.kt @@ -0,0 +1,271 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.os.SystemClock +import android.system.Os +import android.system.OsConstants +import android.util.Log +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File +import java.io.InputStream +import java.nio.file.Files +import java.nio.file.LinkOption.NOFOLLOW_LINKS +import java.security.MessageDigest + +/** One app-issued Steam session and one attested Gamescope worker. This is not an + * isolation boundary against arbitrary code already running as the Android app UID. */ +internal object FrameAcquireWorkerProbe { + private const val SESSION_SCRIPT = "/usr/local/bin/droiddeck-session" + private const val PATH = "/usr/local/bin/gamescope" + private const val CAPABILITY = "linuxfs/usr/local/share/droiddeck/gamescope-producer-acquire-v1" + internal const val GAMESCOPE_ENABLE = "GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE=1" + internal const val GAME_ENABLE = "DROIDDECK_GAME_DROIDDECK_GAME_FRAME_ACQUIRE=1" + private const val MAX_BINARY_BYTES = 32L * 1024L * 1024L + internal const val RECEIPT_TAG = 0x44445046 + internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES + private const val TTL_MS = 90_000L + + internal data class Ticket( + val owner: Int, val root: File, val configuredRoot: File, val binary: File, + val expected: ByteArray, val expires: Long, val steamGameUrl: String?, + ) + internal data class Qualified(val ticket: Ticket, val dev: Long, val ino: Long, val mtime: Long, val ctime: Long) + private var intent: Ticket? = null + private var nativeOwner = 0 + private var nativePid = 0 + + private enum class Stage { ARM, MATCH, PUBLISH } + private enum class Reason { + ENABLED, MATCH_ACK, MATCH_OWNER, MATCH_EXPIRED, MATCH_PATH, MATCH_ROOT, + MATCH_ARGV, MATCH_FILE, MATCH_DIGEST, QUALIFIED, PUBLISH_TICKET, PUBLISH_RESTAT, + PUBLISH_NATIVE, PUBLISH_RECEIPT, RESERVED + } + private val reported = mutableSetOf() + @Synchronized private fun breadcrumb(stage: Stage, reason: Reason) { + if (reported.add(stage)) Log.i("FrameAcquireWorkerProbe", "worker_admission=" + reason.name) + } + + internal fun validEnvironment(agentEnvironment: List, customEnvironment: List): Boolean { + // AgentEnv supplies a replacement PATH whenever any executable override is staged. + // Custom env is user-editable, including names not known to this build; it is not a trust root. + return agentEnvironment.isEmpty() && customEnvironment.isEmpty() + } + + fun available(context: Context): Boolean = + android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.core.DeviceSupport.adreno() && + runCatching { context.assets.open(CAPABILITY).use { it.readBytes().decodeToString() } } + .getOrNull() == "droiddeck-producer-acquire-v1\n" + + private fun digest(input: InputStream, maxBytes: Long): ByteArray { + val out = MessageDigest.getInstance("SHA-256") + val buffer = ByteArray(64 * 1024) + var size = 0L + while (true) { + val n = input.read(buffer) + if (n == -1) break + require(n > 0) + size += n + require(size <= maxBytes) + out.update(buffer, 0, n) + } + require(size > 0) + return out.digest() + } + + // Compute asset identity outside SessionService's stop lock and before a worker + // exists. The resulting ticket still has to be assigned to that exact owner. + private const val STEAM_RUN_PREFIX = "steam://rungameid/" + + internal fun permittedLaunch(url: String?, frontendGame: Boolean): Boolean = + if (url == null) !frontendGame else frontendGame && url.startsWith(STEAM_RUN_PREFIX) && + com.droiddeck.launcher.frontend.GameLaunchLink.validId(url.removePrefix(STEAM_RUN_PREFIX)) + + internal fun prepare(context: Context, steamGameUrl: String?, frontendGame: Boolean): Ticket? { + if (!permittedLaunch(steamGameUrl, frontendGame) || + !available(context) || !WaylandCompositor.frameWorkerProbeEnabled()) return null + return runCatching { + val configuredRoot = LinuxRuntime.rootDir(context).absoluteFile + val root = configuredRoot.canonicalFile + val file = File(root.path + PATH) + require(file.canonicalFile == file && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS)) + val script = File(root.path + SESSION_SCRIPT) + require(exactSteamScript(SESSION_SCRIPT, root, configuredRoot)) + val stagedScript = script.inputStream().use { digest(it, 1024L * 1024L) } + val signedScript = context.assets.open("linuxfs" + SESSION_SCRIPT).use { digest(it, 1024L * 1024L) } + require(MessageDigest.isEqual(stagedScript, signedScript)) + val expected = context.assets.open("linuxfs" + PATH).use { digest(it, MAX_BINARY_BYTES) } + Ticket(0, root, configuredRoot, file, expected, SystemClock.elapsedRealtime() + TTL_MS, steamGameUrl) + }.getOrNull() + } + + @Synchronized fun arm(owner: Int, prepared: Ticket): Boolean { + if (owner <= 0 || SystemClock.elapsedRealtime() >= prepared.expires) return false + reported.clear() + intent = prepared.copy(owner = owner) + breadcrumb(Stage.ARM, Reason.ENABLED) + return true + } + + /** Native shebang handling can give Bash the staged host filename as its $0. */ + internal fun exactSteamScript(token: String, root: File, configuredRoot: File): Boolean { + if (token != SESSION_SCRIPT && token != root.path + SESSION_SCRIPT && + token != configuredRoot.path + SESSION_SCRIPT) return false + return runCatching { + val expected = File(root.path + SESSION_SCRIPT) + val supplied = if (token == SESSION_SCRIPT) expected else File(token) + // Reject symlinks within the authorized root, including a symlink replacing the script. + // Android's configured root itself may be an alias of its app-issued canonical root. + require(configuredRoot.canonicalFile == root && expected.canonicalFile == expected && + supplied.canonicalFile == expected && + Files.isRegularFile(expected.toPath(), NOFOLLOW_LINKS) && + Files.isRegularFile(supplied.toPath(), NOFOLLOW_LINKS)) + Files.isSameFile(supplied.toPath(), expected.toPath()) + }.getOrDefault(false) + } + + internal fun exactGamescopeArgs( + argv: List, steamGameUrl: String? = null, script: (String) -> Boolean, + ): Boolean { + if (argv.firstOrNull() !in listOf("gamescope", PATH)) return false + val delimiter = argv.indexOf("--") + val tailSize = if (steamGameUrl == null) 3 else 4 + if (delimiter < 4 || argv.size != delimiter + tailSize || argv[delimiter + 2] != "steam" || + !script(argv[delimiter + 1]) || + (steamGameUrl != null && (!permittedLaunch(steamGameUrl, true) || argv.last() != steamGameUrl))) return false + val opts = argv.subList(1, delimiter) + if (opts.take(4) != listOf("--backend", "wayland", "--expose-wayland", "-f")) return false + val dimensions = setOf("-W", "-H", "-w", "-h") + val seen = mutableSetOf() + var i = 4 + while (i < opts.size) { + val option = opts[i++] + if (!seen.add(option)) return false + when (option) { + "-e", "--hdr-enabled", "--mangoapp" -> Unit + "-S" -> if (opts.getOrNull(i++) != "stretch") return false + "--default-touch-mode" -> if (opts.getOrNull(i++) != "4") return false + "-W", "-H", "-w", "-h", "-r", "--xwayland-count" -> { + val value = opts.getOrNull(i++) ?: return false + if (value.length !in 1..6 || value.any { it !in '0'..'9' } || + value.toIntOrNull()?.let { it > 0 } != true) return false + } + else -> return false + } + } + return seen.containsAll(dimensions) + } + + fun match(owner: Int, root: File, file: String, argv: List, ack: Boolean): Qualified? { + val t = synchronized(this) { intent } ?: return null + // Startup's --version worker and unrelated workers must not consume the one diagnostic. + val candidate = "--version" !in argv && (file.substringAfterLast('/') == "gamescope" || + argv.firstOrNull()?.substringAfterLast('/') == "gamescope") + val rejection = when { + !ack -> Reason.MATCH_ACK + t.owner != owner -> Reason.MATCH_OWNER + SystemClock.elapsedRealtime() >= t.expires -> Reason.MATCH_EXPIRED + file != PATH -> Reason.MATCH_PATH + runCatching { root.canonicalFile }.getOrNull() != t.root -> Reason.MATCH_ROOT + !exactGamescopeArgs(argv, t.steamGameUrl) { exactSteamScript(it, t.root, t.configuredRoot) } -> Reason.MATCH_ARGV + else -> null + } + if (rejection != null) { + if (candidate) breadcrumb(Stage.MATCH, rejection) + return null + } + // Hash an actual descriptor rather than two pathname opens. Check both the + // descriptor and pathname identity; a race or substituted executable denies the grant. + val qualified = runCatching { + require(t.binary.canonicalFile == t.binary) + val before = Os.lstat(t.binary.path) + require(OsConstants.S_ISREG(before.st_mode) && before.st_size in 1..MAX_BINARY_BYTES) + val fd = Os.open(t.binary.path, OsConstants.O_RDONLY or OsConstants.O_NOFOLLOW or OsConstants.O_CLOEXEC, 0) + val sum = try { + require(stillSame(before, Os.fstat(fd))) + android.os.ParcelFileDescriptor.AutoCloseInputStream(android.os.ParcelFileDescriptor.dup(fd)).use { + digest(it, MAX_BINARY_BYTES) + }.also { require(stillSame(before, Os.fstat(fd))) } + } finally { + Os.close(fd) + } + val after = Os.lstat(t.binary.path) + require(stillSame(before, after)) + if (!MessageDigest.isEqual(sum, t.expected)) { + breadcrumb(Stage.MATCH, Reason.MATCH_DIGEST) + return null + } + Qualified(t, after.st_dev, after.st_ino, after.st_mtime, after.st_ctime) + }.getOrNull() + breadcrumb(Stage.MATCH, if (qualified == null) Reason.MATCH_FILE else Reason.QUALIFIED) + return qualified + } + + private fun stillSame(a: android.system.StructStat, b: android.system.StructStat): Boolean = + a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size && + a.st_mtime == b.st_mtime && a.st_ctime == b.st_ctime && + OsConstants.S_ISREG(b.st_mode) + + internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long = + if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L + + internal fun parseSelfStat(stat: String, pid: Int): Long { + if (pid <= 1 || !stat.startsWith("$pid (")) return 0L + val comm = stat.lastIndexOf(')') + if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L + val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() } + if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L + val value = fields[19] // field 22 from field 3 (the single-character task state). + return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } } + ?.toLongOrNull()?.takeIf { it > 0 } ?: 0L + } + + internal fun selfStartTicks(pid: Int): Long = runCatching { + File("/proc/self/stat").inputStream().use { input -> + val bytes = ByteArray(4096) + var used = 0 + while (used < bytes.size) { + val n = input.read(bytes, used, bytes.size - used) + if (n < 0) break + if (n == 0) return@runCatching 0L + used += n + } + if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L + else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid) + } + }.getOrDefault(0L) + + /** Runs just before the final GO byte. Failure never changes ordinary launch. */ + @Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) { + val t = q.ticket + if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) { + if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET) + return + } + intent = null // At most one candidate per explicitly armed session. + if (startTicks <= 0L) { + breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT) + return + } + val status = runCatching { + val st = Os.lstat(t.binary.path) + require(OsConstants.S_ISREG(st.st_mode) && st.st_dev == q.dev && st.st_ino == q.ino && + st.st_mtime == q.mtime && st.st_ctime == q.ctime) + if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) { + nativeOwner = t.owner + nativePid = pid + Reason.RESERVED + } else Reason.PUBLISH_NATIVE + }.getOrDefault(Reason.PUBLISH_RESTAT) + breadcrumb(Stage.PUBLISH, status) + } + + @Synchronized fun revoke(owner: Int, pid: Int = 0) { + if (owner <= 0) return + if (pid == 0 && intent?.owner == owner) intent = null + if (nativeOwner == owner && (pid == 0 || pid == nativePid)) { + WaylandCompositor.frameWorkerProbeRevoke(owner, pid) + nativeOwner = 0 + nativePid = 0 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt index b4843fc6df..e3f7d0ba01 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -45,7 +45,16 @@ open class GuestWorker : Service() { val fillBinderFd = data.readInt() != 0 val go = data.readFileDescriptor() val nice = data.readInt() - reply?.writeInt(Process.myPid()) + val pid = Process.myPid() + reply?.writeInt(pid) + // Optional fixed-size receipt, on the exact local, non-exported worker's Binder. + // Nothing in the guest socket request populates these fields. + if (reply != null && + Binder.getCallingUid() == Process.myUid() && + data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) { + reply.writeInt(pid) + reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid)) + } Handler(Looper.getMainLooper()).post { // The app writes a byte once it has the reply and has taken the launch on: an exec // before then would end this process with the reply undelivered, and with none (the @@ -437,7 +446,8 @@ object GuestWorkers { private fun start(context: Context, argv: List, env: List, fds: List, targets: IntArray, guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true }, confirmed: () -> Boolean = { true }, owner: Int = session, - nice: Int = Process.getThreadPriority(Process.myTid())): Int { + nice: Int = Process.getThreadPriority(Process.myTid()), + testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int { val app = context.applicationContext if (guest && owner <= stopped) { Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") + @@ -473,13 +483,21 @@ object GuestWorkers { data.writeInt(if (guest) 0 else 1) data.writeFileDescriptor(go[0].fileDescriptor) data.writeInt(nice) - slot.service!!.transact(GuestWorker.RUN, data, reply, 0) + val service = checkNotNull(slot.service) + if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG) + check(service.transact(GuestWorker.RUN, data, reply, 0)) // The worker has its own copy: with ours closed (and the request's, which holds one too), // a worker that gave up leaves no reader data.recycle() data = null go[0].close() val pid = reply.readInt() + val startTicks = if (testWorker != null) { + val size = reply.dataAvail() + if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES) + FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size) + else 0L + } else 0L // Once a session's teardown has begun (stopGuests), none of its programs may start: it // would not find them. val stopping = { guest && owner <= stopped } @@ -508,7 +526,12 @@ object GuestWorkers { // launching slot), or never. val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1 val accepted = answered && synchronized(authorizing) { - !stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + if (stopping() || !confirmed()) false + else { + if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid, + if (slot.service === service) startTicks else 0L) + Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1 + } } val endedRunning = synchronized(slots) { slot.launching = false @@ -685,6 +708,7 @@ object GuestWorkers { } } context?.let { app -> drained.forEach { release(app, it) } } + FrameAcquireWorkerProbe.revoke(of) val pids = guestPids(of) if (pids.isEmpty()) return pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) } @@ -902,16 +926,19 @@ object GuestWorkers { val owner = request.optInt("session", 0).coerceAtLeast(0) // The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT) + val testWorker = FrameAcquireWorkerProbe.match(owner, root, file, argv, ack) val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code -> + if (testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker) status = code if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker) exited.countDown() }, confirmed = { - !ack || runCatching { + val confirmed = !ack || runCatching { out.write("ok\n".toByteArray()) out.flush() confirmedToHook = true }.isSuccess + confirmed }, commit = { started -> worker = started if (!ack) return@start true @@ -930,7 +957,8 @@ object GuestWorkers { } ended && line.toString() == "go" }.getOrDefault(false) - }) + }, testWorker = testWorker) + if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker) handedOver = true programFds.filter { it !== table }.forEach { runCatching { it.close() } } if (pid <= 0) table?.let { runCatching { it.close() } } 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 3a33e47be3..19ad40b695 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1874,6 +1874,13 @@ object SessionPrefs { prefs(context).edit().putBoolean(hdrKey(mode), on).apply() } + /** Restart-scoped opt-in; not inferred from Zero-copy (which defaults on). */ + fun producerAcquireFences(context: Context): Boolean = prefs(context).getBoolean("producerAcquireFences", false) + + fun setProducerAcquireFences(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("producerAcquireFences", on).apply() + } + fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true) fun setZeroCopy(context: Context, mode: String, on: Boolean) { 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 eb4fed441c..16b9fd84e7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -394,8 +394,10 @@ class SessionService : Service() { SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM) SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty() SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI) - SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL) - val steamUrlGameId = SessionState.steamUrl + val launchSteamUrl = intent?.getStringExtra(EXTRA_STEAM_URL) + val frontendSteamGame = intent?.getBooleanExtra(EXTRA_FRONTEND_STEAM_GAME, false) == true + SessionState.steamUrl = launchSteamUrl + val steamUrlGameId = launchSteamUrl ?.let { url -> when { url.startsWith(GAME_URL_PREFIX) -> @@ -447,7 +449,7 @@ class SessionService : Service() { Thread({ OrphanReaper.reap("session starting") ProtonExtras.awaitReplacement(120_000) - runSession(gen) + runSession(gen, launchSteamUrl, frontendSteamGame) }, "session-start").start() return START_NOT_STICKY } @@ -500,7 +502,7 @@ class SessionService : Service() { } - private fun runSession(gen: Int) { + private fun runSession(gen: Int, launchSteamUrl: String?, frontendSteamGame: Boolean) { SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(this) if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) { com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) } @@ -555,9 +557,10 @@ class SessionService : Service() { return } } - val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) } + val nextAgentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) } .onFailure { Log.w(TAG, "agent environment skipped", it) } - .getOrDefault(emptyList()) + val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList()) + val customEnvironment = extraEnv() try { if (systemVulkan) { SystemVulkanDriver.prepare(this) @@ -623,7 +626,7 @@ class SessionService : Service() { .onFailure { Log.w(TAG, "forced components", it) } } try { - SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) } + SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment, customEnvironment) } } catch (e: IllegalStateException) { Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e) failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1) @@ -708,15 +711,28 @@ class SessionService : Service() { // this session's worker number: the shared field may be a newer session's by the time it is used var ownWorkers = 0 if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) { + val fenceWorker = com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe + val preparedFence = if (steamHere && !systemVulkan && !VenusComponent.wanted(this) && + SessionPrefs.zeroCopy(this, MODE_STEAM) && SessionPrefs.producerAcquireFences(this) && + nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment(agentEnvironment, customEnvironment) + ) fenceWorker.prepare(this, launchSteamUrl, frontendSteamGame) else null + var fenceArmed = false // Under the lock a stop takes its number with: a stop either comes first (and this session // starts no workers) or owns them ownWorkers = synchronized(stopLock) { if (gen != sessionGen || !SessionState.running) 0 - else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it } + else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { + guestWorkerSession = it + if (preparedFence != null) fenceArmed = fenceWorker.arm(it, preparedFence) + } } if (ownWorkers > 0) { guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this)) guest.add("DD_SPAWN_SESSION=$ownWorkers") + if (fenceArmed) { + guest.add(fenceWorker.GAMESCOPE_ENABLE) + guest.add(fenceWorker.GAME_ENABLE) + } } } // Proton builds up to 11.12 report X11 text fields under this name. @@ -738,7 +754,7 @@ class SessionService : Service() { val desktopGuest = ArrayList(guest) guest.add(LinuxRuntime.SESSION_SCRIPT) guest.add(SessionState.mode) - if (SessionState.mode == MODE_STEAM) SessionState.steamUrl?.takeIf { it.startsWith("steam://") }?.let { + if (SessionState.mode == MODE_STEAM) launchSteamUrl?.takeIf { it.startsWith("steam://") }?.let { guest.add(it) Log.i(TAG, "steam: handing the client $it") } @@ -1017,7 +1033,8 @@ class SessionService : Service() { return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode } - private fun addClientEnvironment(guest: MutableList, steamHere: Boolean, agentEnvironment: List) { + private fun addClientEnvironment(guest: MutableList, steamHere: Boolean, + agentEnvironment: List, customEnvironment: List) { guest.add("/usr/bin/env") guest.add("-i") guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this)) @@ -1135,7 +1152,7 @@ class SessionService : Service() { guest.add("DD_ZRAM=1") } guest.add("AUDIO_DIRECT_DECAY=0") - val extra = extraEnv() + agentEnvironment + val extra = customEnvironment + agentEnvironment guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra)) if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=") extra.forEach { guest.add(it) } @@ -2755,6 +2772,9 @@ class SessionService : Service() { const val EXTRA_PROGRAM_ARGS = "programArgs" const val EXTRA_STEAM_UI = "steamUi" const val EXTRA_STEAM_URL = "steamUrl" + // Set by the first-party Library play action on the private SessionActivity/Service path. + // Never copied from an exported intent or Agent command. + internal const val EXTRA_FRONTEND_STEAM_GAME = "com.droiddeck.launcher.FRONTEND_STEAM_GAME" const val EXTRA_GAME_ID = "gameId" fun start( @@ -2762,6 +2782,7 @@ class SessionService : Service() { steamUi: String? = null, steamUrl: String? = null, programArgs: Array? = null, gameId: String? = null, displayId: Int = Display.DEFAULT_DISPLAY, + frontendSteamGame: Boolean = false, ) { SteamClientPrefetch.cancel() SessionState.activityDisplayId = displayId @@ -2772,6 +2793,7 @@ class SessionService : Service() { if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl) + if (frontendSteamGame) intent.putExtra(EXTRA_FRONTEND_STEAM_GAME, true) if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index d1a7b862fc..313f67a574 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -20,7 +20,7 @@ object SettingsReset { "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", - "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", + "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "producerAcquireFences", "paceCores", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage", "guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark", diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 3509d0a83d..cc8a9bc0eb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -62,6 +62,7 @@ class ModeSettings( val hdrReason: String?, val hdrDisplay: Boolean = true, val zeroCopy: Boolean = true, + val producerAcquireFences: Boolean? = null, val gpuDrivers: String? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, @@ -125,6 +126,7 @@ class ModeSettingsActions( val onResolutionPortrait: (String) -> Unit = {}, val onHdr: (Boolean) -> Unit, val onZeroCopy: (Boolean) -> Unit = {}, + val onProducerAcquireFences: (Boolean) -> Unit = {}, val onGpuDrivers: () -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -284,6 +286,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch) } ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy) + s.producerAcquireFences?.let { enabled -> + ToggleRow(host, "producer-acquire-fences", stringResource(R.string.producer_acquire_fences), + stringResource(R.string.producer_acquire_fences_summary), checked = enabled, + onChange = a.onProducerAcquireFences) + } } SettingsGroup(stringResource(R.string.display_image_scaling)) { s.integerScaling?.let { enabled -> diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 70fdc0e595..86e5b90601 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -9,6 +9,10 @@ public final class WaylandCompositor { private WaylandCompositor() {} + public static native boolean frameWorkerProbeEnabled(); + public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks); + public static native void frameWorkerProbeRevoke(int owner, int pid); + private static volatile Runnable firstFrameListener; public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0c2bc79eaa..0aa6e64681 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4519,4 +4519,6 @@ Close Steam first Pause the Steam download first This game installs its Linux build. Install it from Steam. + Direct game frames (experimental) + With Zero-copy enabled, compatible Steam games can avoid a frame copy. Takes effect next session. diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt new file mode 100644 index 0000000000..f771031b4c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/FrameAcquireWorkerProbeTest.kt @@ -0,0 +1,117 @@ +package com.droiddeck.launcher.runtime + +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class FrameAcquireWorkerProbeTest { + @Test fun requiresExactSteamScriptInTheAppIssuedGuestRoot() { + val dir = Files.createTempDirectory("worker-probe-script").toFile().canonicalFile + try { + val root = File(dir, "root").apply { mkdir() } + val configured = File(dir, "configured") + Files.createSymbolicLink(configured.toPath(), root.toPath()) + val untrustedAlias = File(dir, "other-alias") + Files.createSymbolicLink(untrustedAlias.toPath(), root.toPath()) + val script = "/usr/local/bin/droiddeck-session" + val expected = File(root.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") } + val otherRoot = File(dir, "sibling") + File(otherRoot.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") } + val otherScript = File(expected.parentFile, "other-script").apply { writeText("#!/bin/bash\n") } + + val args = listOf("gamescope", "--backend", "wayland", "--expose-wayland", "-f", + "-W", "1280", "-H", "720", "-w", "1280", "-h", "720", "-r", "60", + "-e", "--xwayland-count", "2", "--default-touch-mode", "4", "--hdr-enabled", + "--", script, "steam") + fun valid(argv: List) = FrameAcquireWorkerProbe.exactGamescopeArgs(argv) { + FrameAcquireWorkerProbe.exactSteamScript(it, root, configured) + } + fun child(path: String) = args.dropLast(2) + listOf(path, "steam") + + assertTrue(valid(args)) + assertTrue(valid(args.toMutableList().also { it[0] = "/usr/local/bin/gamescope" })) + assertFalse(valid(args.toMutableList().also { it[0] = "/opt/droiddeck-agent/bin/gamescope" })) + assertTrue(valid(child(root.path + script))) + assertTrue(valid(child(configured.path + script))) + for (path in listOf(otherRoot.path + script, untrustedAlias.path + script, + root.path + "/usr/local/bin/./droiddeck-session", root.path + "/../sibling" + script, + otherScript.path, "droiddeck-session")) { + assertFalse(valid(child(path))) + } + for (bad in listOf(listOf("gamescope", "--version"), args + "", + args + "steam://open/library", args.dropLast(1) + "desktop", + args.take(5) + "--unknown-flag" + args.drop(5), + args.take(5) + listOf("-W", "64") + args.drop(5))) { + assertFalse(valid(bad)) + } + + assertTrue(expected.delete()) + Files.createSymbolicLink(expected.toPath(), otherScript.toPath()) + assertFalse(valid(args)) + assertFalse(valid(child(configured.path + script))) + } finally { + // Don't follow the intentionally broken/foreign symlinks in this fixture. + Files.walk(dir.toPath()).use { paths -> + paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) } + } + } + } + @Test fun warmSteamAndExactlyExpectedFirstPartyColdLaunchOnly() { + val probe = FrameAcquireWorkerProbe + val script = "/usr/local/bin/droiddeck-session" + val args = listOf("gamescope", "--backend", "wayland", "--expose-wayland", "-f", + "-W", "1280", "-H", "720", "-w", "1280", "-h", "720", "--", script, "steam") + val url = com.droiddeck.launcher.frontend.GameLaunchLink.steamUrl("3902570") + fun valid(actual: List, expected: String?) = probe.exactGamescopeArgs(actual, expected) { it == script } + + assertTrue(probe.permittedLaunch(null, false)) + assertFalse(probe.permittedLaunch(null, true)) + assertTrue(probe.permittedLaunch(url, true)) + assertFalse(probe.permittedLaunch(url, false)) + assertTrue(valid(args, null)) + assertTrue(valid(args + url, url)) + assertFalse(valid(args + url, null)) + assertFalse(valid(args, url)) + assertFalse(valid(args + "steam://rungameid/3902571", url)) + assertFalse(valid(args + listOf(url, ""), url)) + assertFalse(valid(args + listOf(url, "--version"), url)) + assertFalse(valid(args + listOf(url, url), url)) + assertFalse(valid(args.dropLast(2) + listOf("/tmp/droiddeck-session", "steam", url), url)) + for (bad in listOf("steam://open/library", "steam://run/3902570", "Steam://rungameid/3902570", + "steam://rungameid/03902570", "$url/", "$url?x=1", "$url#x", "$url%20", + "$url --version", "steam://rungameid/18446744073709551616", "https://example.test/")) { + assertFalse(probe.permittedLaunch(bad, true)) + assertFalse(valid(args + bad, bad)) + } + } + + @Test fun selfStatAndFixedBinderReceiptRejectWrongWorkerAndExtraBytes() { + val probe = FrameAcquireWorkerProbe + val fields = (1..18).joinToString(" ") + fun stat(pid: Int, ticks: String) = "$pid (guest )worker) S $fields $ticks 123\n" + assertTrue(probe.parseSelfStat(stat(400, "125"), 400) == 125L) + for (bad in listOf(stat(401, "125"), stat(400, "0"), stat(400, "-1"), + stat(400, "1x"), stat(400, "9223372036854775808"), "400 (guest)")) { + assertTrue(probe.parseSelfStat(bad, 400) == 0L) + } + val size = probe.RECEIPT_BYTES + assertTrue(probe.validReceipt(400, 400, 125L, size) == 125L) + assertTrue(probe.validReceipt(400, 401, 125L, size) == 0L) + assertTrue(probe.validReceipt(1, 1, 125L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, 0L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, -1L, size) == 0L) + assertTrue(probe.validReceipt(400, 400, 125L, size - 4) == 0L) + assertTrue(probe.validReceipt(400, 400, 125L, size + 4) == 0L) + } + + @Test fun anyCustomOrAgentEnvironmentDisablesTheProductionTicket() { + val probe = FrameAcquireWorkerProbe + assertTrue(probe.validEnvironment(emptyList(), emptyList())) + assertFalse(probe.validEnvironment(listOf("PATH=/opt/droiddeck-agent/bin"), emptyList())) + assertFalse(probe.validEnvironment(emptyList(), listOf("LD_PRELOAD=/tmp/custom.so"))) + assertFalse(probe.validEnvironment(listOf("DD_THOR_WORKER_ACQUIRE_TEST=1"), emptyList())) + } + +} diff --git a/docs/development/producer-acquire-fences.md b/docs/development/producer-acquire-fences.md new file mode 100644 index 0000000000..880f216f0c --- /dev/null +++ b/docs/development/producer-acquire-fences.md @@ -0,0 +1,19 @@ +# Opt-in producer acquire fences for Steam + +[Thor investigation and captured benchmark](https://github.com/Droid-Deck/DroidDeck/pull/3636). + +The existing copy path is the default. In Steam display settings, **Direct game frames (experimental)** is a separate opt-in, applied at the next session. It requires zero-copy presentation, an eligible Adreno/native-worker Steam session, and a signed APK containing a capable Gamescope asset. The next normal session without the option, or a session with custom or Agent launch environment overrides, sees no private host global. Non-compatible clients and older components keep their current path. This is not a trust boundary against arbitrary code already executing as the Android app UID. + +## Source and lifetime + +- APK preparation verifies the Gamescope archive digest. At run time, the app compares the staged executable against the signed APK copy. It also checks the staged session script. No Agent executable, user environment, debug property, or test key can arm the host. Only a launch of the exact staged Gamescope path can qualify. +- One app-owned session prepares a short-lived worker ticket. Only the matching Steam backend launch can consume it. The dedicated, app-bound non-exported Worker reports its own PID/start time through the existing local Binder exchange, not into a guest message. The broker uses a live pidfd, a matching start time, and an exact executable mapping after exec. If Android hides the pre-exec stat entry, the Worker receipt is provisional only until the same timestamp is observable after exec. A malformed or wrong timestamp, wrong executable, stale worker, or no pidfd denies the private global. The bound grant remains scoped to that worker and is revoked on stop or worker exit. +- Gamescope only offers v1 to nested clients after negotiating v1 with that authenticated host. Mesa must export a real native sync_file for that particular attachment. Gamescope ties it to the exact submitted buffer/commit, waits on its duplicate normally, and forwards only a successful, signaled fence for unchanged source content. It cannot use a source fence as proof for composited output. The host consumes only a matching attachment's genuine successful fence and retains existing release and copy behavior. No fence, failed export, unsupported buffer, missing global, or X11-only path is not a license to scan out unsynchronized content. + +## Validation and rollout gates + +The historical controlled build on Thor used the same APK/components in both arms, the same Bright Family House camera with 120/no VSync and Steam limiter off at 60 Hz. Independent Android actual-presentation timestamps measured **21.08 FPS OFF → 37.42 FPS ON**. The compositor separately submitted 42.5–42.6 FPS on the direct path. This validates the technical approach, not the final candidate or physical panel behavior. + +Before default changes or release: after testing the exact signed candidate with the intended Gamescope and Turnip binaries, record OFF/ON same-scene timestamps and direct/layer/full/verified-acquire counters; old producer/host, malformed/missing proof, X11/FIFO and unsupported import should use safe fallback. Exercise cap changes, pause/resume, Home→return, and a cold restart to verify no stale fence/buffer/cap state. Test boot with the option off. Use an external camera on the actual panel for tearing/corruption; Android captures cannot settle it. Keep the feature off by default and hold rollout if these checks do not pass. + +The APK pins the SHA-256 of [the exact tested Gamescope archive](https://github.com/Droid-Deck/DroidDeck-Components/releases/tag/gamescope-3.16.29-verified-acquire-v1), promoted without rebuilding or replacing the previous release. It includes the signed APK capability marker. A compatible DD-Turnip producer is still required for actual direct frames: an older driver or missing fence retains the copy path even if the option is enabled. diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 9c322dbff4..045208fc51 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -506,3 +506,15 @@ on a 120 Hz screen (frames alternately one and two refreshes apart). The first t it is still being scanned out, the backend now composites every frame into its own output images. Those are reused at latch under 0146, and the client's buffers return as soon as the composite has read them: the Steam UI then runs at the full 120 fps. Hosts that release a buffer only after scanout never take this path and keep forwarding. + +## 0998 Wayland backend: verified producer acquire fences for forwarded frames + +When the app opts in and the parent Wayland registry actually advertises +`droiddeck_frame_acquire_v1`, Gamescope offers a separate v1 acquire global +to nested clients. A validated native sync_file stays with one matching +surface attachment and commit generation. Pending fences go through the +existing readiness waiter; a failed fence never marks a frame ready. +Only a forwarded, unchanged source buffer can carry its completed fence to +the parent. Composited output, unsupported clients, older hosts, and X11 +continue through their existing paths. The host and producer do not need +to upgrade simultaneously to retain the existing copy fallback. diff --git a/tools/gamescope/build-in-arch.sh b/tools/gamescope/build-in-arch.sh index cf56408bff..a021265d39 100755 --- a/tools/gamescope/build-in-arch.sh +++ b/tools/gamescope/build-in-arch.sh @@ -46,6 +46,9 @@ cd "$WORK" g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \ tools/gamescope/tests/nested-swapchain.cpp -o pkg/test-nested-swapchain pkg/test-nested-swapchain +g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \ + tools/gamescope/tests/producer-acquire.cpp -o pkg/test-producer-acquire +env -u GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE pkg/test-producer-acquire rm -rf out && mkdir -p out/usr/local/bin PKG=$(ls pkg/arch/gamescope-*.pkg.tar.* | grep -v -- '-debug-' | head -1) tar -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope @@ -60,6 +63,11 @@ echo "NEEDED: $NEEDED" MISSING="" for lib in $NEEDED; do grep -qx "$lib" tools/gamescope/runtime-sonames.txt || MISSING="$MISSING $lib"; done if [ -n "$MISSING" ]; then echo "ERROR: not in the runtime:$MISSING"; exit 3; fi +# The signed APK can distinguish the negotiated release from earlier Gamescope +# assets; leave the feature unavailable rather than relying on a filename. +LC_ALL=C grep -aFq 'GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE' out/usr/local/bin/gamescope +mkdir -p out/usr/local/share/droiddeck +printf 'droiddeck-producer-acquire-v1\n' > out/usr/local/share/droiddeck/gamescope-producer-acquire-v1 (cd out && tar --use-compress-program='zstd -19' -cf ../gamescope.tzst usr) sha256sum gamescope.tzst | tee gamescope.tzst.sha256 ls -l gamescope.tzst out/usr/local/bin/gamescope diff --git a/tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch b/tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch new file mode 100644 index 0000000000..d7826b51f1 --- /dev/null +++ b/tools/gamescope/patches/0998-forward-verified-producer-acquire-fences.patch @@ -0,0 +1,693 @@ +diff --git a/protocol/droiddeck-frame-acquire-v1.xml b/protocol/droiddeck-frame-acquire-v1.xml +new file mode 100644 +index 0000000..f056b6e +--- /dev/null ++++ b/protocol/droiddeck-frame-acquire-v1.xml +@@ -0,0 +1,43 @@ ++ ++ ++ ++ ++ Optional explicit acquire sideband independent of DRM syncobj and buffer ++ allocation. Binding does not opt the client out of ordinary wl_buffer ++ release or existing synchronization protocols. The server advertises it ++ only when it implements all semantics for the selected display path. ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ After wl_surface.attach of a non-null buffer, and before its next ++ wl_surface.commit, send the producer's final writer fence for that ++ exact attachment. This outer probe requires that fence to have already ++ successfully signaled. The fence must be a real Linux sync_file, not a ++ dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received ++ descriptor once for that attachment; the caller closes its local FD ++ after marshalling. ++ ++ The receiver validates the matching pending surface and buffer and ++ validates the descriptor. A duplicate, invalid, pending or mismatched ++ request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same ++ wl_buffer), detach, surface/resource loss or supersession makes the ++ old proof inapplicable. Metadata-only commits may amend receiver-side ++ still-pending state but cannot introduce or re-use a fence themselves. ++ If no request was made, the receiver keeps its established safe path. ++ If a valid fence has been accepted and later the layer is ineligible, ++ the buffer must not be copied/read before that fence is satisfied or ++ imported as the source dependency. Transport never implies readiness ++ on missed deadlines and never changes release/retirement requirements. ++ ++ ++ ++ ++ ++ ++ +diff --git a/protocol/droiddeck-game-frame-acquire-v1.xml b/protocol/droiddeck-game-frame-acquire-v1.xml +new file mode 100644 +index 0000000..1b8c2a5 +--- /dev/null ++++ b/protocol/droiddeck-game-frame-acquire-v1.xml +@@ -0,0 +1,17 @@ ++ ++ ++ ++ ++ Immediately after wl_surface.attach and before the associated nonempty ++ commit, submit the successful or pending Linux sync_file representing the ++ final writer of that exact attachment. The caller closes its descriptor ++ after marshalling. This does not change wl_buffer release semantics. ++ Without a genuine positive descriptor, omit the sideband. ++ ++ ++ ++ ++ ++ ++ ++ +diff --git a/protocol/meson.build b/protocol/meson.build +index 71fe31b..1e56fbf 100644 +--- a/protocol/meson.build ++++ b/protocol/meson.build +@@ -44,6 +44,8 @@ protocols = [ + 'gamescope-action-binding.xml', + + 'droiddeck-refresh-v1.xml', ++ 'droiddeck-game-frame-acquire-v1.xml', ++ 'droiddeck-frame-acquire-v1.xml', + + # wlroots protocols + 'wlr-layer-shell-unstable-v1.xml', +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 45e32f3..e5cb845 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -43,6 +43,7 @@ + #include + #include + #include ++#include + #include "wlr_end.hpp" + + #include "drm_include.h" +@@ -143,6 +144,7 @@ namespace gamescope + struct WaylandPlaneState + { + wl_buffer *pBuffer; ++ std::shared_ptr pProducerFence; + int32_t nDestX; + int32_t nDestY; + double flSrcX; +@@ -755,6 +757,8 @@ namespace gamescope + virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override; + + std::span GetHostRefreshRates() const; ++ droiddeck_frame_acquire_v1 *GetHostAcquire() const { return m_pHostAcquire; } ++ bool SupportsDroidDeckProducerAcquire() const override { return m_pHostAcquire != nullptr; } + void SyncHostRefreshTarget(); + virtual bool SupportsExplicitSync() const override; + +@@ -893,6 +897,7 @@ namespace gamescope + OwningRc m_pBlackTexture; + wp_presentation *m_pPresentation = nullptr; + droiddeck_refresh_v1 *m_pHostRefresh = nullptr; ++ droiddeck_frame_acquire_v1 *m_pHostAcquire = nullptr; + std::array m_HostRefreshRates{}; + std::atomic m_uHostRefreshRateCount = { 0 }; + std::vector m_PendingHostRefreshRates; +@@ -1613,6 +1618,8 @@ namespace gamescope + { + std::unique_lock lock( m_PlaneStateLock ); + m_oCurrentPlaneState = oState; ++ if (m_oCurrentPlaneState) ++ m_oCurrentPlaneState->pProducerFence.reset(); + } + + if ( oState ) +@@ -1760,6 +1767,12 @@ namespace gamescope + // The x/y here does nothing? Why? What is it for... + // Use the subsurface set_position thing instead. + wl_surface_attach( m_pSurface, oState->pBuffer, 0, 0 ); ++ if ( auto *manager = m_pBackend->GetHostAcquire(); manager && oState->pProducerFence ) ++ { ++ const int fd = oState->pProducerFence->SignaledFd(); ++ if (fd >= 0) ++ droiddeck_frame_acquire_v1_set_acquire_fence(manager, m_pSurface, oState->pBuffer, fd); ++ } + wl_surface_damage( m_pSurface, 0, 0, INT32_MAX, INT32_MAX ); + wl_surface_set_opaque_region( m_pSurface, oState->bOpaque ? m_pBackend->GetFullRegion() : nullptr ); + wl_surface_set_buffer_scale( m_pSurface, 1 ); +@@ -1815,6 +1828,7 @@ namespace gamescope + ClipPlane( WaylandPlaneState + { + .pBuffer = pBuffer, ++ .pProducerFence = pLayer->pProducerFence, + .nDestX = int32_t( -pLayer->offset.x ), + .nDestY = int32_t( -pLayer->offset.y ), + .flSrcX = 0.0, +@@ -2812,6 +2826,12 @@ namespace gamescope + wl_output_add_listener( pOutput , &s_OutputListener, this ); + m_pOutputs.emplace( std::make_pair( std::move( pOutput ), WaylandOutputInfo{} ) ); + } ++ else if ( droiddeck::ProducerAcquireEnabled() && ++ uVersion >= 1 && !strcmp( pInterface, droiddeck_frame_acquire_v1_interface.name ) && !m_pHostAcquire ) ++ { ++ m_pHostAcquire = static_cast( ++ wl_registry_bind( pRegistry, uName, &droiddeck_frame_acquire_v1_interface, 1u ) ); ++ } + else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) ) + { + m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u ); +diff --git a/src/WaylandServer/WaylandServerLegacy.h b/src/WaylandServer/WaylandServerLegacy.h +index 63ee2ca..0164853 100644 +--- a/src/WaylandServer/WaylandServerLegacy.h ++++ b/src/WaylandServer/WaylandServerLegacy.h +@@ -3,9 +3,11 @@ + #include + #include "WaylandDecls.h" + #include ++#include + #include + #include + #include "vulkan_include.h" ++#include "droiddeck_producer_fence.hpp" + + + #include "wlr_begin.hpp" +@@ -57,6 +59,10 @@ struct wlserver_wl_surface_info + uint64_t desired_present_time = 0; + + uint64_t last_refresh_cycle = 0; ++ const void *producerPendingAttachment = nullptr; ++ droiddeck::PendingProducerFence producerFence; ++ std::unordered_map committedProducerFences; ++ struct wl_listener producerFenceClientCommit; + }; + + wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf); +diff --git a/src/backend.h b/src/backend.h +index 9a27711..9fe0c15 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -377,6 +377,7 @@ namespace gamescope + virtual bool IsSessionBased() const = 0; + + virtual bool SupportsExplicitSync() const = 0; ++ virtual bool SupportsDroidDeckProducerAcquire() const { return false; } + + // Dumb helper we should remove to support multi display someday. + gamescope::GamescopeScreenType GetScreenType() +diff --git a/src/commit.cpp b/src/commit.cpp +index fbfb550..cd35202 100644 +--- a/src/commit.cpp ++++ b/src/commit.cpp +@@ -55,7 +55,9 @@ void commit_t::OnPollIn() + + { + std::unique_lock lock( m_WaitableCommitStateMutex ); +- if ( !CloseFenceInternal() ) ++ const bool bFailedProducerFence = m_bProducerFence && ++ droiddeck::ProducerFenceStatus(m_nCommitFence) != 1; ++ if ( !CloseFenceInternal() || bFailedProducerFence ) + return; + } + +@@ -115,12 +117,13 @@ bool commit_t::CloseFenceInternal() + return true; + } + +-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame ) ++void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame, bool bProducerFence ) + { + std::unique_lock lock( m_WaitableCommitStateMutex ); + CloseFenceInternal(); + + m_nCommitFence = nFence; ++ m_bProducerFence = bProducerFence; + m_bMangoNudge = bMangoNudge; + m_uMangoMsgType = uMangoMsgType; + m_bDroidDeckHudFrame = bDroidDeckHudFrame; +diff --git a/src/commit.h b/src/commit.h +index ae767b6..99b32ae 100644 +--- a/src/commit.h ++++ b/src/commit.h +@@ -35,13 +35,14 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + // Returns true if we had a fence that was closed. + bool CloseFenceInternal(); +- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame = false ); ++ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr &pDoneCommits, bool bDroidDeckHudFrame = false, bool bProducerFence = false ); + + bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler ); + + struct wlr_buffer *buf = nullptr; + gamescope::Rc vulkanTex; + std::optional upscaledTexture; ++ std::shared_ptr pProducerFence; + + gamescope::Rc GetTexture( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler, GamescopeAppTextureColorspace &colorspace ) + { +@@ -79,6 +80,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable, + + std::mutex m_WaitableCommitStateMutex; + int m_nCommitFence = -1; ++ bool m_bProducerFence = false; + bool m_bMangoNudge = false; + // Typed mangoapp stream to nudge, 0 for none, never the legacy type. + uint32_t m_uMangoMsgType = 0; +diff --git a/src/droiddeck_producer_fence.hpp b/src/droiddeck_producer_fence.hpp +new file mode 100644 +index 0000000..5e7dd9d +--- /dev/null ++++ b/src/droiddeck_producer_fence.hpp +@@ -0,0 +1,67 @@ ++#pragma once ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace droiddeck ++{ ++ inline bool ProducerAcquireEnabled() ++ { ++ static const bool enabled = [] { ++ const char *value = std::getenv("GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE"); ++ return value && std::strcmp(value, "1") == 0; ++ }(); ++ return enabled; ++ } ++ ++ // Status 1 is success, 0 is pending, everything else is unsafe. ++ inline int ProducerFenceStatus(int fd) ++ { ++ sync_file_info info{}; ++ if (fd < 0 || ioctl(fd, SYNC_IOC_FILE_INFO, &info) < 0 || !info.num_fences) ++ return -1; ++ return info.status; ++ } ++ ++ class ProducerFence ++ { ++ public: ++ explicit ProducerFence(int fd) : m_fd(fd) {} ++ ProducerFence(ProducerFence &&other) noexcept : m_fd(other.TakeFd()) {} ++ ProducerFence(const ProducerFence &) = delete; ++ ProducerFence &operator=(const ProducerFence &) = delete; ++ ~ProducerFence() { if (m_fd >= 0) close(m_fd); } ++ ++ int SyncStatus() const { return ProducerFenceStatus(m_fd); } ++ int Dup() const { return m_fd < 0 ? -1 : fcntl(m_fd, F_DUPFD_CLOEXEC, 0); } ++ int SignaledFd() const { return SyncStatus() == 1 ? m_fd : -1; } ++ int Fd() const { return m_fd; } ++ int TakeFd() { return std::exchange(m_fd, -1); } ++ ++ private: ++ int m_fd; ++ }; ++ ++ // This slot belongs to one nested surface and is cleared by *every* ++ // attach request, even if the client reuses the same wl_buffer object. ++ struct PendingProducerFence ++ { ++ std::shared_ptr fence; ++ uint32_t sequence = 0; ++ const void *buffer = nullptr; ++ ++ std::shared_ptr Consume(bool attached, uint32_t seq, const void *current) ++ { ++ auto owned = std::exchange(fence, {}); ++ const bool same = attached && seq == sequence && current && current == buffer; ++ return same ? owned : nullptr; ++ } ++ }; ++} +diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp +index 8ae3b71..235cfc0 100644 +--- a/src/rendervulkan.hpp ++++ b/src/rendervulkan.hpp +@@ -281,6 +281,8 @@ enum AlphaBlendingMode_t + //#define DRM_MODE_BLEND_COVERAGE 1 + //#define DRM_MODE_BLEND_PIXEL_NONE 2 + ++namespace droiddeck { class ProducerFence; } ++ + struct FrameInfo_t + { + bool useFSRLayer0; +@@ -309,6 +311,7 @@ struct FrameInfo_t + struct Layer_t + { + gamescope::Rc tex; ++ std::shared_ptr pProducerFence; + int zpos; + + vec2_t offset; +@@ -378,6 +381,7 @@ struct FrameInfo_t + if ( m_nCount >= k_nMaxLayers ) + return nullptr; + ++ m_Layers[m_nCount].pProducerFence.reset(); + return &m_Layers[ m_nCount++ ]; + } + +diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp +index c2e04ab..f5b744b 100644 +--- a/src/steamcompmgr.cpp ++++ b/src/steamcompmgr.cpp +@@ -2559,6 +2559,7 @@ paint_cached_base_layer(const gamescope::Rc& commit, const BaseLayerIn + + layer->tex = commit->GetTexture( base.eUpscaleFilter, base.eUpscaleScaler, layer->colorspace ); + layer->filter = base.filter; ++ layer->pProducerFence = layer->tex == commit->vulkanTex ? commit->pProducerFence : nullptr; + if ( layer->tex == commit->vulkanTex ) + { + if ( base.uOutputWidth == currentOutputWidth && base.uOutputHeight == currentOutputHeight ) +@@ -2670,6 +2671,7 @@ paint_window_commit( const gamescope::Rc &lastCommit, steamcompmgr_win + layer->filter = ( flags & PaintWindowFlag::NoFilter ) ? GamescopeUpscaleFilter::LINEAR : frameInfo->eUpscaleFilter; + + layer->tex = lastCommit->GetTexture( layer->filter, frameInfo->eUpscaleScaler, layer->colorspace ); ++ layer->pProducerFence = layer->tex == lastCommit->vulkanTex ? lastCommit->pProducerFence : nullptr; + + if ( flags & PaintWindowFlag::NoScale ) + { +@@ -8915,7 +8917,7 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + already_exists = true; + } + +- if ( already_exists && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() ) ++ if ( already_exists && !reslistentry.pProducerFence && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() ) + { + wlserver_lock(); + wlr_buffer_unlock( buf ); +@@ -8957,6 +8959,8 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + droiddeck::frame_trace::Event::ImportSucceededOther, + bTraceCurrent ); + ++ newCommit->pProducerFence = std::move(reslistentry.pProducerFence); ++ const bool bProducerFence = bool(newCommit->pProducerFence); + int fence = -1; + global_focus_t *pCurrentFocus = GetCurrentFocus(); + +@@ -9104,7 +9108,24 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + pBackendFb->SetBuffer( buf ); + } + +- if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent ) ++ if ( bProducerFence ) ++ { ++ const int status = newCommit->pProducerFence->SyncStatus(); ++ if ( status != 0 && status != 1 ) ++ return; // A failed producer write may not be marked ready. ++ bKnownReady = status == 1; ++ if ( !bKnownReady ) ++ { ++ fence = newCommit->pProducerFence->Dup(); ++ if ( fence < 0 ) ++ { ++ // Still wait on original; this commit cannot forward proof. ++ fence = newCommit->pProducerFence->TakeFd(); ++ newCommit->pProducerFence.reset(); ++ } ++ } ++ } ++ else if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent ) + { + fence = eventFd.first; + bKnownReady = eventFd.second; +@@ -9127,13 +9148,13 @@ void update_wayland_res(const std::shared_ptr &doneCommits, st + + if ( cv_commit_ready_check ) + { +- if ( !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) ) ++ if ( !bProducerFence && !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) ) + bKnownReady = true; + note_commit_fence( bKnownReady ); + } + gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 ); + { +- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted() ); ++ newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted(), bProducerFence ); + if ( bKnownReady ) + { + newCommit->Signal(); +diff --git a/src/wlserver.cpp b/src/wlserver.cpp +index 84602c0..6a4f4da 100644 +--- a/src/wlserver.cpp ++++ b/src/wlserver.cpp +@@ -57,6 +57,7 @@ + #include "gamescope-private-protocol.h" + #include "gamescope-swapchain-protocol.h" + #include "presentation-time-protocol.h" ++#include "droiddeck-game-frame-acquire-v1-protocol.h" + + #include "wlserver.hpp" + #include "hdmi.h" +@@ -136,7 +137,8 @@ std::vector& gamescope_xwayland_server_t::retrieve_commits() + + gamescope::ConVar cv_drm_debug_syncobj_force_wait_on_commit( "drm_debug_syncobj_force_wait_on_commit", false, "Force a wait on DRM sync objects before committing buffers" ); + +-ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf ) ++ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf, ++ std::shared_ptr pProducerFence ) + { + auto wl_surf = get_wl_surface_info( surf ); + +@@ -168,7 +170,8 @@ ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf ) + wl_surf->present_id, + wl_surf->desired_present_time, + std::move( pAcquirePoint ), +- std::move( pReleasePoint ) ++ std::move( pReleasePoint ), ++ bExplicitSync ? nullptr : std::move( pProducerFence ) + }; + wl_surf->present_id = std::nullopt; + wl_surf->desired_present_time = 0; +@@ -216,6 +219,12 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) { + ? droiddeck::frame_trace::Event::SurfaceCommitBuffer + : droiddeck::frame_trace::Event::SurfaceCommitNoBuffer ); + ++ // Capture state before the existing damage/attach flags are reset. ++ const bool bAttached = wlr_surface->current.committed & WLR_SURFACE_STATE_BUFFER; ++ auto &proofs = get_wl_surface_info(wlr_surface)->committedProducerFences; ++ auto proof = proofs.extract(wlr_surface->current.seq); ++ auto pProducerFence = proof.empty() ? nullptr : proof.mapped().Consume( ++ bAttached, wlr_surface->current.seq, wlr_surface->current.buffer ); + wlr_surface->current.committed = 0; + + wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface; +@@ -249,7 +258,14 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) { + + gpuvis_trace_printf( "xwayland_surface_commit wlr_surface %p", wlr_surface ); + +- ResListEntry_t entry = PrepareCommit( wlr_surface, buf ); ++ // A texture may still designate older storage after a rejected/no-op import. ++ if ( pProducerFence ) ++ { ++ struct wlr_dmabuf_attributes dmabuf{}; ++ if ( wlr_surface->current.buffer != buf || !wlr_buffer_get_dmabuf(buf, &dmabuf) ) ++ pProducerFence.reset(); ++ } ++ ResListEntry_t entry = PrepareCommit( wlr_surface, buf, std::move(pProducerFence) ); + + if (wlserver_x11_surface_info) + { +@@ -612,6 +628,31 @@ wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf) + return reinterpret_cast(wlr_surf->data); + } + ++// This wlroots signal runs with its own pending.buffer lock, after the ++// pending object has been resolved and before the commit is applied or cached. ++static bool producer_fence_protocol_active(); ++ ++static void handle_producer_fence_client_commit(wl_listener *listener, void *) ++{ ++ wlserver_wl_surface_info *info = wl_container_of(listener, info, producerFenceClientCommit); ++ wlr_surface *surface = info->wlr; ++ info->producerPendingAttachment = nullptr; ++ auto proof = std::exchange(info->producerFence, {}); ++ if (!proof.fence || !surface->pending.buffer || proof.sequence != surface->pending.seq || ++ !(surface->pending.committed & WLR_SURFACE_STATE_BUFFER)) ++ return; ++ struct wlr_dmabuf_attributes dmabuf{}; ++ if (!wlr_buffer_get_dmabuf(surface->pending.buffer, &dmabuf) || ++ info->committedProducerFences.size() >= 64 || ++ info->committedProducerFences.contains(proof.sequence)) ++ { ++ wlr_surface_reject_pending(surface, surface->resource, 0, "invalid or excessive producer fence commits"); ++ return; ++ } ++ proof.buffer = surface->pending.buffer; // Borrowed from the state lock, no extra release path. ++ info->committedProducerFences.emplace(proof.sequence, std::move(proof)); ++} ++ + static void handle_wl_surface_commit( struct wl_listener *l, void *data ) + { + wlserver_wl_surface_info *surf = wl_container_of( l, surf, commit ); +@@ -707,6 +748,7 @@ static void handle_wl_surface_destroy( struct wl_listener *l, void *data ) + } + + wl_list_remove( &surf->commit.link ); ++ wl_list_remove(&surf->producerFenceClientCommit.link); + wl_list_remove( &surf->destroy.link ); + + delete surf; +@@ -725,6 +767,12 @@ static void wlserver_new_surface(struct wl_listener *l, void *data) + + wl_surface_info->commit.notify = handle_wl_surface_commit; + wl_signal_add( &wlr_surf->events.commit, &wl_surface_info->commit ); ++ wl_list_init(&wl_surface_info->producerFenceClientCommit.link); ++ if (producer_fence_protocol_active()) ++ { ++ wl_surface_info->producerFenceClientCommit.notify = handle_producer_fence_client_commit; ++ wl_signal_add(&wlr_surf->events.client_commit, &wl_surface_info->producerFenceClientCommit); ++ } + + wlr_surf->data = wl_surface_info; + +@@ -1811,6 +1859,79 @@ static bool filter_global(const struct wl_client *client, const struct wl_global + return server && server->get_output() == output; + } + ++static wl_protocol_logger *s_pProducerFenceLogger; ++static wl_global *s_pProducerFenceGlobal; ++ ++static bool producer_fence_protocol_active() ++{ ++ return s_pProducerFenceGlobal != nullptr; ++} ++ ++static void producer_fence_protocol_log( void *, wl_protocol_logger_type direction, ++ const wl_protocol_logger_message *message ) ++{ ++ if ( direction != WL_PROTOCOL_LOGGER_REQUEST || std::strcmp(message->message->name, "attach") || ++ std::strcmp(wl_resource_get_class(message->resource), wl_surface_interface.name) || ++ message->arguments_count != 3 ) ++ return; ++ auto *surf = wlr_surface_from_resource(message->resource); ++ if ( auto *info = get_wl_surface_info(surf) ) ++ { ++ info->producerFence = {}; ++ // Wayland's server demarshaller gives the wl_object at the start ++ // of the wl_resource. Compare identity only, never dereference it. ++ info->producerPendingAttachment = message->arguments[0].o; ++ } ++} ++ ++static void set_producer_fence( wl_client *client, wl_resource *manager, wl_resource *surface, ++ wl_resource *buffer, int32_t fd ) ++{ ++ droiddeck::ProducerFence fence(fd); ++ wlr_surface *surf = surface && wl_resource_get_client(surface) == client ++ ? wlr_surface_from_resource(surface) : nullptr; ++ auto *info = get_wl_surface_info(surf); ++ if (!info || !buffer || wl_resource_get_client(buffer) != client || ++ !(surf->pending.committed & WLR_SURFACE_STATE_BUFFER) || ++ info->producerPendingAttachment != buffer || info->producerFence.fence) ++ { ++ wl_resource_post_error(manager, 0, "invalid or duplicate producer fence attachment"); ++ return; ++ } ++ ++ const int status = fence.SyncStatus(); ++ if (status != 0 && status != 1) ++ { ++ wl_resource_post_error(manager, 0, "producer fence requires a real sync_file"); ++ return; ++ } ++ info->producerFence = { std::make_shared(std::move(fence)), ++ surf->pending.seq }; ++} ++ ++static const struct droiddeck_game_frame_acquire_v1_interface producer_fence_impl = { ++ .set_acquire_fence = set_producer_fence, ++}; ++ ++static void bind_producer_fence(wl_client *client, void *, uint32_t, uint32_t id) ++{ ++ auto *resource = wl_resource_create(client, &droiddeck_game_frame_acquire_v1_interface, 1, id); ++ if (!resource) ++ { ++ wl_client_post_no_memory(client); ++ return; ++ } ++ wl_resource_set_implementation(resource, &producer_fence_impl, nullptr, nullptr); ++} ++ ++static void stop_producer_fence_protocol() ++{ ++ if (s_pProducerFenceGlobal) ++ wl_global_destroy(std::exchange(s_pProducerFenceGlobal, nullptr)); ++ if (s_pProducerFenceLogger) ++ wl_protocol_logger_destroy(std::exchange(s_pProducerFenceLogger, nullptr)); ++} ++ + bool wlsession_init( void ) { + static bool s_bInitted = false; + if ( s_bInitted ) +@@ -1824,6 +1945,7 @@ bool wlsession_init( void ) { + + wl_display_set_global_filter(wlserver.display, filter_global, nullptr); + ++ + const struct wlserver_output_info output_info = { + .description = "Virtual gamescope output", + }; +@@ -2200,6 +2322,18 @@ void wlserver_set_keyboard_layout( const char *pszLayout ) + bool wlserver_init( void ) { + assert( wlserver.display != nullptr ); + ++ // The backend has round-tripped its parent registry before wlserver_init. ++ // Older hosts, non-Wayland backends or an unarmed host keep the original ++ // producer conventions: do not advertise this inner protocol at all. ++ if (droiddeck::ProducerAcquireEnabled() && GetBackend()->SupportsDroidDeckProducerAcquire()) ++ { ++ s_pProducerFenceLogger = wl_display_add_protocol_logger(wlserver.display, producer_fence_protocol_log, nullptr); ++ if (s_pProducerFenceLogger) ++ s_pProducerFenceGlobal = wl_global_create(wlserver.display, &droiddeck_game_frame_acquire_v1_interface, 1, nullptr, bind_producer_fence); ++ if (!s_pProducerFenceGlobal) ++ stop_producer_fence_protocol(); ++ } ++ + wl_list_init(&pending_surfaces); + + wlserver.wlr.multi_backend = wlr_multi_backend_create( wlserver.event_loop ); +@@ -2345,6 +2479,7 @@ bool wlserver_init( void ) { + { + wl_log.errorf("Failed to start backend"); + wlr_backend_destroy( wlserver.wlr.multi_backend ); ++ stop_producer_fence_protocol(); + wl_display_destroy(wlserver.display); + return false; + } +@@ -2527,6 +2662,7 @@ void wlserver_run(void) + wl_list_remove( &wlserver.session_active.link ); + #endif + ++ stop_producer_fence_protocol(); + wl_display_destroy_clients(wlserver.display); + wl_display_destroy(wlserver.display); + wlserver.display = NULL; +diff --git a/src/wlserver.hpp b/src/wlserver.hpp +index 63542ef..12141b6 100644 +--- a/src/wlserver.hpp ++++ b/src/wlserver.hpp +@@ -50,6 +50,7 @@ struct ResListEntry_t { + uint64_t desired_present_time; + std::shared_ptr pAcquirePoint; + std::shared_ptr pReleasePoint; ++ std::shared_ptr pProducerFence; + }; + + struct wlserver_content_override; diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index bab97af41f..fbced83679 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-17928792 -GAMESCOPE_SHA256=b25680d5f81c8ba1f3e0f6f49894686a148baa296647c3bf3dafa3a04697b7c8 +GAMESCOPE_TAG=gamescope-3.16.29-verified-acquire-v1 +GAMESCOPE_SHA256=0861b5f6f694842eead87e4fd68f7b3cf93c35f10e1dccffd5ea3fc75081b97d diff --git a/tools/gamescope/tests/producer-acquire.cpp b/tools/gamescope/tests/producer-acquire.cpp new file mode 100644 index 0000000000..f99974a5e5 --- /dev/null +++ b/tools/gamescope/tests/producer-acquire.cpp @@ -0,0 +1,36 @@ +#include "droiddeck_producer_fence.hpp" +#include +#include +#include + +int main() +{ + using namespace droiddeck; + assert(!ProducerAcquireEnabled()); // normal startup, no opt-in + assert(ProducerFenceStatus(-1) < 0); + + int ends[2]; + assert(pipe(ends) == 0); + const int readEnd = ends[0]; + auto fd = std::make_shared(readEnd); + assert(fd->SyncStatus() < 0); // ordinary pipe must never become a ready writer fence + assert(fd->SignaledFd() < 0); + int a, b; + PendingProducerFence old{fd, 21, &a}; + assert(!old.Consume(true, 22, &a)); + assert(!old.fence); + PendingProducerFence different{fd, 21, &a}; + assert(!different.Consume(true, 21, &b)); + PendingProducerFence empty{fd, 21, &a}; + assert(!empty.Consume(false, 21, &a)); + PendingProducerFence matching{std::move(fd), 21, &a}; + auto consumed = matching.Consume(true, 21, &a); + assert(consumed && !matching.Consume(true, 21, &a)); // never clonable across commits + int dup = consumed->Dup(); + assert(dup >= 0 && fcntl(dup, F_GETFD) == FD_CLOEXEC); + consumed.reset(); + assert(fcntl(readEnd, F_GETFD) == -1 && errno == EBADF); + assert(fcntl(dup, F_GETFD) == FD_CLOEXEC); + close(dup); + close(ends[1]); +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 1e02ad4be2..4e56c7b17c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -15,7 +15,7 @@ import tempfile from pathlib import Path GAME_PREFIX = "DROIDDECK_GAME_" -GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR") +GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE") CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"} SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists" diff --git a/tools/tests/frame_worker_peer_live_test.c b/tools/tests/frame_worker_peer_live_test.c new file mode 100644 index 0000000000..87e6ee300e --- /dev/null +++ b/tools/tests/frame_worker_peer_live_test.c @@ -0,0 +1,51 @@ +#define _GNU_SOURCE +#include "frame_worker_peer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +static uint64_t start_ticks(pid_t id) { + char proc[64], line[4096]; snprintf(proc,sizeof(proc),"/proc/%d/stat",id); + FILE *f=fopen(proc,"r");assert(f);assert(fgets(line,sizeof(line),f));fclose(f); + uint64_t ticks=0; + assert(dd_worker_parse_start(line,&ticks)==DD_WORKER_STAT_OK); + return ticks; +} +static bool check_maps(const struct dd_worker_grant *g,pid_t id,uint64_t ticks) { + char proc[64],line[4096];snprintf(proc,sizeof(proc),"/proc/%d/maps",id); + FILE *f=fopen(proc,"r");assert(f);bool found=false; + while(fgets(line,sizeof(line),f)) if(dd_worker_grant_matches(g,4,getuid(),id,ticks,4,line)){ found=true;break;} + fclose(f);return found; +} +int main(void){ + char p[]="/tmp/dd-live-map.XXXXXX";int fd=mkstemp(p);assert(fd>=0); + assert(ftruncate(fd,4096)==0);struct stat st;assert(fstat(fd,&st)==0); + int a[2],b[2];assert(pipe(a)==0&&pipe(b)==0);pid_t id=fork();assert(id>=0); + if(id==0){ + close(a[0]);close(b[1]); + void *m=mmap(NULL,4096,PROT_READ|PROT_EXEC,MAP_PRIVATE,fd,0);assert(m!=MAP_FAILED); + assert(write(a[1],"y",1)==1); + char c;assert(read(b[0],&c,1)==1);assert(mprotect(m,4096,PROT_READ)==0); + assert(write(a[1],"y",1)==1);assert(read(b[0],&c,1)==1);_exit(0); + } + close(a[1]);close(b[0]);char c;assert(read(a[0],&c,1)==1); + int pfd=syscall(SYS_pidfd_open,id,0);assert(pfd>=0); + struct pollfd pfd_poll={.fd=pfd,.events=POLLIN};assert(poll(&pfd_poll,1,0)==0); + uint64_t start=start_ticks(id);assert(start); + struct dd_worker_grant g={.owner=4,.uid=getuid(),.pid=id,.dev_major=major(st.st_dev),.dev_minor=minor(st.st_dev),.ino=st.st_ino,.start_ticks=start,.expires=10,.canonical_file=p,.app_launch_verified=true,.final_go=true}; + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED,0,start+1)); + assert(!check_maps(&g,id,start+1)); // A forged self receipt fails against live post-exec ticks. + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK,start,start)); + assert(check_maps(&g,id,start)); + g.final_go=false;assert(!check_maps(&g,id,start));g.final_go=true; + assert(write(b[1],"n",1)==1);assert(read(a[0],&c,1)==1);assert(!check_maps(&g,id,start)); + assert(write(b[1],"n",1)==1);assert(poll(&pfd_poll,1,2000)==1); + assert(pfd_poll.revents&POLLIN);int status;assert(waitpid(id,&status,0)==id&&WIFEXITED(status)&&WEXITSTATUS(status)==0); + close(fd); close(pfd);unlink(p); puts("Live executable map, start-time reuse rejection, no-GO revocation, non-executable map rejection, and pidfd exit readiness passed."); +} diff --git a/tools/tests/frame_worker_peer_test.c b/tools/tests/frame_worker_peer_test.c new file mode 100644 index 0000000000..a8401aae0d --- /dev/null +++ b/tools/tests/frame_worker_peer_test.c @@ -0,0 +1,48 @@ +#include "frame_worker_peer.h" +#include + +static const char file[]="/app/private/linuxfs/opt/droiddeck-agent/bin/gamescope"; +static const char good[]="1000-2000 r-xp 00001000 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope\n"; +int main(void) { + uint64_t ticks = 0; + assert(dd_worker_parse_start("650 (with ) parens) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 251191 123\n", &ticks) == DD_WORKER_STAT_OK); + assert(ticks == 251191); + assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 0 123\n", &ticks) == DD_WORKER_STAT_ZERO); + assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551616 123\n", &ticks) == DD_WORKER_STAT_PARSE); + assert(dd_worker_parse_start("650 (x) S 1 2 3", &ticks) == DD_WORKER_STAT_PARSE); + assert(dd_worker_open_failure(EACCES) == DD_WORKER_STAT_DENIED); + assert(dd_worker_open_failure(EPERM) == DD_WORKER_STAT_DENIED); + assert(dd_worker_open_failure(ENOENT) == DD_WORKER_STAT_HIDDEN); + assert(dd_worker_open_failure(ESRCH) == DD_WORKER_STAT_HIDDEN); + assert(dd_worker_open_failure(EMFILE) == DD_WORKER_STAT_OPEN); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251191, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251192, 251191)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 251191)); + assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_HIDDEN, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 0)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OPEN, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_READ, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_PARSE, 0, 251191)); + assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_ZERO, 0, 251191)); + struct dd_worker_grant g={.owner=3,.uid=10197,.pid=650,.dev_major=254,.dev_minor=21, + .start_ticks=251191,.ino=5502,.expires=1000,.canonical_file=file,.app_launch_verified=true,.final_go=true}; + assert(dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,1000,good)); + assert(!dd_worker_grant_matches(&g,4,10197,650,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10198,650,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,651,251191,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,650,251192,999,good)); + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,NULL)); + const char *invalid[]={ + "1000-2000 r--p 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope", + "1000-2000 r-xp 0 fe:15 5503 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope", + "1000-2000 r-xp 0 fe:16 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope", + "1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope (deleted)", + "1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope.bak", + "1000-2000 r-xp 0 fe:15 5502 /system/lib64/libddexec.so", "", NULL}; + for (int i=0;invalid[i];i++) assert(!dd_worker_map_matches(&g,invalid[i])); + g.final_go=false; + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); + g.final_go=true; g.app_launch_verified=false; + assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good)); +} diff --git a/tools/tests/subsurface_release_harness.c b/tools/tests/subsurface_release_harness.c index f162e53ce9..74eb818a50 100644 --- a/tools/tests/subsurface_release_harness.c +++ b/tools/tests/subsurface_release_harness.c @@ -26,6 +26,8 @@ struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, v struct wl_resource { struct wl_list listeners; int acquired, releases, errors; }; struct dmabuf_buffer { int unused; }; enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE }; +/* These release fixtures exercise legacy attachments, which own no acquire FD. */ +#define dd_frame_acquire_clear(slot) ((void)0) struct surface { struct wl_list link; struct wl_resource *dmabuf; diff --git a/tools/tests/test_commit_waits_for_client_writes.py b/tools/tests/test_commit_waits_for_client_writes.py index 39b37e93a9..2f31b9aff8 100644 --- a/tools/tests/test_commit_waits_for_client_writes.py +++ b/tools/tests/test_commit_waits_for_client_writes.py @@ -74,6 +74,11 @@ static int poll(struct pollfd *p, unsigned n, int timeout) { } static int fcntl(int fd, int cmd, int arg) { (void)cmd; (void)arg; dup_of[next_dup] = fd; return next_dup++; } static int close(int fd) { closed[fd]++; return 0; } +struct dd_frame_acquire { int fd_plus_one; }; +static void dd_frame_acquire_clear(struct dd_frame_acquire *f) { + if (f->fd_plus_one) close(f->fd_plus_one - 1); + f->fd_plus_one = 0; +} struct wl_event_source { int fd; int (*fd_cb)(int, uint32_t, void *); int (*timer_cb)(void *); void *data; int armed_ms, removed; }; struct wl_event_loop; @@ -121,6 +126,7 @@ struct surface { struct wl_resource *resource, *xdg_toplevel; int toplevel_committed; struct wl_resource *pending_buffer; + struct dd_frame_acquire pending_frame_acquire; struct wl_listener pending_buffer_destroy; int pending_attach, pending_src_set, pending_dst_set, pending_opaque_set; float pending_src[4]; @@ -146,6 +152,7 @@ FUNCTIONS static void surface_state_apply(struct surface *s, struct surface_state *st) { (void)s; + dd_frame_acquire_clear(&st->frame_acquire); applies++; applied_attach = st->attach; applied_buffer = st->attach ? st->buffer : NULL; diff --git a/tools/tests/test_frame_acquire_peer_gate.py b/tools/tests/test_frame_acquire_peer_gate.py new file mode 100644 index 0000000000..e39b41469b --- /dev/null +++ b/tools/tests/test_frame_acquire_peer_gate.py @@ -0,0 +1,81 @@ +"""Focused worker-grant contract; no Android or guest boot required.""" +import os +import sys +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT=Path(__file__).resolve().parents[2] +SRC=ROOT/'app/src/main/cpp/waylandcomp/src' +JAVA=ROOT/'app/src/main/java/com/droiddeck/launcher' + + +class FrameAcquirePeerGateTest(unittest.TestCase): + def test_app_issued_identity_and_executable_mapping(self): + with tempfile.TemporaryDirectory() as tmp: + image=Path(tmp)/'probe' + subprocess.run([os.environ.get('CC','cc'), '-std=c11','-Wall','-Wextra','-Werror', + '-I',str(SRC),str(Path(__file__).with_name('frame_worker_peer_test.c')), + '-o',str(image)],check=True) + subprocess.run([str(image)],check=True,timeout=10) + + @unittest.skipUnless(sys.platform.startswith("linux"), "Requires Linux procfs and pidfd") + def test_live_worker_mapping_starttime_and_revocation(self): + with tempfile.TemporaryDirectory() as tmp: + image = Path(tmp) / "probe" + subprocess.run([os.environ.get("CC", "cc"), "-std=c11", "-Wall", "-Wextra", "-Werror", + "-I", str(SRC), str(Path(__file__).with_name("frame_worker_peer_live_test.c")), + "-o", str(image)], check=True) + subprocess.run([str(image)], check=True, timeout=10) + + def test_publish_before_worker_go_and_require_map_at_bind(self): + workers=(JAVA/'runtime/GuestWorkers.kt').read_text() + broker=workers.split("private fun start(",1)[1].split("private fun takeWarm",1)[0] + check=broker.index("if (stopping() || !confirmed())") + publish=broker.index("FrameAcquireWorkerProbe.publish",check) + self.assertLess(publish,broker.index("Os.write(go[1]",check)) + self.assertIn("if (slot.service === service) startTicks else 0L",broker) + self.assertIn("val size = reply.dataAvail()",broker) + self.assertIn("if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)",broker) + service=workers.split("override fun onTransact",1)[1].split("Handler(",1)[0] + self.assertIn("data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG",service) + self.assertIn("Binder.getCallingUid() == Process.myUid()",service) + self.assertIn("data.dataAvail() == Int.SIZE_BYTES",service) + self.assertIn("reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))",service) + self.assertIn('if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke',workers) + comp=(SRC/'compositor.c').read_text() + bind=comp.split('static void bind_frame_acquire',1)[1].split('#endif',1)[0] + self.assertIn('frame_acquire_peer_allowed(client, true, true)',bind) + self.assertIn('poll(&alive, 1, 0) == 0',comp) + + + def test_admission_diagnostics_are_coarse_bounded_and_probe_only(self): + kt=(JAVA/'runtime/FrameAcquireWorkerProbe.kt').read_text() + comp=(SRC/'compositor.c').read_text() + jni=(SRC/'waylandcomp_jni.c').read_text() + prepare=kt.split('fun prepare(',1)[1].split('fun arm(',1)[0] + match=kt.split('fun match(',1)[1].split('fun publish(',1)[0] + self.assertIn('!WaylandCompositor.frameWorkerProbeEnabled()',prepare) + self.assertIn('context.assets.open("linuxfs" + PATH)',prepare) + self.assertIn('context.assets.open("linuxfs" + SESSION_SCRIPT)',prepare) + svc=(JAVA/'session/SessionService.kt').read_text() + self.assertIn('SessionPrefs.producerAcquireFences(this)',svc) + self.assertIn('nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment',svc) + prefs=(JAVA/'session/SessionPrefs.kt').read_text() + self.assertIn('getBoolean("producerAcquireFences", false)',prefs) + self.assertLess(match.index('?: return null'),match.index('breadcrumb(')) + self.assertIn('"--version" !in argv',match) + self.assertIn('if (reported.add(stage))',kt) + self.assertIn('"worker_admission=" + reason.name',kt) + for name in ('MATCH_ACK','MATCH_OWNER','MATCH_EXPIRED','MATCH_PATH','MATCH_ROOT', + 'MATCH_ARGV','MATCH_FILE','MATCH_DIGEST','QUALIFIED','PUBLISH_TICKET', + 'PUBLISH_RESTAT','PUBLISH_NATIVE','PUBLISH_RECEIPT','RESERVED'): + self.assertIn('Reason.'+name,kt) + self.assertIn(' return JNI_FALSE;\n#endif',jni.split('frameWorkerProbeEnabled(',1)[1]) + self.assertIn('if (!frame_worker_map_reported)',comp) + for name in ('NATIVE_FILE','NATIVE_PIDFD','NATIVE_STAT_OPEN_DENIED','NATIVE_STAT_OPEN_HIDDEN', + 'NATIVE_STAT_OPEN_OTHER','NATIVE_STAT_READ','NATIVE_STAT_PARSE','NATIVE_STAT_ZERO', + 'NATIVE_STAT_MISMATCH','NATIVE_PIDFD_NOT_LIVE','NATIVE_ALREADY_RESERVED', + 'MAP_STARTTIME','MAP_OPEN','MAP_IDENTITY'): + self.assertIn('"worker_admission='+name+'"',comp) diff --git a/tools/tests/test_frame_acquire_protocol.py b/tools/tests/test_frame_acquire_protocol.py new file mode 100644 index 0000000000..a17fa02f78 --- /dev/null +++ b/tools/tests/test_frame_acquire_protocol.py @@ -0,0 +1,166 @@ +"""Exercise production receiver and attachment replacement with Unix FD passing. + +This Linux fixture stubs Wayland resources and only the success/status values of +SYNC_IOC_FILE_INFO. It does not claim a Vulkan or SurfaceFlinger hardware test. +""" +import os +from pathlib import Path +import platform +import subprocess +import tempfile +import unittest + +from test_vk_pending_completion import function + +SRC = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src' +HEAD = r''' +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +static int query_status, query_result; +static unsigned query_count; +static int test_ioctl(int fd, unsigned long request, void *arg) { + assert(fd >= 0 && request == SYNC_IOC_FILE_INFO); + struct sync_file_info *info = arg; + assert(!info->flags && !info->sync_fence_info); + query_count++; + info->status = query_status; + info->num_fences = 1; + return query_result; +} +#define ioctl test_ioctl +#include "frame_acquire.h" +#undef ioctl +#include "wayland-util.h" +void wl_list_init(struct wl_list *list) { list->prev = list->next = list; } +void wl_list_remove(struct wl_list *list) { (void)list; } +struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); }; +struct wl_client { int identity; }; +struct wl_resource { struct wl_client *owner; void *data; int type; unsigned error; }; +struct surface { + struct wl_resource *pending_buffer; + struct wl_listener pending_buffer_destroy; + struct dd_frame_acquire pending_frame_acquire; + int pending_attach; +}; +static int wl_surface_interface, surface_impl; +static int peer_allowed=1; +static int frame_acquire_peer_allowed(const struct wl_client *c, bool verify_exec, bool bind) { (void)c; (void)verify_exec; (void)bind; return peer_allowed; } +static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->owner; } +static void *wl_resource_get_user_data(struct wl_resource *r) { return r->data; } +static int wl_resource_instance_of(struct wl_resource *r, const void *iface, const void *impl) { + assert(iface == &wl_surface_interface && impl == &surface_impl); + return r->type == 1; +} +static int get_dmabuf(struct wl_resource *r) { return r->type == 2; } +static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { (void)r; (void)l; } +static void wl_resource_post_error(struct wl_resource *r, unsigned err, const char *why) { + assert(why && !r->error); + r->error = err+1; +} +''' +TAIL = r''' +/* Real descriptor transfer and sender close; before dispatch, receiver owns it. */ +static int tx(int fd) { + int conn[2]; char byte = 'F'; + assert(socketpair(AF_UNIX, SOCK_DGRAM, 0, conn) == 0); + union { struct cmsghdr a; char bytes[CMSG_SPACE(sizeof(fd))]; } control = {0}; + struct iovec payload = {.iov_base=&byte, .iov_len=1}; + struct msghdr msg = {.msg_iov=&payload, .msg_iovlen=1, .msg_control=control.bytes, + .msg_controllen=sizeof(control.bytes)}; + struct cmsghdr *h = CMSG_FIRSTHDR(&msg); + h->cmsg_len=CMSG_LEN(sizeof(fd)); h->cmsg_level=SOL_SOCKET; h->cmsg_type=SCM_RIGHTS; + memcpy(CMSG_DATA(h), &fd, sizeof(fd)); + assert(sendmsg(conn[0], &msg, 0) == 1); + assert(close(fd) == 0); + memset(&control, 0, sizeof(control)); + assert(recvmsg(conn[1], &msg, MSG_CMSG_CLOEXEC) == 1); + assert(!(msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) && byte == 'F'); + h=CMSG_FIRSTHDR(&msg); + assert(h && h->cmsg_len==CMSG_LEN(sizeof(fd)) && h->cmsg_level==SOL_SOCKET && h->cmsg_type==SCM_RIGHTS); + memcpy(&fd, CMSG_DATA(h), sizeof(fd)); + close(conn[0]); close(conn[1]); + return fd; +} +static int transmit_fd(void) { + int p[2]; assert(pipe(p) == 0); close(p[1]); return tx(p[0]); +} +static void closed(int fd) { + assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF); +} +int main(void) { + struct wl_client client={1}, unrelated={2}; + struct surface s={0}; + struct wl_resource manager={.owner=&client}, surf={.owner=&client,.data=&s,.type=1}; + struct wl_resource buf={.owner=&client,.type=2}, other={.owner=&client,.type=2}; + struct wl_resource wrong_owner={.owner=&unrelated,.type=2}, not_dmabuf={.owner=&client,.type=3}; + int fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(manager.error == 1 && !query_count); closed(fd); + + surface_attach(&client,&surf,&buf,0,0); + struct wl_resource *bad[] = {&other, &wrong_owner, ¬_dmabuf, NULL}; + for (unsigned i=0; i=0 && display_fd!=fd && (fcntl(display_fd,F_GETFD)&FD_CLOEXEC)); + close(display_fd); + int duplicate=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,duplicate); + assert(manager.error==2 && query_count==1); closed(duplicate); + + /* The same Wayland buffer, attached a second time, is a different write. */ + surface_attach(&client,&surf,&buf,0,0); + assert(dd_frame_acquire_dup(&s.pending_frame_acquire)==-1); closed(fd); + for (int status=0; status>=-2; status--) { + manager.error=0; query_status=status; + if (status==-2) query_result=-1; /* non-sync file ioctl failure */ + fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(manager.error == 3 && !s.pending_frame_acquire.fd_plus_one); closed(fd); + } + manager.error=0; query_result=0; query_status=1; + fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(!manager.error); + on_pending_buffer_destroyed(&s.pending_buffer_destroy,NULL); + assert(!s.pending_buffer && !s.pending_frame_acquire.fd_plus_one); closed(fd); + peer_allowed=0; manager.error=0; + surface_attach(&client,&surf,&buf,0,0); + fd=transmit_fd(); + frame_acquire_set(&client,&manager,&surf,&buf,fd); + assert(manager.error==4&&!s.pending_frame_acquire.fd_plus_one);closed(fd); + return 0; +} +''' + + +@unittest.skipUnless(platform.system() == 'Linux', 'Linux sync_file UAPI') +class FrameAcquireProtocolTest(unittest.TestCase): + def test_production_receiver_rejects_invalid_and_keeps_exact_attachment(self): + comp = (SRC / 'compositor.c').read_text() + protocol = (SRC.parent / 'generated/droiddeck-frame-acquire-v1-server-protocol.h').read_text() + errors = protocol.split('enum droiddeck_frame_acquire_v1_error {', 1)[1].split('};', 1)[0] + actual = '\n'.join(function(comp, name) for name in ( + 'on_pending_buffer_destroyed', 'surface_attach', 'frame_acquire_set')) + with tempfile.TemporaryDirectory(prefix='droiddeck-frame-acquire-') as tmp: + probe = Path(tmp) / 'probe.c' + exe = Path(tmp) / 'probe' + probe.write_text(HEAD + '\nenum droiddeck_frame_acquire_v1_error {' + errors + '};\n' + actual + TAIL) + subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-Wall', '-Wextra', + '-Werror', '-Wno-unused-parameter', '-UNDEBUG', '-fsanitize=address,undefined', + '-I', str(SRC), '-I', str(SRC.parent / 'prebuilt/include'), + str(probe), '-o', str(exe)], check=True) + subprocess.run([str(exe)], check=True, timeout=10) diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index b7b658f21b..b927d18694 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -24,6 +24,16 @@ STATE = tempfile.TemporaryDirectory() COMPAT["main"].__globals__["COMPAT_DIR"] = STATE.name +class ProducerAcquireGameEnvironmentTest(unittest.TestCase): + def test_prefixed_opt_in_enters_only_the_game_environment(self): + key = "DROIDDECK_GAME_FRAME_ACQUIRE" + scope = MODULE["GAME_PREFIX"] + key + self.assertEqual({}, MODULE["game_gpu"]({scope: "1"}, keep=True)) + self.assertEqual({key: "1"}, MODULE["game_gpu"]({scope: "1"})) + self.assertEqual({}, MODULE["game_gpu"]({key: "1", scope: ""})) + self.assertEqual({}, MODULE["game_gpu"]({})) + + class SupergiantDotnetReporterTest(unittest.TestCase): def test_allows_the_builtin_mscoree_for_supergiant_reporter(self): game = mock.Mock(files={"basecampbugreporter.native.dll"}) diff --git a/tools/tests/test_zero_copy_acquire_fence.py b/tools/tests/test_zero_copy_acquire_fence.py index 5cae4586cb..8b4259661c 100644 --- a/tools/tests/test_zero_copy_acquire_fence.py +++ b/tools/tests/test_zero_copy_acquire_fence.py @@ -38,6 +38,7 @@ static unsigned g_stat_zero_copy; static int g_export_failed_logged; static struct surface *g_announced; static volatile int64_t g_last_zero_copy_ns; +static int explicit_proof; static int export_ok, exports, presents, presented_acquire, logs, polls; static int fake_ioctl(int fd, unsigned long req, void *arg) { struct droiddeck_dma_buf_sync_file *f = arg; @@ -57,6 +58,13 @@ static int fake_poll(struct pollfd *p, nfds_t n, int timeout) { static int64_t now_ns(void) { return 1; } static void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->slot; } static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; } +static int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) { + assert(s && b); + if (explicit_proof != 1) return explicit_proof ? -2 : -1; + int fd = dup(0); + assert(fd >= 0); + return fd; +} static const void *droiddeck_surface_color(struct surface *s) { (void)s; return NULL; } static void droiddeck_surface_describe(struct surface *s, char *out, size_t n) { (void)s; snprintf(out, n, "game"); } static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++logs; } @@ -79,7 +87,15 @@ static void run(int fd, int can_export, int copyable) { b.slot = &ab; export_ok = can_export; int r = ahb_swapchain_present(&b, &s, 64, 64, draw); - if (fd >= 0 && can_export) { + if (explicit_proof) { + assert(exports == 0 && polls == 0); + if (explicit_proof == 1) { + assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer); + assert(fcntl(presented_acquire, F_GETFD) == -1 && errno == EBADF); + } else { + assert(r == -1 && presents == 0 && !ab.on_layer); + } + } else if (fd >= 0 && can_export) { assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer && g_stat_zero_copy == 1 && polls == 0); } else if (copyable) { assert(r == -1 && presents == 0 && !ab.on_layer && g_stat_zero_copy == 0 && polls == (fd >= 0)); @@ -90,7 +106,8 @@ static void run(int fd, int can_export, int copyable) { } } int main(int argc, char **argv) { - assert(argc == 4); + assert(argc == 5); + explicit_proof = atoi(argv[4]); run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); return 0; } @@ -121,11 +138,18 @@ class ZeroCopyAcquireFenceTest(unittest.TestCase): if built.returncode: raise AssertionError(built.stdout + built.stderr) - def scenario(self, fd, can_export, copyable=1): - result = subprocess.run([str(self.binary), str(fd), str(can_export), str(copyable)], capture_output=True, text=True, + def scenario(self, fd, can_export, copyable=1, explicit_proof=0): + result = subprocess.run([str(self.binary), str(fd), str(can_export), str(copyable), str(explicit_proof)], capture_output=True, text=True, timeout=10) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + def test_explicit_fence_goes_to_display_without_dmabuf_ioctl(self): + self.scenario(5, 0, explicit_proof=1) + + def test_failed_explicit_dup_never_falls_through_to_legacy(self): + self.scenario(5, 1, explicit_proof=2) + self.scenario(5, 0, copyable=0, explicit_proof=2) + def test_exported_fence_goes_to_the_display(self): self.scenario(5, 1) diff --git a/tools/tests/vk_dmabuf_quarantine_test.c b/tools/tests/vk_dmabuf_quarantine_test.c index f4163a4ca7..77f62ab012 100644 --- a/tools/tests/vk_dmabuf_quarantine_test.c +++ b/tools/tests/vk_dmabuf_quarantine_test.c @@ -26,6 +26,8 @@ struct dmabuf_buffer { void *ahb_state; }; enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE }; +/* These release fixtures exercise legacy attachments, which own no acquire FD. */ +#define dd_frame_acquire_clear(slot) ((void)0) struct surface { enum surface_role role; struct surface *parent; From 5a18f69c7e97dd2fd674afca722c48d89b9aebbc Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:54:04 -0500 Subject: [PATCH 8/8] Controls below the game: drop the second-screen bar, Steam and Quick Access under the pad (#3653) * Controls below the game: drop the second-screen bar, Steam and Quick Access under the pad * Test the keys under the unfolded pad instead of the removed bar * Keep a touch drawer button below the game --- .../com/droiddeck/launcher/SessionActivity.kt | 33 ++++++++----------- .../input/ControllerPortraitGeometry.kt | 9 ++++- .../launcher/input/OnScreenLayout.kt | 7 ++++ .../droiddeck/launcher/ui/BottomScreenBar.kt | 18 ++++++++++ .../droiddeck/launcher/ui/SessionOverlay.kt | 7 ++++ .../launcher/input/OnScreenLayoutTest.kt | 14 ++++++++ .../launcher/ui/SecondScreenBarTest.kt | 22 ++++++++++--- 7 files changed, 86 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index e8ac7f836e..f7624434b1 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -230,6 +230,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private var unfoldedPanel by mutableStateOf(null) private var unfoldedColumn: android.widget.LinearLayout? = null + private var unfoldedKeys: View? = null private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var unfoldedDeckPanel by mutableStateOf(null) @@ -2049,6 +2050,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }, unfoldedControls = unfoldedControls, onUnfoldedControls = ::chooseUnfoldedControls, + deckPanel = unfoldedDeckPanel, + onDeckPanel = ::selectDeckPanel, adaptiveSticks = adaptiveSticks.takeIf { unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && !steamTouchInUse }, @@ -4058,7 +4061,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde steamTouchControls?.let { takes(it, it::takesTouchAt) } == true || unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true || unfoldedDeckSurface?.let { takes(it, it::takesTouchAt) } == true || - unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true + unfoldedKeys?.let { takes(it) { _, _ -> true } } == true } override fun dispatchTouchEvent(event: MotionEvent): Boolean { @@ -5102,12 +5105,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val width = rootContentWidth() val height = rootContentHeight() val wanted = controlsBelowWanted() - val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let { - it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt() - } ?: 0 val outputAspect = if (!wanted || SessionState.followScreen) 0f else outputSize().let { it.first.toFloat() / it.second.coerceAtLeast(1) } - val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, outputAspect) + val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, aspect = outputAspect) else FrameLayout.LayoutParams.MATCH_PARENT val params = surfaceView.layoutParams as FrameLayout.LayoutParams if (params.height != gameHeight) { @@ -5124,6 +5124,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (panel != null && (!wanted || panel.dock != dock)) { sessionRoot.removeView(unfoldedColumn) unfoldedColumn = null + unfoldedKeys = null unfoldedDeckSurface = null unfoldedDeckPanel = null unfoldedPanel = null @@ -5135,13 +5136,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) } val column = android.widget.LinearLayout(this).apply { orientation = android.widget.LinearLayout.VERTICAL - addView(unfoldedBar().apply { - addOnLayoutChangeListener { _, _, top, _, bottom, _, oldTop, _, oldBottom -> - if (bottom - top != oldBottom - oldTop) post { applyUnfoldedControls() } - } - }, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, - android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)) addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) + unfoldedKeys = com.droiddeck.launcher.ui.padKeysView( + this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM, + { releasePads(); drawerOpen = true }, ::tapSteamButton, ::tapQam, + ).also { + addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, + android.widget.LinearLayout.LayoutParams.WRAP_CONTENT)) + } } sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1) unfoldedColumn = column @@ -5152,13 +5154,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM) } - private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) { - val deck = unfoldedDeckPanel - com.droiddeck.launcher.ui.sessionBarModel(getString(if (deck != null) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad), - { chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam, - tabs = deck?.let { com.droiddeck.launcher.ui.deckPanelTabs(this, it, ::selectDeckPanel) }) - } - private fun showUnfoldedDeckPanel() { val column = unfoldedColumn val panel = unfoldedPanel @@ -5174,7 +5169,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde panel.visibility = View.GONE unfoldedDeckSurface = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, layout.elements, InputRole.PRIMARY, layout.style, haptics = true).also { it.tag = layout - column.addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) + column.addView(it, column.indexOfChild(panel) + 1, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt index 907d71c70d..d6958f7b17 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPortraitGeometry.kt @@ -46,7 +46,14 @@ internal class ControllerPortraitGeometry( } row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit) var bodyTop = top + pad + buttonHeight + gap - if (presented.any { it.control in REAR && isStock(it) }) { + if (presented.any { it.control in REAR && isStock(it) } && docked) { + val chipHeight = 36f * unit + val cell = (w - 2f * pad - 5f * gap) / 6f + listOf(0, 1, 4, 5).zip(REAR).forEach { (index, control) -> + put(control, Box(safe.left + pad + cell / 2f + index * (cell + gap), bodyTop + chipHeight / 2f, cell, chipHeight)) + } + bodyTop += chipHeight + gap + } else if (presented.any { it.control in REAR && isStock(it) }) { val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight) row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap) bodyTop += rearHeight + gap diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index e8490f624f..88ecec5fc7 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -36,6 +36,13 @@ object OnScreenLayout { fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect, buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null, trackpads: Boolean? = null): List { + val placed = placeElements(context, saved, width, height, safe, buttonsOnly, dock, rearButtons, trackpads) + // Below the game a stick covers nothing, so it keeps its base in view instead of appearing only under the thumb. + return if (dock == null) placed else placed.map { if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false) else it } + } + + private fun placeElements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect, + buttonsOnly: Boolean, dock: Dock?, rearButtons: Boolean?, trackpads: Boolean?): List { if (saved == null) return emptyList() if (width <= 0 || height <= 0) return saved.elements val layout = oriented(saved, dock?.portrait ?: (height > width)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt index fe66a06396..1524da8b92 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt @@ -338,6 +338,24 @@ internal fun sessionBarModel( internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) = BarTabs(DeckPanel.entries.map { context.getString(it.label) }, selected.ordinal) { onSelect(DeckPanel.entries[it]) } +internal fun padKeysView( + context: Context, steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit, +): ComposeView = ComposeView(context).apply { + setContent { DroidDeckTheme { PadKeys(steam, onMenu, onSteam, onQam) } } +} + +@Composable +internal fun PadKeys(steam: Boolean, onMenu: () -> Unit, onSteam: () -> Unit, onQam: () -> Unit) { + Row( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = if (steam) Arrangement.SpaceBetween else Arrangement.Center, + ) { + if (steam) BarActions(null, false, onSteam, null) + BarActions(onMenu, false, null, null) + if (steam) BarActions(null, false, null, onQam) + } +} + internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply { setContent { DroidDeckTheme { BottomScreenBar(model()) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 8791d880d2..9402e8396b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -390,6 +390,8 @@ class DrawerActions( val quickButtons: Map = emptyMap(), val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> }, val onUnfoldedControls: (Boolean) -> Unit = {}, + val deckPanel: com.droiddeck.launcher.input.DeckPanel? = null, + val onDeckPanel: (com.droiddeck.launcher.input.DeckPanel) -> Unit = {}, val unfoldedControlsWithController: Boolean = false, val onUnfoldedControlsWithController: (Boolean) -> Unit = {}, val onShareLogs: () -> Unit, @@ -768,6 +770,11 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, chipModifier = track("unfolded-controls"), onChange = a.onUnfoldedControls) + a.deckPanel?.let { panel -> + ChoiceRow(host, "deck-panel", stringResource(R.string.ctrl_layout), null, + com.droiddeck.launcher.input.DeckPanel.entries.map { it to stringResource(it.label) }, panel, + chipModifier = track("deck-panel"), onPick = a.onDeckPanel) + } if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller", stringResource(R.string.unfolded_controls_with_controller), stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController, diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index 3b02f4db38..ba74358841 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -506,6 +506,20 @@ class OnScreenLayoutTest { } } + @Test fun controlsBelowTheGameKeepRearButtonsAtTheEdgesAndSticksInView() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val w = 1216 + val placed = OnScreenLayout.elements(context, gamepad(), w, 1900, Rect(), dock = OnScreenLayout.Dock.deck(true, null)) + fun centre(control: InputControl) = placed.single { it.control == control }.let { it.x + it.width / 2f } + assertTrue(centre(InputControl.L4) < centre(InputControl.L5)) + assertTrue(centre(InputControl.L5) < .5f && centre(InputControl.R5) > .5f) + assertTrue(centre(InputControl.R5) < centre(InputControl.R4)) + val shoulder = placed.single { it.control == InputControl.LB } + assertTrue(placed.filter { it.control in setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) } + .all { it.width < shoulder.width }) + assertTrue(placed.filter { it.kind == InputElementKind.STICK }.none { it.hideWhenIdle }) + } + private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1" private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt index 2239382b37..f9f1979206 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenBarTest.kt @@ -297,9 +297,23 @@ class SecondScreenBarTest { } finally { panel()?.closeControls() } } - @Test fun unfoldedControlsGetTheSessionBar() { - SessionState.mode = SessionService.MODE_STEAM - val activity = Robolectric.buildActivity(SessionActivity::class.java).get() - assertTrue(ReflectionHelpers.callInstanceMethod(activity, "unfoldedBar") is ComposeView) + @Test fun unfoldedPadHasSteamQuickAccessAndDrawerWithoutTheSecondScreenBar() { + val actions = mutableListOf() + compose.setContent { DroidDeckTheme { PadKeys(true, { actions += "menu" }, { actions += "steam" }, { actions += "qam" }) } } + compose.onNodeWithTag("bottom-bar-tabs").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-close").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-steam").assertIsDisplayed().performClick() + compose.onNodeWithTag("bottom-bar-menu").assertIsDisplayed().performClick() + compose.onNodeWithTag("bottom-bar-qam").assertIsDisplayed().performClick() + assertEquals(listOf("steam", "menu", "qam"), actions) + } + + @Test fun unfoldedPadKeepsTheDrawerReachableOutsideSteam() { + var drawerOpened = false + compose.setContent { DroidDeckTheme { PadKeys(false, { drawerOpened = true }, {}, {}) } } + compose.onNodeWithTag("bottom-bar-steam").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-qam").assertDoesNotExist() + compose.onNodeWithTag("bottom-bar-menu").assertIsDisplayed().performClick() + assertTrue(drawerOpened) } }