From a4e6279a8d29a6723f891c62690f4cfa5c1876c2 Mon Sep 17 00:00:00 2001 From: Ben Pfeiffer Date: Fri, 9 Oct 2026 02:51:29 +0000 Subject: [PATCH 01/80] feat(gpu): add Snapdragon X Elite and Adreno X1-85 detection --- .../droiddeck/launcher/core/DeviceSupport.kt | 5 ++++- .../com/droiddeck/launcher/gpu/GpuInfo.kt | 21 +++++++++++++++---- .../com/droiddeck/launcher/gpu/SocNames.kt | 7 +++++++ .../launcher/gpu/GpuModelFallbackTest.kt | 14 +++++++++++++ .../droiddeck/launcher/gpu/SocNamesTest.kt | 6 ++++++ 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index 4170d69f17..e621372380 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -16,7 +16,10 @@ import java.io.File */ object DeviceSupport { fun adreno(): Boolean = - File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() + File("/sys/class/kgsl/kgsl-3d0").exists() + || File("/vendor/lib64/hw/vulkan.adreno.so").exists() + || File("/sys/bus/platform/drivers/msm_drm").exists() + || File("/sys/class/drm/renderD128").exists() /** The chip as the device names it, for the card that explains the refusal. */ fun gpuName(context: Context): String { diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index 87bf01d4dd..64b5a76e39 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -76,16 +76,16 @@ data class GpuInfo( private const val UNNAMED = "this GPU" fun detect(): GpuInfo { - val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() + val adreno = com.droiddeck.launcher.core.DeviceSupport.adreno() val raw = listOf("/sys/class/kgsl/kgsl-3d0/gpu_model", "/sys/class/kgsl/kgsl-3d0/gpu_chipid") .firstNotNullOfOrNull { FileUtils.readString(File(it))?.trim()?.takeIf(String::isNotEmpty) } // Where vendors put the chip's model, named when it is known: "Snapdragon 8 Gen 2 (QCS8550)". val soc = if (adreno) SocNames.label() else "" - val fromKernel = raw?.let { threeDigits(it) } ?: 0 + val fromKernel = raw?.let { parseModel(it) } ?: 0 // Some kernels name the GPU without its model (AYANEO's Pocket FIT: "Adreno33v2"). The // Vulkan driver's own name, when this process has asked it, then the platform's code // name stand in - the GPU is the same on every phone of a platform. - val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { threeDigits(it) } ?: 0 + val fromVulkan = if (fromKernel > 0 || !adreno) 0 else VulkanInfo.cachedOrNull()?.get("device")?.let { parseModel(it) } ?: 0 val fromPlatform = if (fromKernel > 0 || fromVulkan > 0 || !adreno) 0 else platformModel() val model = maxOf(fromKernel, fromVulkan, fromPlatform) val source = when { @@ -96,20 +96,33 @@ data class GpuInfo( } val family = familyOf(adreno, model) val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) + val isX1 = model == 741 || raw?.contains("X1-", ignoreCase = true) == true + val gpuDisplayName = when { + !adreno -> Build.HARDWARE.ifBlank { UNNAMED } + isX1 -> "Adreno X1-85" + model > 0 -> "Adreno $model" + else -> "Adreno" + } return GpuInfo( - name = if (!adreno) Build.HARDWARE.ifBlank { UNNAMED } else if (model > 0) "Adreno $model" else "Adreno", + name = gpuDisplayName, model = model, family = family, soc = soc, oneUi8Gen2 = samsung && model == 740, kgslName = raw.orEmpty(), modelSource = source, ) } + internal fun parseModel(text: String): Int { + if (Regex("""(?i)X1[-_]85|X1[-_]45|Adreno\s*741""").containsMatchIn(text)) return 741 + return threeDigits(text) + } + private fun threeDigits(text: String): Int = Regex("""(\d{3})""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0 /** Qualcomm platform code names whose GPU is known for certain. */ private val PLATFORMS = mapOf( "msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730, "kalama" to 740, "pineapple" to 750, "sun" to 830, + "hamoa" to 741, "sc8380xp" to 741, "x1e80100" to 741, "purwa" to 741, ) internal fun platformModel(platform: String = systemProperty("ro.board.platform")): Int = diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt index 76adb4bf2d..5c20bc672a 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt @@ -17,6 +17,11 @@ object SocNames { "SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5", "SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3", "SM6375" to "Snapdragon 695", + "SC8380XP" to "Snapdragon X Elite", "X1E80100" to "Snapdragon X Elite", "X1E-80-100" to "Snapdragon X Elite", + "X1E84100" to "Snapdragon X Elite", "X1E-84-100" to "Snapdragon X Elite", + "X1E78100" to "Snapdragon X Elite", "X1E-78-100" to "Snapdragon X Elite", + "X1P64100" to "Snapdragon X Plus", "X1P-64-100" to "Snapdragon X Plus", + "X1P42100" to "Snapdragon X Plus", "X1P-42-100" to "Snapdragon X Plus", ) /** Platform code names: every chip of one platform shares its CPU and GPU design. */ @@ -24,6 +29,8 @@ object SocNames { "msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888", "taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2", "pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite", + "hamoa" to "Snapdragon X Elite", "purwa" to "Snapdragon X Plus", + "sc8380xp" to "Snapdragon X Elite", "x1e80100" to "Snapdragon X Elite", ) /** The chip's model code ("QCS8550", "SG8350P"), or "" when the phone does not say. */ diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt index 10a0fd971d..abbb787b54 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt @@ -9,7 +9,21 @@ class GpuModelFallbackTest { assertEquals(750, GpuInfo.platformModel("pineapple")) assertEquals(740, GpuInfo.platformModel("KALAMA")) assertEquals(830, GpuInfo.platformModel("sun")) + assertEquals(741, GpuInfo.platformModel("hamoa")) + assertEquals(741, GpuInfo.platformModel("sc8380xp")) + assertEquals(741, GpuInfo.platformModel("x1e80100")) + assertEquals(741, GpuInfo.platformModel("purwa")) assertEquals(0, GpuInfo.platformModel("somethingelse")) assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple"))) + assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("hamoa"))) + } + + @Test fun alphanumericModelNamesAreParsed() { + assertEquals(741, GpuInfo.parseModel("Adreno X1-85")) + assertEquals(741, GpuInfo.parseModel("Adreno(TM) X1-85")) + assertEquals(741, GpuInfo.parseModel("X1-45")) + assertEquals(741, GpuInfo.parseModel("Adreno 741")) + assertEquals(750, GpuInfo.parseModel("Adreno750")) + assertEquals(0, GpuInfo.parseModel("unknown")) } } diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt index d90e261d05..7bf8a59b99 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt @@ -17,9 +17,15 @@ class SocNamesTest { @Test fun knownModelsAndPlatformsGetTheirNames() { assertEquals("Snapdragon 8 Gen 2", SocNames.name("QCS8550", "")) assertEquals("Snapdragon 8 Gen 3 family", SocNames.name("SG8350P", "pineapple")) + assertEquals("Snapdragon X Elite", SocNames.name("SC8380XP", "")) + assertEquals("Snapdragon X Elite", SocNames.name("X1E80100", "")) + assertEquals("Snapdragon X Elite family", SocNames.name("other", "hamoa")) + assertEquals("Snapdragon X Plus family", SocNames.name("other", "purwa")) assertNull(SocNames.name("XYZ123", "nowhere")) assertEquals("Snapdragon 8 Gen 2 (QCS8550)", SocNames.label("QCS8550", "")) assertEquals("Snapdragon 8 Gen 3 family (SG8350P)", SocNames.label("SG8350P", "pineapple")) + assertEquals("Snapdragon X Elite (SC8380XP)", SocNames.label("SC8380XP", "hamoa")) + assertEquals("Snapdragon X Elite family (other)", SocNames.label("other", "hamoa")) assertEquals("XYZ123", SocNames.label("XYZ123", "")) } } From 2b424bdfe7686f5a427d5f8ecc1bcc42c4bb14e9 Mon Sep 17 00:00:00 2001 From: Ben Pfeiffer Date: Sat, 10 Oct 2026 17:22:07 +0000 Subject: [PATCH 02/80] feat(gpu): default to nolrz and nolrzfc on Adreno X1-85 to prevent depth dithering Turnip's Low-Resolution Z (LRZ / early-Z) depth tile cache can desynchronize on Adreno 741 (X1-85 / X1-45), leading to checkerboard or dithering depth artifacts in 3D titles and Vulkan presentation. Default TU_DEBUG to 'nolrz,nolrzfc' on GPU model 741 in both GameEnvironment defaults (Proton games) and SessionService (Gamescope/Steam session), while preserving user overrides. --- .../launcher/core/GameEnvironment.kt | 15 ++++++-- .../launcher/session/SessionService.kt | 35 ++++++++++++++++--- .../launcher/core/GameEnvironmentTest.kt | 10 ++++++ .../launcher/session/SessionTuDebugTest.kt | 33 +++++++++++++++++ 4 files changed, 85 insertions(+), 8 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt index a03f31d945..b2a8611f4e 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.core +import com.droiddeck.launcher.gpu.GpuInfo + object GameEnvironment { data class Config( val shared: Map = emptyMap(), @@ -25,7 +27,7 @@ object GameEnvironment { fun validValue(value: String) = '\u0000' !in value && value.length <= 8192 fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true) - fun defaults(preset: String, forceSsbs: Boolean = false): Map = linkedMapOf( + fun defaults(preset: String, forceSsbs: Boolean = false, gpuModel: Int = GpuInfo.detect().model): Map = linkedMapOf( "MESA_SHADER_CACHE_DISABLE" to "false", "VKD3D_FEATURE_LEVEL" to "12_2", "VKD3D_SHADER_MODEL" to "6_9", @@ -39,10 +41,17 @@ object GameEnvironment { FexPreset.env(preset).forEach { put(it.substringBefore('='), it.substringAfter('=')) } // Steam settings' Force SSBS: droiddeck-game-env preloads libssbs.so into the game's Wine. if (forceSsbs) put(FORCE_SSBS, "1") + if (gpuModel == 741) put("TU_DEBUG", "nolrz,nolrzfc") } const val FORCE_SSBS = "DROIDDECK_FORCE_SSBS" - fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map = - defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty() + fun effective( + config: Config, + preset: String, + scope: String, + forceSsbs: Boolean = false, + gpuModel: Int = GpuInfo.detect().model, + ): Map = + defaults(preset, forceSsbs, gpuModel) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 69d4ea65ee..affe0cf63d 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.session +import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager @@ -300,11 +301,17 @@ class SessionService : Service() { private fun tuDebug(linuxDriverId: String): String? { val override = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH) .takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() } - if (!override.isNullOrEmpty()) return override - if (SessionPrefs.tuSysmem(this)) return "sysmem" - if (linuxDriverId.isEmpty()) return null - val name = LinuxVulkanDriverManager(this).getDriverName(linuxDriverId).lowercase() - return if (name.contains("710-720") || name.contains("710_720")) "sysmem" else null + val driverName = if (linuxDriverId.isNotEmpty()) { + LinuxVulkanDriverManager(this).getDriverName(linuxDriverId).lowercase() + } else { + "" + } + return tuDebugFor( + override = override, + tuSysmem = SessionPrefs.tuSysmem(this), + driverName = driverName, + gpuModel = GpuInfo.detect().model + ) } // ── The session ───────────────────────────────────────────────────────────────────────── @@ -1708,6 +1715,24 @@ class SessionService : Service() { private const val TRACER_NICE = -6 /** Downloads file whose contents become TU_DEBUG inside the session, e.g. "sysmem". */ private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug" + + internal fun tuDebugFor( + override: String?, + tuSysmem: Boolean, + driverName: String, + gpuModel: Int = GpuInfo.detect().model + ): String? { + if (!override.isNullOrEmpty()) return override + val flags = mutableListOf() + if (tuSysmem || driverName.contains("710-720") || driverName.contains("710_720")) { + flags.add("sysmem") + } + if (gpuModel == 741) { + flags.add("nolrz") + flags.add("nolrzfc") + } + return if (flags.isNotEmpty()) flags.joinToString(",") else null + } /** * Where droiddeck-env (KEY=VALUE lines added to the session environment verbatim) used to * be. Ignored now: a line there reaches the Steam client's environment as written diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt index aacfcfb20b..ede82180c5 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -86,4 +86,14 @@ class GameEnvironmentTest { assertTrue(GameEnvironment.validScope("4294967295")) for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope)) } + + @Test fun tuDebugDefaultsToNolrzOnAdrenoX185() { + assertEquals("nolrz,nolrzfc", GameEnvironment.defaults("", gpuModel = 741)["TU_DEBUG"]) + assertNull(GameEnvironment.defaults("", gpuModel = 740)["TU_DEBUG"]) + assertNull(GameEnvironment.defaults("", gpuModel = 825)["TU_DEBUG"]) + + // User override in shared or game profile should override the default + val config = GameEnvironment.Config(shared = mapOf("TU_DEBUG" to "noubwc")) + assertEquals("noubwc", GameEnvironment.effective(config, "", "42", gpuModel = 741)["TU_DEBUG"]) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt new file mode 100644 index 0000000000..41402007c2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt @@ -0,0 +1,33 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class SessionTuDebugTest { + @Test fun overrideFileWinsOverEverything() { + assertEquals("noubwc", SessionService.tuDebugFor("noubwc", tuSysmem = true, driverName = "710-720", gpuModel = 741)) + } + + @Test fun x185DefaultsToNolrzAndNolrzfc() { + assertEquals("nolrz,nolrzfc", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "", gpuModel = 741)) + } + + @Test fun a710FamilyGetsSysmem() { + assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "Turnip-v24-710-720", gpuModel = 730)) + assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "Turnip_710_720", gpuModel = 730)) + } + + @Test fun tuSysmemPreferenceAddsSysmem() { + assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = true, driverName = "", gpuModel = 740)) + } + + @Test fun combinesSysmemAndNolrzWhenBothApply() { + assertEquals("sysmem,nolrz,nolrzfc", SessionService.tuDebugFor(override = null, tuSysmem = true, driverName = "", gpuModel = 741)) + } + + @Test fun otherGpusDefaultToNull() { + assertNull(SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "turnip-v24", gpuModel = 740)) + assertNull(SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "turnip-v24", gpuModel = 825)) + } +} From 74a77c1402f4455ca860894a0addcccdb95743aa Mon Sep 17 00:00:00 2001 From: xXJsonDeruloXx Date: Sun, 18 Oct 2026 17:49:52 -0400 Subject: [PATCH 03/80] fix: keep the GPU hardware fallback non-null when Build.HARDWARE is unset --- app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index 2a57e50d75..b759da86a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -78,7 +78,7 @@ data class GpuInfo( val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) val isX1 = model == 741 || raw?.contains("X1-", ignoreCase = true) == true val gpuDisplayName = when { - !adreno -> Build.HARDWARE.ifBlank { UNNAMED } + !adreno -> (Build.HARDWARE ?: "").ifBlank { UNNAMED } isX1 -> "Adreno X1-85" model > 0 -> "Adreno $model" else -> "Adreno" From 2f16ea63aa94b2ac69aaedb8908f3222a712631d Mon Sep 17 00:00:00 2001 From: Ben Pfeiffer Date: Sat, 24 Oct 2026 00:31:49 +0000 Subject: [PATCH 04/80] fix(gpu): distinguish Adreno X1-45 and remove generic renderD128 check - Distinguish Adreno X1-45 (Snapdragon X Plus / purwa) from Adreno X1-85 (Snapdragon X Elite / hamoa) in GpuInfo, falling back to neutral 'Adreno X1' when the exact variant is unspecified. - Remove generic /sys/class/drm/renderD128 check from DeviceSupport.adreno() so non-Qualcomm DRM GPUs are not erroneously marked as Adreno. - Add unit tests verifying X1 variant name resolution. --- .../droiddeck/launcher/core/DeviceSupport.kt | 1 - .../com/droiddeck/launcher/gpu/GpuInfo.kt | 24 +++++++++++++++---- .../launcher/gpu/GpuModelFallbackTest.kt | 14 +++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index 2a482aa757..8913128294 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -10,7 +10,6 @@ object DeviceSupport { File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() || File("/sys/bus/platform/drivers/msm_drm").exists() - || File("/sys/class/drm/renderD128").exists() fun gpuName(context: Context): String { val soc = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it.isNotBlank() && it != Build.UNKNOWN } else null diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index 6553bbbfd5..7683f6116e 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -71,18 +71,20 @@ data class GpuInfo( val raw = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_model"))?.trim() val chipId = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))?.trim().orEmpty() val soc = if (adreno) SocNames.label() else "" - val platformGpuModel = if (adreno) platformModel() else 0 + val platform = systemProperty("ro.board.platform").ifBlank { systemProperty("ro.vendor.qti.soc_name") } + val platformGpuModel = if (adreno) platformModel(platform = platform) else 0 + val vulkan = VulkanInfo.cachedOrNull()?.get("device") val (model, source) = if (adreno) modelFromNames( raw, - { VulkanInfo.cachedOrNull()?.get("device") }, + { vulkan }, { platformGpuModel }, ) else 0 to "" val family = familyOf(adreno, model) val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) - val isX1 = model == 741 || raw?.contains("X1-", ignoreCase = true) == true + val isX1 = model == 741 || Regex("""(?i)X1[-_](?:85|45)""").containsMatchIn(raw.orEmpty()) val gpuDisplayName = when { !adreno -> (Build.HARDWARE ?: "").ifBlank { UNNAMED } - isX1 -> "Adreno X1-85" + isX1 -> x1Name(raw, vulkan, platform) model > 0 -> "Adreno $model" else -> "Adreno" } @@ -100,6 +102,20 @@ data class GpuInfo( return threeDigits(text) } + internal fun x1Name( + raw: String? = null, + vulkan: String? = null, + platform: String = "", + ): String { + val names = listOfNotNull(raw, vulkan).joinToString(" ") + val p = platform.lowercase() + return when { + Regex("""(?i)X1[-_]45""").containsMatchIn(names) || p == "purwa" -> "Adreno X1-45" + Regex("""(?i)X1[-_]85""").containsMatchIn(names) || p in listOf("hamoa", "sc8380xp", "x1e80100") -> "Adreno X1-85" + else -> "Adreno X1" + } + } + internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0 internal fun modelFromNames( diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt index 6dc43716bb..4507dc399d 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt @@ -25,6 +25,20 @@ class GpuModelFallbackTest { assertEquals(750, GpuInfo.parseModel("Adreno750")) assertEquals(0, GpuInfo.parseModel("unknown")) } + + @Test fun x1VariantNamesAreDistinguished() { + assertEquals("Adreno X1-85", GpuInfo.x1Name(raw = "Adreno X1-85")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(vulkan = "Adreno(TM) X1-85")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "hamoa")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "sc8380xp")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "x1e80100")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(raw = "Adreno X1-45")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(vulkan = "Adreno(TM) X1-45")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(platform = "purwa")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(raw = "X1-45", platform = "hamoa")) + assertEquals("Adreno X1", GpuInfo.x1Name(raw = "Adreno 741", platform = "unknown")) + assertEquals("Adreno X1", GpuInfo.x1Name()) + } @Test fun sm8975IsTheOnlyNewSocFallback() { assertEquals(850, GpuInfo.platformModel("unknown", "", "SM8975")) assertEquals(850, GpuInfo.platformModel("unknown", "", "QTI SM8975")) From 1a7a116939ef441d2c5a745d53191220eef1a816 Mon Sep 17 00:00:00 2001 From: JRAlmonte <89419177+JRAlmonte@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:48:36 -0500 Subject: [PATCH 05/80] feat(ui): add frosted launcher wallpaper and cards (#3559) Add opt-in frosted wallpaper and cards with separate transparency settings. Keep dialogs solid and fall back to the standard palette when blur or readable contrast is unavailable. --- .../droiddeck/launcher/ui/LauncherPreviews.kt | 53 ++++++ .../droiddeck/launcher/FrontEndActivity.kt | 57 +++++- .../launcher/session/SessionPrefs.kt | 33 ++++ .../launcher/session/SettingsReset.kt | 2 +- .../droiddeck/launcher/ui/FrontEndScreen.kt | 13 +- .../droiddeck/launcher/ui/FrontEndSetup.kt | 32 +++- .../com/droiddeck/launcher/ui/GlideWindows.kt | 6 +- .../droiddeck/launcher/ui/LauncherFrost.kt | 130 ++++++++++++++ .../droiddeck/launcher/ui/SettingsIndex.kt | 9 +- .../droiddeck/launcher/ui/SettingsSearch.kt | 4 +- .../droiddeck/launcher/ui/SettingsWidgets.kt | 4 +- .../java/com/droiddeck/launcher/ui/StepOut.kt | 17 +- .../java/com/droiddeck/launcher/ui/Theme.kt | 36 ++-- .../com/droiddeck/launcher/ui/ThemeColors.kt | 4 +- app/src/main/res/values-ar/strings.xml | 10 ++ app/src/main/res/values-b+es+419/strings.xml | 10 ++ app/src/main/res/values-bg/strings.xml | 10 ++ app/src/main/res/values-cs/strings.xml | 10 ++ app/src/main/res/values-da/strings.xml | 10 ++ app/src/main/res/values-de/strings.xml | 10 ++ app/src/main/res/values-el/strings.xml | 10 ++ app/src/main/res/values-es/strings.xml | 10 ++ app/src/main/res/values-fi/strings.xml | 10 ++ app/src/main/res/values-fr/strings.xml | 10 ++ app/src/main/res/values-hi/strings.xml | 10 ++ app/src/main/res/values-hu/strings.xml | 10 ++ app/src/main/res/values-in/strings.xml | 10 ++ app/src/main/res/values-it/strings.xml | 10 ++ app/src/main/res/values-ja/strings.xml | 10 ++ app/src/main/res/values-ko/strings.xml | 10 ++ app/src/main/res/values-ms/strings.xml | 10 ++ app/src/main/res/values-nb/strings.xml | 10 ++ app/src/main/res/values-nl/strings.xml | 10 ++ app/src/main/res/values-pl/strings.xml | 10 ++ app/src/main/res/values-pt-rPT/strings.xml | 10 ++ app/src/main/res/values-pt/strings.xml | 10 ++ app/src/main/res/values-ro/strings.xml | 10 ++ app/src/main/res/values-ru/strings.xml | 10 ++ app/src/main/res/values-sv/strings.xml | 10 ++ app/src/main/res/values-th/strings.xml | 10 ++ app/src/main/res/values-tr/strings.xml | 10 ++ app/src/main/res/values-uk/strings.xml | 10 ++ app/src/main/res/values-vi/strings.xml | 10 ++ app/src/main/res/values-zh-rCN/strings.xml | 10 ++ app/src/main/res/values-zh-rHK/strings.xml | 10 ++ app/src/main/res/values-zh-rTW/strings.xml | 10 ++ app/src/main/res/values/strings.xml | 10 ++ .../launcher/ui/LauncherFrostTest.kt | 166 ++++++++++++++++++ docs/compose-previews.md | 4 +- docs/development/themes.md | 34 ++++ docs/settings-map.md | 1 + 51 files changed, 907 insertions(+), 28 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index 0ab0ab8216..05d9559271 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -1,13 +1,17 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.material.icons.filled.Settings import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import com.droiddeck.launcher.R import com.droiddeck.launcher.input.SecondScreenMode @@ -26,6 +30,50 @@ private fun Launcher(tab: String, games: List Unit) = + DroidDeckTheme(frost = FrostChoice(transparency, cards, cardTransparency)) { + val wallpaper = Brush.linearGradient(listOf(Color(0xFFE2725B), Color(0xFF7A4BC2), Color(0xFF2A9D8F))) + Box(Modifier.fillMaxSize().background(wallpaper).background(LocalFrost.current ?: Color.Transparent)) { content() } + } + +@Composable +private fun FrostedLauncher(tab: String, transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT) = + Frosted(transparency, cards, cardTransparency) { FrontEndScreen(sampleState(navigate = tab), sampleActions) } + +/** A settings step opened over frosted page text with see-through cards: the step is solid, so none of the text shows through it. */ +@Composable +private fun FrostedStepOut() = Frosted(cards = true) { + val text: @Composable (Int) -> String = { androidx.compose.ui.res.stringResource(it) } + Column(Modifier.padding(24.dp)) { + val line = List(8) { text(R.string.stores_shelf_new) }.joinToString(" ") + repeat(14) { androidx.compose.material3.Text(line, fontSize = 24.sp, color = LocalPalette.current.onBackground, maxLines = 1, softWrap = false) } + } + androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) { + val pill = with(androidx.compose.ui.platform.LocalDensity.current) { + androidx.compose.ui.geometry.Rect(androidx.compose.ui.geometry.Offset((maxWidth - 68.dp).toPx(), 16.dp.toPx()), androidx.compose.ui.geometry.Size(44.dp.toPx(), 44.dp.toPx())) + } + val accent = LocalPalette.current.signal + StepOut( + open = true, pill = pill, preferredSide = StepSide.Left, accent = accent, onDismiss = {}, onClosed = {}, items = 2, maxWidth = 440.dp, + handle = { androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Filled.Settings, null, tint = accent, modifier = Modifier.size(20.dp)) }, + ) { + StepTitle(text(R.string.stores_settings_eyebrow)) + Column(Modifier.stepItem(1)) { + SettingsRow(text(R.string.stores_show_mature), null) { ToggleSwitch(true, label = text(R.string.stores_show_mature)) {} } + SettingsRow(text(R.string.gog_achievements), text(R.string.gog_achievements_hint)) { ToggleSwitch(false, label = text(R.string.gog_achievements)) {} } + } + } + } +} + +@DroidDeckPreviews @Composable private fun FrostedSteamTabPreview() = FrostedLauncher("steam") +@DroidDeckPreviews @Composable private fun FrostedLibraryPreview() = FrostedLauncher("games") +@DroidDeckPreviews @Composable private fun FrostedSettingsCardsPreview() = FrostedLauncher("setup", cards = true) +@DroidDeckPreviews @Composable private fun FrostedSettingsClearestPreview() = FrostedLauncher("setup", transparency = FROST_MAX, cards = true, cardTransparency = FROST_MAX) +@DroidDeckPreviews @Composable private fun FrostedStepOutPreview() = FrostedStepOut() + /** The in-game menu on one page, as a session shows it. */ @Composable private fun SessionMenu(page: SessionDrawerPage, steam: Boolean = true, desktop: Boolean = false) = PreviewHost { @@ -72,6 +120,11 @@ internal val previewCases: List = listOf( PreviewCase("downloads") { Launcher("downloads") }, PreviewCase("settings") { Launcher("setup") }, PreviewCase("runtime-missing") { Launcher("setup", ready = false) }, + PreviewCase("frosted-steam-tab") { FrostedLauncher("steam") }, + PreviewCase("frosted-library", storesLoaded) { FrostedLauncher("games") }, + PreviewCase("frosted-settings-cards") { FrostedLauncher("setup", cards = true) }, + PreviewCase("frosted-settings-clearest") { FrostedLauncher("setup", transparency = FROST_MAX, cards = true, cardTransparency = FROST_MAX) }, + PreviewCase("frosted-step-out") { FrostedStepOut() }, PreviewCase("session-menu-controller") { SessionMenu(SessionDrawerPage.CONTROLLER) }, PreviewCase("session-menu-display") { SessionMenu(SessionDrawerPage.DISPLAY) }, PreviewCase("session-menu-hud") { SessionMenu(SessionDrawerPage.HUD) }, diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 154ca4e9fb..1ebd5b7bdf 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -25,6 +25,7 @@ import android.widget.EditText import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -207,6 +208,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) private var homePage by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM) private var launcherFullscreen by mutableStateOf(true) + private var launcherFrost by mutableStateOf(false) + private var frostWallpaper by mutableStateOf(true) + private var frostCards by mutableStateOf(true) + private var frostTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT) + private var frostCardTransparency by mutableStateOf(com.droiddeck.launcher.ui.FROST_DEFAULT) + private val frost = com.droiddeck.launcher.ui.LauncherFrost(this) private var controllerHaptics by mutableStateOf(true) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadMirror by mutableStateOf("") @@ -1372,6 +1379,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet requestedOrientation = launcherOrientation homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) launcherFullscreen = SessionPrefs.launcherFullscreen(this) + launcherFrost = SessionPrefs.launcherFrost(this) + frostWallpaper = SessionPrefs.frostWallpaper(this) + frostCards = SessionPrefs.frostCards(this) + frostTransparency = SessionPrefs.frostTransparency(this) + frostCardTransparency = SessionPrefs.frostCardTransparency(this) + frost.start() + frost.prepare(launcherFrost && frostWallpaper) + frost.show(frostShown()) controllerHaptics = SessionPrefs.controllerHaptics(this) downloadSource = DownloadSource.mode(this) downloadMirror = DownloadSource.mirror(this) @@ -1396,8 +1411,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() } - DroidDeckTheme(theme, appScale = appScale) { - com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) { + val frostShown = frostShown() + androidx.compose.runtime.LaunchedEffect(frostShown) { frost.show(frostShown) } + val frostChoice = if (frostShown) com.droiddeck.launcher.ui.FrostChoice(frostTransparency, frostCards, frostCardTransparency) else null + DroidDeckTheme(theme, appScale = appScale, frost = frostChoice) { + val palette = com.droiddeck.launcher.ui.LocalPalette.current + val veil = com.droiddeck.launcher.ui.LocalFrost.current + val ground = if (frost.prepared) androidx.compose.ui.Modifier.background(veil ?: palette.background) else androidx.compose.ui.Modifier + com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().then(ground).exposeTestTags()) { if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog( onConfirm = { decky.confirmPluginZip() }, onCancel = { decky.cancelPluginZip() }, ) @@ -1473,6 +1494,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherOrientation = launcherOrientation, homePage = homePage, launcherFullscreen = launcherFullscreen, + launcherFrost = launcherFrost, + frostWallpaper = frostWallpaper, + frostCards = frostCards, + frostTransparency = frostTransparency, + frostCardTransparency = frostCardTransparency, + frostSupported = frost.supported, controllerHaptics = controllerHaptics, downloadSource = downloadSource, downloadMirror = downloadMirror, @@ -1808,6 +1835,28 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launcherFullscreen = on applyLauncherFullscreen() }, + onLauncherFrost = { on -> + SessionPrefs.setLauncherFrost(this, on) + launcherFrost = on + if (on && frostWallpaper && !frost.prepared) restartLauncher() + }, + onFrostWallpaper = { on -> + SessionPrefs.setFrostWallpaper(this, on) + frostWallpaper = on + if (on && !frost.prepared) restartLauncher() + }, + onFrostCards = { on -> + SessionPrefs.setFrostCards(this, on) + frostCards = on + }, + onFrostTransparency = { percent -> + SessionPrefs.setFrostTransparency(this, percent) + frostTransparency = SessionPrefs.frostTransparency(this) + }, + onFrostCardTransparency = { percent -> + SessionPrefs.setFrostCardTransparency(this, percent) + frostCardTransparency = SessionPrefs.frostCardTransparency(this) + }, onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier }, onNavigated = { navRequest = null }, onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show }, @@ -2114,6 +2163,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } + private fun frostShown(): Boolean = + launcherFrost && frostWallpaper && frost.prepared && frost.available && theme != com.droiddeck.launcher.ui.Themes.TRUE_BLACK + private fun applyLauncherFullscreen() { @Suppress("DEPRECATION") window.decorView.systemUiVisibility = if (launcherFullscreen) { @@ -2461,6 +2513,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet launchCoordinator.cancelAll() cancelCompatLaunch() updates.unregister() + frost.stop() runCatching { unregisterReceiver(shortcutsInstallStatus) } super.onDestroy() } 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 7e77ab41e9..4785f06909 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -118,6 +118,39 @@ object SessionPrefs { prefs(context).edit().putBoolean("launcherFullscreen", on).apply() } + fun launcherFrost(context: Context): Boolean = prefs(context).getBoolean("launcherFrost", false) + + fun setLauncherFrost(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("launcherFrost", on).apply() + } + + fun frostWallpaper(context: Context): Boolean = prefs(context).getBoolean("frostWallpaper", true) + + fun setFrostWallpaper(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("frostWallpaper", on).apply() + } + + fun frostCards(context: Context): Boolean = prefs(context).getBoolean("frostCards", true) + + fun setFrostCards(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("frostCards", on).apply() + } + + fun frostTransparency(context: Context): Int = frostPercent(context, "frostTransparency", com.droiddeck.launcher.ui.FROST_WALLPAPER_DEFAULT) + + fun setFrostTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostTransparency", percent) + + fun frostCardTransparency(context: Context): Int = frostPercent(context, "frostCardTransparency", com.droiddeck.launcher.ui.FROST_DEFAULT) + + fun setFrostCardTransparency(context: Context, percent: Int) = setFrostPercent(context, "frostCardTransparency", percent) + + private fun frostPercent(context: Context, key: String, default: Int): Int = + prefs(context).getInt(key, default).coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX) + + private fun setFrostPercent(context: Context, key: String, percent: Int) { + prefs(context).edit().putInt(key, percent.coerceIn(0, com.droiddeck.launcher.ui.FROST_MAX)).apply() + } + fun controllerHaptics(context: Context): Boolean = prefs(context).getBoolean("controllerHaptics", true) fun setControllerHaptics(context: Context, on: Boolean) { 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 6cf0bace9b..d1a7b862fc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -12,7 +12,7 @@ object SettingsReset { private const val TAG = "SettingsReset" internal val SESSION_KEYS = setOf( - "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", + "orientation", "launcherFullscreen", "launcherFrost", "frostWallpaper", "frostCards", "frostTransparency", "frostCardTransparency", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", "drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", 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 fcfc591951..eb70d0a10b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -177,6 +177,12 @@ class FrontEndState( val launcherOrientation: Int = android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER, val homePage: String = com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_STEAM, val launcherFullscreen: Boolean = true, + val launcherFrost: Boolean = false, + val frostWallpaper: Boolean = true, + val frostCards: Boolean = true, + val frostTransparency: Int = FROST_WALLPAPER_DEFAULT, + val frostCardTransparency: Int = FROST_DEFAULT, + val frostSupported: Boolean = false, val controllerHaptics: Boolean = true, val downloadSource: String = DownloadSource.MODE_AUTO, val downloadMirror: String = "", @@ -284,6 +290,11 @@ class FrontEndActions( val onLauncherOrientation: (Int) -> Unit = {}, val onHomePage: (String) -> Unit = {}, val onLauncherFullscreen: (Boolean) -> Unit = {}, + val onLauncherFrost: (Boolean) -> Unit = {}, + val onFrostWallpaper: (Boolean) -> Unit = {}, + val onFrostCards: (Boolean) -> Unit = {}, + val onFrostTransparency: (Int) -> Unit = {}, + val onFrostCardTransparency: (Int) -> Unit = {}, val onControllerHaptics: (Boolean) -> Unit = {}, val onAnimationsEnabled: (Boolean) -> Unit = {}, val onLowStorageWarning: (Boolean) -> Unit = {}, @@ -693,7 +704,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } androidx.compose.foundation.layout.BoxWithConstraints( - modifier = Modifier.fillMaxSize().background(colors.background) + modifier = Modifier.fillMaxSize().background(if (LocalFrost.current != null) Color.Transparent else colors.background) .windowInsetsPadding(if (s.launcherFullscreen) WindowInsets.displayCutout else WindowInsets.systemBars) .onFocusChanged { anyFocused = it.hasFocus }, ) { 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 3ad877dea1..c2058c277e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -156,6 +156,7 @@ internal fun SetupPanel( ) { val host = rememberMenuHost() val ctx = LocalContext.current + val frostRow = s.frostSupported && s.theme != Themes.TRUE_BLACK var steamOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "steam")) } var desktopOrientation by remember { mutableStateOf(SessionPrefs.orientation(ctx, "desktop")) } val lifecycleOwner = LocalLifecycleOwner.current @@ -268,7 +269,7 @@ internal fun SetupPanel( val listing = searching && query.isNotBlank() val fixed = tab == CONTROLLER_TAB && !listing Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (fixed) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (fixed) 0.dp else 24.dp)) { - if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) } + if (listing) SettingsSearchResults(query, frostRow) { section -> pick(section.ordinal) } else when (tab) { OVERVIEW_TAB -> { OnboardingCard(limitBlocks, a.onShowPhantomGate) @@ -465,6 +466,35 @@ internal fun SetupPanel( if (s.theme == Themes.GRADIENT) GradientColorRows() if (s.theme == Themes.CUSTOM) CustomColorRows() if (s.theme == Themes.TRUE_BLACK) HighlightColorRow() + if (frostRow) { + ToggleRow( + host, "launcher-frost", stringResource(R.string.setup_frosted_background), + stringResource(R.string.setup_frosted_background_hint), s.launcherFrost, onChange = a.onLauncherFrost, + ) + if (s.launcherFrost) { + val ctx = androidx.compose.ui.platform.LocalContext.current + val percent: (Int) -> String = { ctx.getString(R.string.ctrl_percent, it) } + ToggleRow( + host, "launcher-frost-wallpaper", stringResource(R.string.setup_frosted_wallpaper), null, + s.frostWallpaper, onChange = a.onFrostWallpaper, + ) + SliderRow( + stringResource(R.string.setup_frost_transparency), stringResource(R.string.setup_frost_transparency_hint), + s.frostTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper, format = percent, + onChange = a.onFrostTransparency, + ) + ToggleRow( + host, "launcher-frost-cards", stringResource(R.string.setup_frosted_cards), + stringResource(if (s.frostWallpaper) R.string.setup_frosted_cards_hint else R.string.setup_frosted_cards_needs_wallpaper), + s.frostCards, enabled = s.frostWallpaper, onChange = a.onFrostCards, + ) + SliderRow( + stringResource(R.string.setup_frost_card_transparency), stringResource(R.string.setup_frost_card_transparency_hint), + s.frostCardTransparency, 0..FROST_MAX, step = FROST_STEP, enabled = s.frostWallpaper && s.frostCards, format = percent, + onChange = a.onFrostCardTransparency, + ) + } + } ChoiceRow( host, "app-scale", stringResource(R.string.setup_app_scale), stringResource(R.string.setup_app_scale_hint), com.droiddeck.launcher.core.AppUiPrefs.scales.map { percent -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt index c13bebef13..7000bb936f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GlideWindows.kt @@ -76,7 +76,7 @@ internal fun WindowDialog( content: @Composable () -> Unit, ) { if (!LocalPresentationWindow.current) { - Dialog(onDismissRequest, properties, content) + Dialog(onDismissRequest, properties) { SolidSurfaces(content) } return } Popup( @@ -87,7 +87,7 @@ internal fun WindowDialog( Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black.copy(alpha = 0.6f)) .tapOutside { if (properties.dismissOnClickOutside) onDismissRequest() }, contentAlignment = Alignment.Center, - ) { content() } + ) { SolidSurfaces(content) } } } @@ -150,7 +150,7 @@ internal fun GlidePopup( ) { Popup(popupPositionProvider, onDismissRequest, properties) { if (properties.focusable) TrackKeyWindow() - FocusGlideHost(content = content) + SolidSurfaces { FocusGlideHost(content = content) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt b/app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt new file mode 100644 index 0000000000..91f2cdf402 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/LauncherFrost.kt @@ -0,0 +1,130 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.graphics.drawable.ColorDrawable +import android.os.Build +import android.os.PowerManager +import android.view.WindowManager +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.graphics.luminance +import java.util.function.Consumer + +internal val LocalFrost = staticCompositionLocalOf { null } + +internal const val FROST_MAX = 100 +internal const val FROST_STEP = 10 +internal const val FROST_DEFAULT = 50 +internal const val FROST_WALLPAPER_DEFAULT = 80 +private const val FROST_TEXT_LIFT = 0.5f +private const val FROST_LIFT_STEPS = 5 +private const val FROST_TINT_MAX = 0.9f +private const val FROST_SEARCH_STEPS = 12 +private const val FROST_BLUR_DP = 28 + +private class FrostScale(val solid: Float, val default: Float, val clear: Float) { + fun at(percent: Int): Float { + val t = percent.coerceIn(0, FROST_MAX) / FROST_DEFAULT.toFloat() + return if (t <= 1f) solid + (default - solid) * t else default + (clear - default) * (t - 1f) + } +} + +private val TINT_DARK = FrostScale(0.9f, 0.58f, 0.32f) +private val TINT_LIGHT = FrostScale(0.94f, 0.7f, 0.48f) +private val CARD_DARK = FrostScale(1f, 0.6f, 0.3f) +private val CARD_LIGHT = FrostScale(1f, 0.74f, 0.45f) +private val TEXT_LIFT_MAX = FrostScale(FROST_TEXT_LIFT, FROST_TEXT_LIFT, 1f) + +class FrostChoice( + val transparency: Int = FROST_WALLPAPER_DEFAULT, + val cards: Boolean = false, + val cardTransparency: Int = FROST_DEFAULT, +) + +internal class FrostLook(val veil: Color, val lift: Float, val cardAlpha: Float) + +internal fun frostLook(palette: Palette, choice: FrostChoice): FrostLook { + val light = palette.background.luminance() > 0.5f + val cardAlpha = if (!choice.cards) 1f else (if (light) CARD_LIGHT else CARD_DARK).at(choice.cardTransparency) + val maxLift = maxOf(TEXT_LIFT_MAX.at(choice.transparency), if (choice.cards) TEXT_LIFT_MAX.at(choice.cardTransparency) else 0f) + // Android reports only the wallpaper's main colours, and any part of it can sit behind text. + fun readable(alpha: Float, lift: Float): Boolean = listOf(Color.Black, Color.White).all { behind -> + val page = palette.background.copy(alpha = alpha).compositeOver(behind) + val card = palette.surface.copy(alpha = cardAlpha).compositeOver(page) + val hint = lerp(palette.onSurfaceVariant, palette.onBackground, lift) + minOf(ThemeColors.contrast(hint, page), ThemeColors.contrast(hint, card)) >= ThemeColors.MIN_CONTRAST + } + var low = 0f + var high = FROST_TINT_MAX + if (readable(low, maxLift)) high = low + else if (!readable(high, maxLift)) high = 1f + else repeat(FROST_SEARCH_STEPS) { + val mid = (low + high) / 2 + if (readable(mid, maxLift)) high = mid else low = mid + } + val lifts = (0..FROST_LIFT_STEPS).map { FROST_TEXT_LIFT + (maxLift - FROST_TEXT_LIFT) * it / FROST_LIFT_STEPS } + val tint = maxOf((if (light) TINT_LIGHT else TINT_DARK).at(choice.transparency), kotlin.math.ceil(high * 255f) / 255f) + val alpha = if (lifts.any { readable(tint, it) }) tint else 1f + val lift = lifts.firstOrNull { readable(alpha, it) } ?: maxLift + return FrostLook(palette.background.copy(alpha = alpha), lift, cardAlpha) +} + +internal fun Palette.frosted(look: FrostLook): Palette = Palette( + id, label, detail, + background = background, + surface = if (look.cardAlpha < 1f) surface.copy(alpha = look.cardAlpha) else surface, + surfaceVariant = if (look.cardAlpha < 1f) surfaceVariant.copy(alpha = look.cardAlpha) else surfaceVariant, + line = line, line2 = line2, + onBackground = onBackground, onSurfaceVariant = lerp(onSurfaceVariant, onBackground, look.lift), + primary = primary, primary2 = primary2, onPrimary = onPrimary, signal = signal, + good = good, error = error, warning = warning, +) + + +internal class LauncherFrost(private val activity: Activity) { + var available by mutableStateOf(false) + private set + var prepared = false + private set + + private var stopListening: (() -> Unit)? = null + + val supported: Boolean + get() = Build.VERSION.SDK_INT >= 31 && + (available || activity.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true) + + fun start() { + if (Build.VERSION.SDK_INT < 31 || stopListening != null) return + val windows = activity.windowManager + val blur = Consumer { available = it } + available = windows.isCrossWindowBlurEnabled + windows.addCrossWindowBlurEnabledListener(blur) + stopListening = { windows.removeCrossWindowBlurEnabledListener(blur) } + } + + fun stop() { + stopListening?.invoke() + stopListening = null + } + + // A window made see-through after its first frame keeps drawing over its old frames, so this runs before setContent. + fun prepare(on: Boolean) { + prepared = on && Build.VERSION.SDK_INT >= 31 + if (prepared) activity.window.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT)) + } + + fun show(on: Boolean) { + if (!prepared || Build.VERSION.SDK_INT < 31) return + val window = activity.window + val flags = WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND + if (on) window.addFlags(flags) else window.clearFlags(flags) + window.attributes = window.attributes.apply { + blurBehindRadius = if (on) (FROST_BLUR_DP * activity.resources.displayMetrics.density).toInt() else 0 + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index 842a49b07a..5983063e1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -39,6 +39,7 @@ internal class SettingsEntry( val words: List = emptyList(), val developer: Boolean = false, val tab: String? = null, + val frost: Boolean = false, ) { val within: Int? get() = section?.title ?: tab?.let { railLabelIcon(it).first } ?: group @@ -100,6 +101,10 @@ internal object SettingsIndex { s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"), s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"), + SettingsEntry( + SettingsPlace.SETTINGS, R.string.setup_frosted_background, section = SettingsSection.LAUNCHER, frost = true, + words = listOf("blur", "wallpaper", "background", "cards", "transparent", "transparency", "opacity", "glass"), + ), s(SettingsSection.LAUNCHER, R.string.setup_app_scale, "size", "zoom"), s(SettingsSection.LAUNCHER, R.string.setup_launcher_icon), s(SettingsSection.LAUNCHER, R.string.setup_animations), @@ -151,6 +156,6 @@ internal object SettingsIndex { sh(R.string.stores_tab_library, R.string.stores_tab_library, "second library", "sd card", "steam library"), ) - fun search(context: Context, query: String): List = - entries.filter { (!it.developer || DeveloperTools.on) && it.matches(context, query) } + fun search(context: Context, query: String, frost: Boolean = false): List = + entries.filter { (!it.developer || DeveloperTools.on) && (!it.frost || frost) && it.matches(context, query) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt index 0a4ab5590c..e195b4ee8e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -96,9 +96,9 @@ internal fun SettingsPillSearch( } @Composable -internal fun SettingsSearchResults(query: String, onOpen: (SettingsSection) -> Unit) { +internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (SettingsSection) -> Unit) { val ctx = LocalContext.current - val found = remember(query) { SettingsIndex.search(ctx, query) } + val found = remember(query, frost) { SettingsIndex.search(ctx, query, frost) } if (found.isEmpty()) { Note(stringResource(R.string.settings_search_none, query.trim())) return diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 93ece0d689..d1889d6fb9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -307,7 +307,7 @@ fun AnchoredMenu( runCatching { firstItemFocus.requestFocus() } } } - CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) { + SolidSurfaces { CompositionLocalProvider(LocalDensity provides density, LocalConfiguration provides configuration) { AnimatedVisibility( visibleState = state, enter = fadeIn(Motion.tw(180)) + scaleIn(Motion.sp(0.7f), initialScale = 0.94f, transformOrigin = TransformOrigin(if (compact) 0f else 1f, 0f)), @@ -363,7 +363,7 @@ fun AnchoredMenu( } } } - } + } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt index b888f08065..084de26ccd 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt @@ -149,7 +149,6 @@ private val OutPull = 6.dp private val OutBoxCorner = 16.dp private val OutFillet = 10.dp -@OptIn(ExperimentalComposeUiApi::class) @Composable internal fun StepOut( open: Boolean, @@ -163,6 +162,22 @@ internal fun StepOut( items: Int = 4, handle: @Composable () -> Unit, content: @Composable StepOutScope.() -> Unit, +) = SolidSurfaces { StepOutPanel(open, pill, preferredSide, accent, onDismiss, onClosed, pillCorner, maxWidth, items, handle, content) } + +@OptIn(ExperimentalComposeUiApi::class) +@Composable +private fun StepOutPanel( + open: Boolean, + pill: Rect, + preferredSide: StepSide, + accent: Color, + onDismiss: () -> Unit, + onClosed: () -> Unit, + pillCorner: Dp?, + maxWidth: Dp, + items: Int, + handle: @Composable () -> Unit, + content: @Composable StepOutScope.() -> Unit, ) { val colors = MaterialTheme.colorScheme val density = LocalDensity.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt index a639615129..17151e1782 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -230,35 +230,51 @@ val LocalPalette = staticCompositionLocalOf { Themes.byId(Themes.GRAPHITE) } val Palette.onSignal: Color get() = if (signal.luminance() > 0.18f) Color(0xFF03111F) else Color.White +internal val LocalSolidPalette = staticCompositionLocalOf { null } + @Composable -fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, content: @Composable () -> Unit) { +fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCALE, frost: FrostChoice? = null, content: @Composable () -> Unit) { val context = LocalContext.current remember(context) { Themes.loadGradient(context) } val id = theme ?: SessionPrefs.theme(context) if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed) - val p = Themes.byId(id) - val scheme = darkColorScheme( - primary = p.primary, onPrimary = p.onPrimary, secondary = p.onSurfaceVariant, - background = p.background, onBackground = p.onBackground, - surface = p.surface, onSurface = p.onBackground, - surfaceVariant = p.surfaceVariant, onSurfaceVariant = p.onSurfaceVariant, - error = p.error, - ) + val solid = Themes.byId(id) + val look = frost?.let { frostLook(solid, it) } + val p = if (look == null) solid else solid.frosted(look) val baseDensity = LocalDensity.current val baseConfiguration = LocalConfiguration.current val density = remember(baseDensity, appScale) { scaledAppDensity(baseDensity, appScale) } val configuration = remember(baseConfiguration, appScale) { scaledAppConfiguration(baseConfiguration, appScale) } CompositionLocalProvider( LocalPalette provides p, + LocalSolidPalette provides solid.takeIf { look != null }, + LocalFrost provides look?.veil, LocalDensity provides density, LocalConfiguration provides configuration, ) { - MaterialTheme(colorScheme = scheme, typography = ContentDirected) { + MaterialTheme(colorScheme = p.scheme(), typography = ContentDirected) { FocusGlideHost { ProvideTextStyle(TextStyle(textDirection = TextDirection.Content), content) } } } } +private fun Palette.scheme() = darkColorScheme( + primary = primary, onPrimary = onPrimary, secondary = onSurfaceVariant, + background = background, onBackground = onBackground, + surface = surface, onSurface = onBackground, + surfaceVariant = surfaceVariant, onSurfaceVariant = onSurfaceVariant, + error = error, +) + +@Composable +internal fun SolidSurfaces(content: @Composable () -> Unit) { + val solid = LocalSolidPalette.current + if (solid == null) content() + else CompositionLocalProvider(LocalPalette provides solid, LocalSolidPalette provides null, LocalFrost provides null) { + MaterialTheme(colorScheme = solid.scheme(), typography = MaterialTheme.typography, content = content) + } +} + private val ContentDirected = Typography().run { fun TextStyle.byContent() = copy(textDirection = TextDirection.Content) Typography( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt b/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt index 279941154f..88cd13355a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ThemeColors.kt @@ -69,7 +69,7 @@ internal object ThemeColors { private val DARK_INK = Color(0xFF03111F) - private fun contrast(a: Color, b: Color): Float { + internal fun contrast(a: Color, b: Color): Float { val x = a.luminance() val y = b.luminance() return (max(x, y) + 0.05f) / (min(x, y) + 0.05f) @@ -80,7 +80,7 @@ internal object ThemeColors { return if (worst(DARK_INK) >= worst(Color.White)) DARK_INK else Color.White } - private const val MIN_CONTRAST = 4.5f + internal const val MIN_CONTRAST = 4.5f private fun fitTo(ink: Color, argb: Int): Int { fun short(color: Int) = contrast(ink, Color(color)) < MIN_CONTRAST diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 3a19a6c5e7..8e3855073f 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1350,6 +1350,16 @@ أجهزة Joy-Con كوحدات تحكم VR أثناء تشغيل SteamVR، يصبح كل Joy-Con يدًا. وجّهه إلى الأمام واضغط مطولًا على Home أو Capture لإعادة توسيطه. الرسوم المتحركة + مصنفر + يعرض خلفية الشاشة مموّهة خلف المشغّل. يستهلك طاقة بطارية أكثر. + خلفية مصنفرة + بطاقات مصنفرة + تُظهر البطاقات والمجموعات قليلًا من الخلفية. تبقى القوائم والحوارات معتمة. + يتطلب الخلفية المصنفرة. + شفافية الخلفية + مقدار ما يظهر من الخلفية. + شفافية البطاقات + مقدار ما يظهر من الخلفية عبر البطاقات. التحذير عند انخفاض مساحة التخزين اسأل قبل تشغيل Steam عندما تكون المساحة الحرة أقل من 10 جيجابايت. التخطيط 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 24e9769318..2b8c9a4afe 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1399,6 +1399,16 @@ Compatibilidad experimental con XREAL 1S, One, One Pro, One Pro+ y Aura. Usa el modo Follow y desactiva la estabilización en el menú de las gafas; en Aura, desactiva también Spatial Anchor. El seguimiento de cabeza y el cambio entre 2D/3D se han probado en Aura y One Pro+. Seguimiento de cabeza experimental para Pro 2. Los ajustes de brillo y volumen y el cambio de modo de pantalla aún no son compatibles. Animaciones + Esmerilado + Muestra tu fondo de pantalla difuminado detrás del launcher. Consume más batería. + Fondo de pantalla esmerilado + Tarjetas esmeriladas + Las tarjetas y los grupos dejan ver un poco del fondo de pantalla. Los menús y diálogos siguen sólidos. + Necesita el fondo de pantalla esmerilado. + Transparencia del fondo de pantalla + Cuánto se ve el fondo de pantalla. + Transparencia de las tarjetas + Cuánto se ve el fondo de pantalla a través de las tarjetas. Avisar cuando queda poco almacenamiento Preguntar antes de iniciar Steam cuando el espacio libre es menor a 10 GB. Disposición diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 9f498245be..b8e3bf6443 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1322,6 +1322,16 @@ Joy-Con като VR контролери Докато SteamVR работи, всеки Joy-Con става ръка. Насочете го напред и задръжте Home или Capture, за да го центрирате отново. Анимации + Матово + Показва тапета ви размазан зад лаунчъра. Изразходва повече батерия. + Матов тапет + Матови карти + Картите и групите пропускат малко от тапета. Менютата и диалозите остават плътни. + Изисква матов тапет. + Прозрачност на тапета + Колко от тапета се вижда. + Прозрачност на картите + Колко от тапета се вижда през картите. Предупреждение при малко място Питай преди стартиране на Steam, когато свободното място е под 10 GB. Разположение diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 2cdca3c13c..0a07d4b77d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1336,6 +1336,16 @@ Joy-Cony jako ovladače VR Když běží SteamVR, každý Joy-Con slouží jako ruka. Namiřte ho dopředu a podržením Home nebo Capture ho znovu vycentrujete. Animace + Matné + Zobrazí za spouštěčem rozmazanou tapetu. Spotřebuje více baterie. + Matná tapeta + Matné karty + Karty a skupiny nechají prosvítat trochu tapety. Nabídky a dialogy zůstanou neprůhledné. + Vyžaduje matnou tapetu. + Průhlednost tapety + Kolik tapety prosvítá. + Průhlednost karet + Kolik tapety prosvítá kartami. Upozornit na nedostatek úložiště Zeptat se před spuštěním Steamu, když je volné místo pod 10 GB. Rozložení diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index bc3f3e334a..5024a32b3d 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1322,6 +1322,16 @@ Joy-Cons som VR-controllere Mens SteamVR kører, bliver hver Joy-Con en hånd. Peg den fremad, og hold Home eller Capture nede for at centrere den igen. Animationer + Mat + Viser din baggrund sløret bag launcheren. Bruger mere batteri. + Mat baggrundsbillede + Matte kort + Kort og grupper lader lidt af baggrundsbilledet skinne igennem. Menuer og dialoger forbliver faste. + Kræver mat baggrundsbillede. + Baggrundens gennemsigtighed + Hvor meget af baggrundsbilledet der skinner igennem. + Kortenes gennemsigtighed + Hvor meget af baggrundsbilledet der skinner gennem kortene. Advar, når lagerpladsen er lav Spørg, før Steam startes, når den ledige plads er under 10 GB. Layout diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index c13d54674f..9e7d0b6eea 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1314,6 +1314,16 @@ Joy-Cons als VR-Controller Während SteamVR läuft, wird jeder Joy-Con zu einer Hand. Richte ihn nach vorn und halte HOME oder Capture gedrückt, um ihn neu auszurichten. Animationen + Milchglas + Zeigt dein Hintergrundbild unscharf hinter dem Launcher. Verbraucht mehr Akku. + Milchglas-Hintergrundbild + Milchglas-Karten + Karten und Gruppen lassen etwas vom Hintergrundbild durch. Menüs und Dialoge bleiben deckend. + Erfordert das Milchglas-Hintergrundbild. + Transparenz des Hintergrundbilds + Wie viel vom Hintergrundbild durchscheint. + Transparenz der Karten + Wie viel vom Hintergrundbild durch die Karten scheint. Bei knappem Speicher warnen Vor dem Start von Steam nachfragen, wenn weniger als 10 GB frei sind. Layout diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 33f88902e3..4785a0a435 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1322,6 +1322,16 @@ Joy-Con ως χειριστήρια VR Όσο εκτελείται το SteamVR, κάθε Joy-Con γίνεται χέρι. Στρέψτε το μπροστά και κρατήστε πατημένο το Home ή το Capture για να το επανακεντράρετε. Κινήσεις + Θαμπό + Εμφανίζει την ταπετσαρία σας θολή πίσω από τον εκκινητή. Καταναλώνει περισσότερη μπαταρία. + Θαμπή ταπετσαρία + Θαμπές κάρτες + Οι κάρτες και οι ομάδες αφήνουν να φαίνεται λίγη από την ταπετσαρία. Τα μενού και οι διάλογοι μένουν συμπαγείς. + Χρειάζεται θαμπή ταπετσαρία. + Διαφάνεια ταπετσαρίας + Πόση από την ταπετσαρία φαίνεται. + Διαφάνεια καρτών + Πόση από την ταπετσαρία φαίνεται μέσα από τις κάρτες. Προειδοποίηση για χαμηλό χώρο αποθήκευσης Ερώτηση πριν από την εκκίνηση του Steam όταν ο ελεύθερος χώρος είναι κάτω από 10 GB. Διάταξη diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index f02d0ff85d..78eccb5bed 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1329,6 +1329,16 @@ Joy-Con como mandos de RV Mientras SteamVR está activo, cada Joy-Con es una mano. Apúntalo al frente y mantén Home o Captura para recentrarlo. Animaciones + Esmerilado + Muestra tu fondo de pantalla difuminado detrás del launcher. Consume más batería. + Fondo de pantalla esmerilado + Tarjetas esmeriladas + Las tarjetas y los grupos dejan ver un poco del fondo de pantalla. Los menús y diálogos siguen opacos. + Necesita el fondo de pantalla esmerilado. + Transparencia del fondo de pantalla + Cuánto se ve el fondo de pantalla. + Transparencia de las tarjetas + Cuánto se ve el fondo de pantalla a través de las tarjetas. Avisar cuando queda poco almacenamiento Preguntar antes de iniciar Steam cuando el espacio libre es inferior a 10 GB. Disposición diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 2ee3de6b59..1108badf1a 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1322,6 +1322,16 @@ Joy-Conit VR-ohjaimina Kun SteamVR on käynnissä, jokainen Joy-Con toimii kätenä. Osoita sillä eteenpäin ja pidä Home- tai Capture-painiketta pohjassa keskittääksesi sen uudelleen. Animaatiot + Huurrettu + Näyttää taustakuvasi sumennettuna käynnistimen takana. Kuluttaa enemmän akkua. + Huurrettu taustakuva + Huurretut kortit + Kortit ja ryhmät päästävät hieman taustakuvaa läpi. Valikot ja valintaikkunat pysyvät peittävinä. + Vaatii huurretun taustakuvan. + Taustakuvan läpinäkyvyys + Kuinka paljon taustakuvaa näkyy läpi. + Korttien läpinäkyvyys + Kuinka paljon taustakuvaa näkyy korttien läpi. Varoita, kun tallennustila on vähissä Kysy ennen Steamin käynnistämistä, kun vapaata tilaa on alle 10 Gt. Asettelu diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 361be45f8e..3182517c3e 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1328,6 +1328,16 @@ Joy-Con comme manettes VR Pendant que SteamVR tourne, chaque Joy-Con devient une main. Pointez-le devant vous et maintenez Home ou Capture pour le recentrer. Animations + Givré + Affiche votre fond d’écran flouté derrière le lanceur. Consomme plus de batterie. + Fond d’écran givré + Cartes givrées + Les cartes et les groupes laissent transparaître un peu du fond d’écran. Les menus et les boîtes de dialogue restent opaques. + Nécessite le fond d’écran givré. + Transparence du fond d’écran + La part du fond d’écran visible à travers. + Transparence des cartes + La part du fond d’écran visible à travers les cartes. Avertir quand l\'espace de stockage est faible Demander avant de lancer Steam lorsque l\'espace libre est inférieur à 10 Go. Disposition diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 8917fb94e2..edf9cad53c 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1322,6 +1322,16 @@ Joy-Con को VR कंट्रोलर की तरह SteamVR चलते समय हर Joy-Con एक हाथ बन जाता है। उसे सामने की ओर करें और फिर से केंद्रित करने के लिए Home या Capture दबाए रखें। एनिमेशन + फ़्रॉस्टेड + लॉन्चर के पीछे आपका वॉलपेपर धुंधला दिखाता है। ज़्यादा बैटरी खर्च होती है। + फ़्रॉस्टेड वॉलपेपर + फ़्रॉस्टेड कार्ड + कार्ड और समूह वॉलपेपर का थोड़ा हिस्सा दिखाते हैं। मेन्यू और डायलॉग ठोस रहते हैं। + फ़्रॉस्टेड वॉलपेपर ज़रूरी है। + वॉलपेपर की पारदर्शिता + वॉलपेपर कितना दिखता है। + कार्ड की पारदर्शिता + कार्ड के पार वॉलपेपर कितना दिखता है। स्टोरेज कम होने पर चेतावनी दें खाली जगह 10 GB से कम होने पर Steam शुरू करने से पहले पूछें। लेआउट diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index be2608c333..83f27827ab 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1322,6 +1322,16 @@ Joy-Conok VR-kontrollerként Amíg a SteamVR fut, minden Joy-Con egy kéz lesz. Irányítsa előre, és tartsa lenyomva a Home vagy a Capture gombot az újraközpontosításhoz. Animációk + Matt + A háttérképet elmosva jeleníti meg az indítóalkalmazás mögött. Több akkumulátort használ. + Matt háttérkép + Matt kártyák + A kártyák és csoportok átengednek egy kicsit a háttérképből. A menük és párbeszédablakok átlátszatlanok maradnak. + Matt háttérkép szükséges hozzá. + Háttérkép átlátszósága + Mennyi látszik át a háttérképből. + Kártyák átlátszósága + Mennyi látszik a háttérképből a kártyákon át. Figyelmeztetés kevés tárhely esetén Rákérdezés a Steam indítása előtt, ha 10 GB-nál kevesebb a szabad hely. Elrendezés diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 5e1b05bda8..917f200f35 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1316,6 +1316,16 @@ Joy-Con sebagai pengontrol VR Saat SteamVR berjalan, setiap Joy-Con menjadi tangan. Arahkan ke depan lalu tahan Home atau Capture untuk memusatkannya kembali. Animasi + Buram + Menampilkan wallpaper Anda yang diburamkan di belakang peluncur. Memakai lebih banyak baterai. + Wallpaper buram + Kartu buram + Kartu dan grup menampilkan sedikit wallpaper. Menu dan dialog tetap solid. + Memerlukan wallpaper buram. + Transparansi wallpaper + Seberapa banyak wallpaper yang terlihat. + Transparansi kartu + Seberapa banyak wallpaper yang terlihat melalui kartu. Peringatkan saat penyimpanan hampir penuh Tanya sebelum memulai Steam saat ruang kosong di bawah 10 GB. Tata letak diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index fca2159a62..ca5fe6244b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1320,6 +1320,16 @@ Joy-Con come controller VR Mentre SteamVR è in esecuzione, ogni Joy-Con diventa una mano. Puntalo in avanti e tieni premuto Home o Capture per ricentrarlo. Animazioni + Satinato + Mostra il tuo sfondo sfocato dietro il launcher. Consuma più batteria. + Sfondo satinato + Schede satinate + Schede e gruppi lasciano trasparire un po’ dello sfondo. Menu e finestre di dialogo restano opachi. + Richiede lo sfondo satinato. + Trasparenza dello sfondo + Quanto dello sfondo si vede attraverso. + Trasparenza delle schede + Quanto dello sfondo si vede attraverso le schede. Avvisa quando lo spazio è scarso Chiedi conferma prima di avviare Steam quando lo spazio libero è inferiore a 10 GB. Layout diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 6cd23d56e9..9af7084b49 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1316,6 +1316,16 @@ Joy-ConをVRコントローラーとして使う SteamVRの実行中は各Joy-Conが手になります。前に向けてHOMEボタンかキャプチャーボタンを長押しすると、向きを合わせ直します。 アニメーション + すりガラス + ランチャーの背後に壁紙をぼかして表示します。バッテリーの消費が増えます。 + すりガラスの壁紙 + すりガラスのカード + カードやグループから壁紙が少し透けて見えます。メニューとダイアログは不透明のままです。 + すりガラスの壁紙が必要です。 + 壁紙の透明度 + 壁紙がどれだけ透けて見えるか。 + カードの透明度 + カード越しに壁紙がどれだけ透けて見えるか。 ストレージ残量が少ないときに警告する 空き容量が 10 GB 未満のとき、Steam を起動する前に確認します。 レイアウト diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 617183be15..1603ed7eb2 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1316,6 +1316,16 @@ Joy-Con을 VR 컨트롤러로 사용 SteamVR이 실행되는 동안 각 Joy-Con이 손이 됩니다. 앞을 향하게 한 채 HOME 또는 캡처 버튼을 길게 누르면 다시 가운데로 맞춥니다. 애니메이션 + 반투명 + 런처 뒤에 배경화면을 흐리게 표시합니다. 배터리를 더 많이 사용합니다. + 반투명 배경화면 + 반투명 카드 + 카드와 그룹에 배경화면이 살짝 비쳐 보입니다. 메뉴와 대화상자는 불투명하게 유지됩니다. + 반투명 배경화면이 필요합니다. + 배경화면 투명도 + 배경화면이 얼마나 비쳐 보이는지 정합니다. + 카드 투명도 + 카드 너머로 배경화면이 얼마나 비쳐 보이는지 정합니다. 저장 공간이 부족할 때 경고 여유 공간이 10GB 미만이면 Steam을 시작하기 전에 확인합니다. 레이아웃 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index fa7ae1d2e9..5728d85712 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1316,6 +1316,16 @@ Joy-Con sebagai pengawal VR Semasa SteamVR berjalan, setiap Joy-Con menjadi tangan. Halakan ke hadapan dan tahan Home atau Capture untuk memusatkannya semula. Animasi + Kabur + Memaparkan kertas dinding anda yang dikaburkan di belakang pelancar. Menggunakan lebih banyak bateri. + Kertas dinding kabur + Kad kabur + Kad dan kumpulan menampakkan sedikit kertas dinding. Menu dan dialog kekal padu. + Memerlukan kertas dinding kabur. + Ketelusan kertas dinding + Berapa banyak kertas dinding yang kelihatan. + Ketelusan kad + Berapa banyak kertas dinding yang kelihatan melalui kad. Beri amaran apabila storan rendah Tanya sebelum memulakan Steam apabila ruang kosong kurang daripada 10 GB. Susun atur diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 0a2424f179..ce52e5ffb2 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1322,6 +1322,16 @@ Joy-Con som VR-kontrollere Mens SteamVR kjører, blir hver Joy-Con en hånd. Pek den fremover og hold inne Home eller Capture for å sentrere den på nytt. Animasjoner + Matt + Viser bakgrunnsbildet ditt uskarpt bak launcheren. Bruker mer batteri. + Matt bakgrunnsbilde + Matte kort + Kort og grupper slipper litt av bakgrunnsbildet gjennom. Menyer og dialoger forblir heldekkende. + Krever matt bakgrunnsbilde. + Bakgrunnens gjennomsiktighet + Hvor mye av bakgrunnsbildet som synes gjennom. + Kortenes gjennomsiktighet + Hvor mye av bakgrunnsbildet som synes gjennom kortene. Advar når lagringsplassen er lav Spør før Steam startes når ledig plass er under 10 GB. Oppsett diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index eec78575f0..59c533f657 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1322,6 +1322,16 @@ Joy-Cons als VR-controllers Zolang SteamVR draait, wordt elke Joy-Con een hand. Richt hem naar voren en houd Home of Capture ingedrukt om hem opnieuw te centreren. Animaties + Matglas + Toont je achtergrond wazig achter de launcher. Verbruikt meer batterij. + Matglazen achtergrond + Matglazen kaarten + Kaarten en groepen laten iets van de achtergrond door. Menu’s en dialogen blijven dekkend. + Vereist de matglazen achtergrond. + Transparantie van de achtergrond + Hoeveel van de achtergrond doorschijnt. + Transparantie van de kaarten + Hoeveel van de achtergrond door de kaarten schijnt. Waarschuwen bij weinig opslagruimte Vragen voordat Steam start als er minder dan 10 GB vrij is. Indeling diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 881073936a..7f0506bd7e 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1336,6 +1336,16 @@ Joy-Cony jako kontrolery VR Gdy działa SteamVR, każdy Joy-Con staje się dłonią. Skieruj go przed siebie i przytrzymaj Home lub Capture, aby go wyśrodkować. Animacje + Matowe + Pokazuje rozmytą tapetę za aplikacją. Zużywa więcej baterii. + Matowa tapeta + Matowe karty + Karty i grupy przepuszczają trochę tapety. Menu i okna dialogowe pozostają nieprzezroczyste. + Wymaga matowej tapety. + Przezroczystość tapety + Ile tapety prześwituje. + Przezroczystość kart + Ile tapety prześwituje przez karty. Ostrzegaj o małej ilości miejsca Pytaj przed uruchomieniem Steam, gdy wolne miejsce wynosi mniej niż 10 GB. Układ diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 3f48785b51..6eb5f0849a 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1320,6 +1320,16 @@ Joy-Con como comandos de RV Enquanto o SteamVR está a correr, cada Joy-Con torna-se uma mão. Aponte-o para a frente e mantenha Home ou Capture premido para o recentrar. Animações + Fosco + Mostra a imagem de fundo desfocada atrás do iniciador. Gasta mais bateria. + Fundo fosco + Cartões foscos + Os cartões e grupos deixam ver um pouco do fundo. Os menus e caixas de diálogo continuam opacos. + Requer o fundo fosco. + Transparência do fundo + Quanto do fundo se vê através. + Transparência dos cartões + Quanto do fundo se vê através dos cartões. Avisar quando o armazenamento estiver baixo Perguntar antes de iniciar o Steam quando o espaço livre for inferior a 10 GB. Esquema diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index e127ed080b..93d4bc6eec 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1328,6 +1328,16 @@ Joy-Cons como controles de RV Enquanto o SteamVR está rodando, cada Joy-Con vira uma mão. Aponte-o para a frente e segure Home ou Capture para recentralizá-lo. Animações + Fosco + Mostra seu papel de parede desfocado atrás do inicializador. Usa mais bateria. + Papel de parede fosco + Cartões foscos + Cartões e grupos deixam ver um pouco do papel de parede. Menus e caixas de diálogo continuam opacos. + Requer o papel de parede fosco. + Transparência do papel de parede + Quanto do papel de parede aparece. + Transparência dos cartões + Quanto do papel de parede aparece através dos cartões. Avisar quando o armazenamento estiver baixo Perguntar antes de iniciar o Steam quando o espaço livre for inferior a 10 GB. Layout diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 402c39e276..9e105d493c 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1329,6 +1329,16 @@ Joy-Con ca controllere VR Cât timp rulează SteamVR, fiecare Joy-Con devine o mână. Îndreaptă-l înainte și ține apăsat Home sau Capture pentru a-l recentra. Animații + Mat + Afișează imaginea de fundal estompată în spatele launcherului. Consumă mai multă baterie. + Imagine de fundal mată + Carduri mate + Cardurile și grupurile lasă să se vadă puțin din imaginea de fundal. Meniurile și dialogurile rămân opace. + Necesită imaginea de fundal mată. + Transparența imaginii de fundal + Cât din imaginea de fundal se vede. + Transparența cardurilor + Cât din imaginea de fundal se vede prin carduri. Avertizează când spațiul de stocare este redus Întreabă înainte de pornirea Steam când spațiul liber este sub 10 GB. Aranjament diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index fa1dac77a5..b3b0450459 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1336,6 +1336,16 @@ Joy-Con как VR-контроллеры Пока работает SteamVR, каждый Joy-Con становится рукой. Направьте его вперёд и удерживайте Home или Capture, чтобы снова его отцентрировать. Анимации + Матовое стекло + Показывает размытые обои за лаунчером. Расходует больше заряда. + Матовые обои + Матовые карточки + Сквозь карточки и группы немного просвечивают обои. Меню и диалоги остаются непрозрачными. + Нужны матовые обои. + Прозрачность обоев + Насколько просвечивают обои. + Прозрачность карточек + Насколько обои просвечивают сквозь карточки. Предупреждать о нехватке места Спрашивать перед запуском Steam, если свободно меньше 10 ГБ. Раскладка diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 0b154e753d..23d08a1e84 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1322,6 +1322,16 @@ Joy-Con som VR-handkontroller Medan SteamVR körs blir varje Joy-Con en hand. Rikta den framåt och håll in Home eller Capture för att centrera den igen. Animationer + Frostat + Visar din bakgrundsbild suddig bakom startprogrammet. Drar mer batteri. + Frostad bakgrundsbild + Frostade kort + Kort och grupper släpper igenom lite av bakgrundsbilden. Menyer och dialogrutor förblir täckande. + Kräver frostad bakgrundsbild. + Bakgrundsbildens genomskinlighet + Hur mycket av bakgrundsbilden som syns igenom. + Kortens genomskinlighet + Hur mycket av bakgrundsbilden som syns genom korten. Varna när lagringsutrymmet är lågt Fråga innan Steam startas när det lediga utrymmet är under 10 GB. Layout diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index e5304587f9..637f355e55 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1316,6 +1316,16 @@ ใช้ Joy-Con เป็นคอนโทรลเลอร์ VR ขณะที่ SteamVR ทำงาน Joy-Con แต่ละตัวจะกลายเป็นมือ ชี้ไปข้างหน้าแล้วกด Home หรือ Capture ค้างไว้เพื่อจัดให้อยู่ตรงกลางอีกครั้ง ภาพเคลื่อนไหว + แบบฝ้า + แสดงวอลเปเปอร์แบบเบลอไว้ด้านหลังตัวเปิดแอป ใช้แบตเตอรี่มากขึ้น + วอลเปเปอร์แบบฝ้า + การ์ดแบบฝ้า + การ์ดและกลุ่มจะเห็นวอลเปเปอร์เล็กน้อย เมนูและกล่องโต้ตอบยังคงทึบ + ต้องเปิดวอลเปเปอร์แบบฝ้า + ความโปร่งใสของวอลเปเปอร์ + ปริมาณวอลเปเปอร์ที่มองทะลุได้ + ความโปร่งใสของการ์ด + ปริมาณวอลเปเปอร์ที่มองทะลุการ์ดได้ เตือนเมื่อพื้นที่เก็บข้อมูลเหลือน้อย ถามก่อนเริ่ม Steam เมื่อพื้นที่ว่างน้อยกว่า 10 GB การจัดวาง diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 3b9224c90b..589d37181b 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1314,6 +1314,16 @@ VR kumandası olarak Joy-Con\'lar SteamVR çalışırken her Joy-Con bir el olur. Öne doğrultun ve yeniden ortalamak için Home veya Capture düğmesini basılı tutun. Animasyonlar + Buzlu + Duvar kâğıdınızı başlatıcının arkasında bulanık gösterir. Daha fazla pil kullanır. + Buzlu duvar kâğıdı + Buzlu kartlar + Kartlar ve gruplar duvar kâğıdının bir kısmını gösterir. Menüler ve iletişim kutuları opak kalır. + Buzlu duvar kâğıdı gerekir. + Duvar kâğıdı saydamlığı + Duvar kâğıdının ne kadar göründüğü. + Kart saydamlığı + Duvar kâğıdının kartların ardından ne kadar göründüğü. Depolama azaldığında uyar Boş alan 10 GB\'ın altındayken Steam\'i başlatmadan önce sor. Düzen diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index b76b47e334..170c957af6 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1336,6 +1336,16 @@ Joy-Con як VR-контролери Поки працює SteamVR, кожен Joy-Con стає рукою. Спрямуйте його вперед і утримуйте Home або Capture, щоб знову його відцентрувати. Анімації + Матове скло + Показує розмиті шпалери за лаунчером. Витрачає більше заряду. + Матові шпалери + Матові картки + Крізь картки та групи трохи просвічують шпалери. Меню й діалоги лишаються непрозорими. + Потрібні матові шпалери. + Прозорість шпалер + Наскільки просвічують шпалери. + Прозорість карток + Наскільки шпалери просвічують крізь картки. Попереджати про брак місця Питати перед запуском Steam, якщо вільно менше 10 ГБ. Розкладка diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 04ab6a162f..731a804078 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1316,6 +1316,16 @@ Dùng Joy-Con làm tay cầm VR Khi SteamVR đang chạy, mỗi Joy-Con trở thành một bàn tay. Hướng nó về phía trước rồi giữ Home hoặc Capture để căn giữa lại. Hiệu ứng chuyển động + Mờ + Hiển thị hình nền được làm mờ phía sau launcher. Tốn pin hơn. + Hình nền mờ + Thẻ mờ + Thẻ và nhóm để lộ một chút hình nền. Menu và hộp thoại vẫn đặc. + Cần bật Hình nền mờ. + Độ trong suốt của hình nền + Mức hình nền hiện qua. + Độ trong suốt của thẻ + Mức hình nền hiện qua các thẻ. Cảnh báo khi dung lượng lưu trữ thấp Hỏi trước khi khởi động Steam khi dung lượng trống dưới 10 GB. Bố cục diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 586ff7ec35..9f180077ae 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1399,6 +1399,16 @@ 将 Joy-Con 用作 VR 手柄 SteamVR 运行时,每个 Joy-Con 都会成为一只手。将其指向前方并按住 HOME 键或截图键即可重新居中。 动画 + 毛玻璃 + 在启动器后方显示模糊的壁纸。耗电更多。 + 毛玻璃壁纸 + 毛玻璃卡片 + 卡片和分组会透出少许壁纸。菜单和对话框保持不透明。 + 需要开启毛玻璃壁纸。 + 壁纸透明度 + 壁纸透出的程度。 + 卡片透明度 + 卡片透出壁纸的程度。 存储空间不足时提醒 可用空间不足 10 GB 时,启动 Steam 前先询问。 布局 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 2a7cb2cbc4..5d7fb121c1 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1315,6 +1315,16 @@ 將 Joy-Con 用作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 + 毛玻璃 + 在啟動器後方顯示模糊的桌布。耗電較多。 + 毛玻璃桌布 + 毛玻璃卡片 + 卡片和群組會透出少許桌布。選單和對話框保持不透明。 + 需要開啟毛玻璃桌布。 + 桌布透明度 + 桌布透出的程度。 + 卡片透明度 + 卡片透出桌布的程度。 儲存空間不足時提醒 可用空間少於 10 GB 時,啟動 Steam 前先詢問。 佈局 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 266c2e4367..0b0757d78b 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1315,6 +1315,16 @@ 將 Joy-Con 當作 VR 控制器 SteamVR 執行時,每個 Joy-Con 都會變成一隻手。將它指向前方並按住 HOME 鍵或擷取鍵,即可重新置中。 動畫 + 毛玻璃 + 在啟動器後方顯示模糊的桌布。較為耗電。 + 毛玻璃桌布 + 毛玻璃卡片 + 卡片和群組會透出少許桌布。選單和對話方塊保持不透明。 + 需要開啟毛玻璃桌布。 + 桌布透明度 + 桌布透出的程度。 + 卡片透明度 + 卡片透出桌布的程度。 儲存空間不足時提醒 可用空間少於 10 GB 時,啟動 Steam 前先詢問。 版面配置 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e4dfeba31a..bbbbd62661 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1493,6 +1493,16 @@ Joy-Cons as VR controllers While SteamVR runs, each Joy-Con becomes a hand. Point it ahead and hold Home or Capture to recenter it. Animations + Frosted + Shows your wallpaper, blurred, behind the launcher. Uses more battery. + Frosted wallpaper + Frosted cards + Cards and groups let a little of the wallpaper through. Menus and dialogs stay solid. + Needs Frosted wallpaper. + Wallpaper transparency + How much of the wallpaper shows through. + Card transparency + How much of the wallpaper shows through cards. Warn when storage is low Ask before starting Steam when free space is under 10 GB. Layout diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt new file mode 100644 index 0000000000..51fb7a92ba --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LauncherFrostTest.kt @@ -0,0 +1,166 @@ +package com.droiddeck.launcher.ui + +import android.app.Activity +import android.content.Context +import android.view.WindowManager +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.graphics.luminance +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class LauncherFrostTest { + private val app get() = RuntimeEnvironment.getApplication() + private val graphite get() = Themes.byId(Themes.GRAPHITE) + private val whiteRed get() = Themes.byId(Themes.WHITE_RED) + + @Before fun clear() { + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + private fun contrast(a: Color, b: Color) = (maxOf(a.luminance(), b.luminance()) + 0.05f) / (minOf(a.luminance(), b.luminance()) + 0.05f) + + private val wallpapers = listOf(Color.White, Color.Black, Color(0xFF808080), Color(0xFFFFE600), Color(0xFF00008B), Color(0xFF20AA96), Color(0xFFE2725B)) + + private val steps = (0..FROST_MAX step FROST_STEP).toList() + + private fun look(theme: Palette, transparency: Int = FROST_WALLPAPER_DEFAULT, cards: Boolean = false, cardTransparency: Int = FROST_DEFAULT) = + frostLook(theme, FrostChoice(transparency, cards, cardTransparency)) + + @Test fun hintTextStaysReadableOnThePageAndOnCardsOverAnyPartOfAnyWallpaper() { + for (theme in Themes.all) for (t in steps) for (c in listOf(0, FROST_DEFAULT, FROST_MAX)) { + val look = look(theme, t, cards = true, cardTransparency = c) + val frosted = theme.frosted(look) + assertTrue("${theme.id} $t/$c veil ${look.veil.alpha}", look.veil.alpha in 0.31f..0.95f) + for (wallpaper in wallpapers) { + val page = look.veil.compositeOver(wallpaper) + val card = frosted.surface.compositeOver(page) + val at = "${theme.id} $t/$c over $wallpaper" + assertTrue("$at page", contrast(frosted.onSurfaceVariant, page) >= 4.5f) + assertTrue("$at card", contrast(frosted.onSurfaceVariant, card) >= 4.5f) + } + } + } + + private fun custom(bg: Color, text: Color) = Palette( + "custom", graphite.label, graphite.detail, + background = bg, surface = bg, surfaceVariant = bg, line = bg, line2 = bg, + onBackground = text, onSurfaceVariant = text, + primary = text, primary2 = text, onPrimary = bg, signal = text, good = text, + ) + + @Test fun aMidGreyCustomPaletteStaysReadableOverBlackAndWhiteWallpaper() { + val grey = custom(Color(0xFF999999), Color.Black) + val look = look(grey, cards = false) + for (wallpaper in listOf(Color.Black, Color.White)) { + assertTrue("over $wallpaper", contrast(Color.Black, look.veil.compositeOver(wallpaper)) >= 4.5f) + } + } + + @Test fun whenNoTintIsReadableTheVeilTurnsSolid() { + val dim = custom(Color.Black, Color(0xFF777777)) + assertEquals(1f, look(dim, cards = false).veil.alpha) + } + + @Test fun aTintThatLosesTheTextOverOneWallpaperTurnsSolid() { + val grey = custom(Color.Black, Color(0xFF757575)) + val look = look(grey, cards = false) + for (wallpaper in listOf(Color.Black, Color.White)) { + assertTrue("over $wallpaper", contrast(Color(0xFF757575), look.veil.compositeOver(wallpaper)) >= 4.5f) + } + } + + @Test fun atTheDefaultTransparencyTheVeilStaysUnderThreeQuarters() { + for (theme in Themes.all) assertTrue(theme.id, look(theme, cards = true).veil.alpha <= 0.75f) + } + + @Test fun moreTransparencyNeverThickensTheVeilOrTheCards() { + for (theme in Themes.all) { + val veils = steps.map { look(theme, it).veil.alpha } + assertTrue("${theme.id}: $veils", veils.zipWithNext().all { (a, b) -> b <= a + 0.005f }) + val cards = steps.map { look(theme, cards = true, cardTransparency = it).cardAlpha } + assertTrue("${theme.id} cards: $cards", cards.zipWithNext().all { (a, b) -> b <= a }) + } + assertTrue(look(graphite, FROST_MAX).veil.alpha < look(graphite).veil.alpha) + assertTrue(look(whiteRed, FROST_MAX).veil.alpha < look(whiteRed).veil.alpha) + } + + @Test fun withoutCardsTheFrostOnlyMovesHintTextTowardTheMainText() { + val frosted = graphite.frosted(look(graphite)) + assertEquals(graphite.background, frosted.background) + assertEquals(graphite.surface, frosted.surface) + assertEquals(graphite.surfaceVariant, frosted.surfaceVariant) + assertEquals(graphite.onBackground, frosted.onBackground) + assertTrue(frosted.onSurfaceVariant.luminance() > graphite.onSurfaceVariant.luminance()) + assertTrue(frosted.onSurfaceVariant.luminance() < graphite.onBackground.luminance()) + } + + @Test fun cardsGoSeeThroughByTheirOwnTransparencyAndAreSolidAtZero() { + for (theme in Themes.all) { + val frosted = theme.frosted(look(theme, cards = true)) + assertTrue(theme.id, frosted.surface.alpha in 0.5f..0.8f && frosted.surfaceVariant.alpha == frosted.surface.alpha) + assertEquals(theme.surface, frosted.surface.copy(alpha = 1f)) + assertEquals(theme.background, frosted.background) + assertEquals(1f, look(theme, cards = true, cardTransparency = 0).cardAlpha) + } + } + + @Test fun firstTurningTheFrostOnFrostsTheWallpaperAndCardsAtTheDefaults() { + assertFalse(SessionPrefs.launcherFrost(app)) + assertTrue(SessionPrefs.frostWallpaper(app)) + assertTrue(SessionPrefs.frostCards(app)) + assertEquals(FROST_WALLPAPER_DEFAULT, SessionPrefs.frostTransparency(app)) + assertEquals(FROST_DEFAULT, SessionPrefs.frostCardTransparency(app)) + SessionPrefs.setLauncherFrost(app, true) + SessionPrefs.setFrostWallpaper(app, false) + SessionPrefs.setFrostCards(app, false) + SessionPrefs.setFrostTransparency(app, 999) + SessionPrefs.setFrostCardTransparency(app, -5) + assertTrue(SessionPrefs.launcherFrost(app)) + assertFalse(SessionPrefs.frostWallpaper(app)) + assertFalse(SessionPrefs.frostCards(app)) + assertEquals(FROST_MAX, SessionPrefs.frostTransparency(app)) + assertEquals(0, SessionPrefs.frostCardTransparency(app)) + } + + @Test fun searchFindsTheFrostOnlyWhereSettingsShowsIt() { + val frosted = SettingsIndex.entries.single { it.frost } + assertTrue(frosted in SettingsIndex.search(app, "transparency", frost = true)) + assertFalse(frosted in SettingsIndex.search(app, "transparency", frost = false)) + assertTrue(SettingsIndex.search(app, "theme", frost = false).isNotEmpty()) + } + + @Test fun theWindowIsPreparedWhileBlurIsOffAndShowsNoWallpaperUntilShown() { + val activity = Robolectric.buildActivity(Activity::class.java).setup().get() + val frost = LauncherFrost(activity) + val flags = WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND + frost.prepare(true) + assertFalse(frost.available) + assertTrue(frost.prepared) + assertEquals(0, activity.window.attributes.flags and flags) + frost.show(true) + assertEquals(flags, activity.window.attributes.flags and flags) + } + + @Test fun aWindowThatWasNotPreparedKeepsItsBackgroundAndShowsNoWallpaper() { + val activity = Robolectric.buildActivity(Activity::class.java).setup().get() + val before = activity.window.decorView.background + val frost = LauncherFrost(activity) + frost.prepare(false) + frost.show(true) + assertFalse(frost.prepared) + assertEquals(before, activity.window.decorView.background) + assertEquals(0, activity.window.attributes.flags and (WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER or WindowManager.LayoutParams.FLAG_BLUR_BEHIND)) + } +} diff --git a/docs/compose-previews.md b/docs/compose-previews.md index 1aa5059563..a91a35d37f 100644 --- a/docs/compose-previews.md +++ b/docs/compose-previews.md @@ -24,7 +24,9 @@ ways: | `app/src/testDebug/.../ui/PreviewRenderTest.kt` | The render test | Previews cover the launcher on each tab (Steam, Library, Library with no games, Stores, Downloads, Settings, Settings with -no runtime) and the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu). +no runtime), the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu), and the frosted +background: the Steam and Library tabs, Settings with frosted cards and with both transparencies at 100 %, and a +settings step opened over frosted page text. ## Adding one diff --git a/docs/development/themes.md b/docs/development/themes.md index 8fbae55688..619dc43b8f 100644 --- a/docs/development/themes.md +++ b/docs/development/themes.md @@ -42,3 +42,37 @@ Gradient in the list, and Setup shows a Speed slider (1 to 10, `SessionPrefs.rgb Compose applies Android's animator scale to it, and the colour holds still when animations are off in the app (`Motion.scale`) or in Android's own settings. The hue is written to `Themes.rgbHue` in 3° steps, which restyles the app only when the colour visibly moves; a slow cycle costs few recompositions. +## Frosted background + +Setup › Launcher › Frosted (`SessionPrefs.launcherFrost`, off by default) is the master switch. Under it, while it is +on, sit Frosted wallpaper and Frosted cards (`frostWallpaper`, `frostCards`, both on by default, so the first time +Frosted is turned on both apply at their defaults), each with its own transparency from 0 to 100 % in steps of 10 +(`frostTransparency` from 80 %, `frostCardTransparency` from 50 %). Frosted cards is greyed out while Frosted wallpaper is +off, since a card can only show the wallpaper the page behind it shows; each slider stays in place and is greyed out +while it has nothing to set. + +Frosted wallpaper shows the device's wallpaper, blurred, behind the launcher. Android draws it: the launcher's window +is see-through and carries `FLAG_SHOW_WALLPAPER` and `FLAG_BLUR_BEHIND`, so the app never reads the wallpaper and needs +no permission (`ui/LauncherFrost.kt`). It works with any theme except True black, which keeps the page unlit. + +Over the wallpaper sits one veil of the theme's `background` (`frostLook`). 0 % is nearly solid and 100 % shows the most +wallpaper. While the frost shows, the theme moves `onSurfaceVariant` toward `onBackground` (`Palette.frosted`): halfway +up to 50 %, and further above it, all the way at 100 %. The veil grows past the chosen transparency only as far as that +hint text needs to keep 4.5:1, on the page and on a card (the rail and the bottom bar are cards here), as far as the +theme's own colours allow: a Custom theme whose hint text matches its background stays unreadable with or without the +frost. Android reports only a wallpaper's main colours, and any part of it can sit behind text, so the check takes the +worst wallpaper there is: white under a dark theme and black under the light one. The veil is then about 0.7 at 50 %, +0.63 at 80 % and 0.6 at 100 % on a dark theme, and 0.7, 0.57 and 0.52 on the light one. The wallpaper slider starts at +80 % so the wallpaper shows about as much as the game page's glass (0.58) does. + +`LocalFrost` carries the veil and the launcher's root steps aside. With Frosted cards on, the theme hands out `surface` +and `surfaceVariant` see-through by the card transparency (0.6 on a dark theme and 0.74 on the light one at 50 %, solid at 0 %), and dialogs, popups, menus and +settings steps take the solid palette back (`SolidSurfaces`), so no page text shows through them. The rail and the bottom bar draw +`surface`, so they follow the cards: see-through with them and solid without. + +The rows show on Android 12 and later when the system can blur behind windows, and also while Battery Saver pauses the +blur, when the page shows the plain background until the blur returns. A window is see-through or not from its first +frame, so the launcher prepares its window whenever the wallpaper frost is on at start, whether or not the blur is +available then. Turning the wallpaper frost on restarts the launcher once only if the window was not prepared at start; +otherwise turning it off and on, and the blur pausing and coming back, switch between the frost and the plain +background at once. diff --git a/docs/settings-map.md b/docs/settings-map.md index a907318e78..aface4f407 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -36,6 +36,7 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Controller | Settings › Controller (`droiddeck://settings/controller`) | gamepad, buttons, mapping, profile, remap | | Smart glasses | Settings › Smart glasses (`droiddeck://settings/glasses`) | xreal, viture, vr, ar | | Theme | Settings › Launcher (`droiddeck://settings/launcher`) | color, dark | +| Frosted | Settings › Launcher (`droiddeck://settings/launcher`) | blur, wallpaper, background, cards, transparent, transparency, opacity, glass | | App scale | Settings › Launcher (`droiddeck://settings/launcher`) | size, zoom | | App icon | Settings › Launcher (`droiddeck://settings/launcher`) | | | Animations | Settings › Launcher (`droiddeck://settings/launcher`) | | From ec281db0d1233930dba9b203416ebe063b9b3e1b Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Wed, 2 Dec 2026 16:32:38 -0500 Subject: [PATCH 06/80] fix(nativeguest): restore desktop startup after child handoff (#3594) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep handed-off children on the guest hook’s standard wait path. Verified the exact signed PR build on a Pocket Fit Elite: the desktop reached READY with KWin, Xwayland, and Plasma running. --- tools/nativeguest/hook/privileged.c | 21 +++++++++++++++ tools/tests/test_native_hook_handoff.py | 35 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 2a4a4dc2e1..14ef7c6654 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -339,6 +339,13 @@ __asm__(".globl setrlimit64\n" ".set setrlimit64, setrlimit\n"); #endif #endif +#ifndef CLONE_PIDFD +#define CLONE_PIDFD 0x00001000 +#endif +#ifndef P_PIDFD +#define P_PIDFD 3 +#endif + #ifndef SECCOMP_SET_MODE_STRICT #define SECCOMP_SET_MODE_STRICT 0 #endif @@ -639,6 +646,20 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_clone + if (number == __NR_clone && (arg1 & CLONE_PIDFD)) { + errno = EINVAL; + return -1; + } +#endif + +#ifdef __NR_waitid + if (number == __NR_waitid && (int)arg1 == P_PIDFD) { + errno = EINVAL; + return -1; + } +#endif + #ifdef __NR_clone3 if (number == __NR_clone3) { errno = ENOSYS; diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index bf4d0e2586..3e9f5bec74 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -1111,6 +1111,34 @@ int main(void) { # A worker's program with its table at fd 1000 (kept, as 900 and 901 are): a dup2() onto the pidfd # lets go of 900 while another thread's close_range(899, 2000) is between its parts, held there by the # hook's test gate. The kept fds above 900 stay open. +PIDFD_PROBE = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +int main(void) { + errno = 0; + long r = syscall(SYS_waitid, 3, INT_MAX, NULL, WEXITED | WNOHANG, NULL); + printf("waitid\t%ld %d\n", r, errno); + int pidfd = -1; + errno = 0; + r = syscall(SYS_clone, 0x00001000 | SIGCHLD, NULL, &pidfd, NULL, 0); + if (r == 0) _exit(9); + printf("clone\t%ld %d %d\n", r < 0 ? -1L : 1L, errno, pidfd); + if (r > 0) waitpid((pid_t)r, NULL, 0); + r = syscall(SYS_clone, SIGCHLD, NULL, NULL, NULL, 0); + if (r == 0) _exit(7); + int status = 0; + printf("fork\t%d\n", r > 0 && waitpid((pid_t)r, &status, 0) == r && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; +} +""" + DUPRACE = r""" #define _GNU_SOURCE #include @@ -2217,6 +2245,13 @@ class NativeHookHandoffTest(unittest.TestCase): pass_fds=(table,)) return parent, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out + def test_a_guest_sees_no_pidfd_support_so_its_waits_go_through_the_handoff(self): + parent, result, out = self.run_worker_program("pidfd", PIDFD_PROBE) + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual("-1 %d" % errno.EINVAL, result.get("waitid"), out.stdout + out.stderr) + self.assertEqual("-1 %d -1" % errno.EINVAL, result.get("clone"), out.stdout) + self.assertEqual("7", result.get("fork"), out.stdout) + def test_a_dup2_onto_the_parents_pidfd_while_a_close_range_runs_closes_no_kept_fd(self): parent, result, out = self.run_worker_program("duprace", DUPRACE, table_fd=1000) self.assertEqual(0, out.returncode, out.stderr) From 5d05c36033499058f8cf6f75319e13dbf82a7829 Mon Sep 17 00:00:00 2001 From: Maksynum <82881842+Maksynum@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:34:46 +0200 Subject: [PATCH 07/80] fix(audio): fall back to standard AAudio and bound startup restarts (#3514) Fall back to standard audio mode after low-latency failures and cap consecutive startup restarts. On the Pocket Fit Elite, the exact locally signed PR build accepted playback in both DirectAudio modes. The Samsung-specific failure did not reproduce on that device. --- .../launcher/audio/PulseAudioComponent.java | 147 +++++++++++++++--- .../launcher/audio/PulseAudioComponentTest.kt | 64 ++++++++ 2 files changed, 193 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 1ff48a77cd..300a08b5f3 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -12,6 +12,7 @@ import com.droiddeck.launcher.core.TarZst; import java.io.File; import java.io.InputStream; import java.net.URL; +import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; @@ -36,9 +37,15 @@ public class PulseAudioComponent extends SessionPart { private final HostLifecycle host = new HostLifecycle(Process::killProcess); static final class HostLifecycle { + static final int MAX_STARTUP_CRASH_RESTARTS = 4; + private static final long[] STARTUP_RESTART_DELAYS_MS = {250L, 1000L, 2000L, 4000L}; + volatile int pid = -1; private long generation; private long launches; + private boolean preferStandardPerformanceMode; + private boolean sinkReady; + private int startupCrashRestarts; private final IntConsumer terminate; final ReentrantReadWriteLock commands = new ReentrantReadWriteLock(); @@ -48,6 +55,9 @@ public class PulseAudioComponent extends SessionPart { synchronized long begin() { stop(); + preferStandardPerformanceMode = false; + sinkReady = false; + startupCrashRestarts = 0; return generation; } @@ -55,6 +65,7 @@ public class PulseAudioComponent extends SessionPart { generation++; if (pid > 1) terminate.accept(pid); pid = -1; + sinkReady = false; } boolean launch(long expected, IntSupplier launch) { @@ -63,6 +74,7 @@ public class PulseAudioComponent extends SessionPart { synchronized (this) { if (expected != generation) return false; launches++; + sinkReady = false; pid = launch.getAsInt(); return true; } @@ -93,11 +105,45 @@ public class PulseAudioComponent extends SessionPart { return token == launches && pid > 1; } + synchronized boolean preferStandardPerformanceMode() { + return preferStandardPerformanceMode; + } + + synchronized void markLowLatencyFailed(long token) { + if (token == launches && pid > 1) preferStandardPerformanceMode = true; + } + + synchronized void markSinkReady(long token) { + if (token == launches && pid > 1) { + sinkReady = true; + startupCrashRestarts = 0; + } + } + synchronized boolean exited(long expected) { if (expected != generation || pid <= 1) return false; pid = -1; return true; } + + /** + * Decides whether a dead host should be restarted and after how many milliseconds. + * Returns 0 for immediate recovery of a host that had a working sink, a positive backoff + * while falling back to standard AAudio mode after a startup crash, or -1 to stop retrying. + */ + synchronized long nextRestartDelayMs(long expected) { + if (expected != generation) return -1L; + if (sinkReady) { + sinkReady = false; + startupCrashRestarts = 0; + return 0L; + } + preferStandardPerformanceMode = true; + if (startupCrashRestarts >= MAX_STARTUP_CRASH_RESTARTS) return -1L; + long delay = STARTUP_RESTART_DELAYS_MS[Math.min(startupCrashRestarts, STARTUP_RESTART_DELAYS_MS.length - 1)]; + startupCrashRestarts++; + return delay; + } } public PulseAudioComponent(Context context) { @@ -167,11 +213,14 @@ public class PulseAudioComponent extends SessionPart { if (micFifoPath != null && !micFifoPath.isEmpty()) { new File(micFifoPath).delete(); } + boolean standardMode = host.preferStandardPerformanceMode(); + String initialPerformanceMode = standardMode ? "0" : "1"; ArrayList config = new ArrayList<>(); config.add("load-module module-native-protocol-unix auth-anonymous=1 auth-cookie-enabled=0 socket=\"" + socket().getAbsolutePath() + "\""); config.add(".nofail"); - config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=1 adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls); + config.add("load-module module-directaudio-native-sink sink_name=DirectAudio performance_mode=" + + initialPerformanceMode + " adaptive=1 decay=0 limiter=1 watchdog=1 volume=1.0 control_dir=" + deviceControls); config.add("set-default-sink DirectAudio"); config.add(".fail"); if (micFifoPath != null && !micFifoPath.isEmpty()) { @@ -197,7 +246,25 @@ public class PulseAudioComponent extends SessionPart { final java.io.PrintWriter out = openLog(); if (!host.launch(generation, () -> HostProcess.startUncounted(command, env.toArray(new String[0]), workingDir, status -> { if (host.exited(generation)) { - Log.w(TAG, "audio host exited with status " + status + "; restarting"); + long delayMs = host.nextRestartDelayMs(generation); + if (delayMs < 0) { + String msg = "audio host exited with status " + status + + " before a client sink came up too many times; not restarting again in this session"; + Log.w(TAG, msg); + note(out, msg); + return; + } + Log.w(TAG, "audio host exited with status " + status + "; restarting" + + (host.preferStandardPerformanceMode() ? " with standard AAudio mode" : "") + + (delayMs > 0 ? " in " + delayMs + " ms" : "")); + if (delayMs > 0) { + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } start(generation); } }, @@ -211,6 +278,24 @@ public class PulseAudioComponent extends SessionPart { guard.start(); } + private boolean loadDirectAudioSink(long token, String performanceMode) { + if ("0".equals(performanceMode)) pactlOk(token, "unload-module", "module-directaudio-native-sink"); + String loaded = pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", + "performance_mode=" + performanceMode, + "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls); + if (loaded == null) return false; + if (pactlOk(token, "set-default-sink", "DirectAudio")) return true; + String moduleId = loaded.trim(); + pactlOk(token, "unload-module", moduleId.matches("\\d+") ? moduleId : "module-directaudio-native-sink"); + return false; + } + + private boolean loadPlainAAudioSink(long token, String performanceMode) { + return pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", + "performance_mode=" + performanceMode, "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) + && pactlOk(token, "set-default-sink", "AAudioSink"); + } + private void ensureClientSink(java.io.PrintWriter out, long token) { try { // Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the @@ -232,27 +317,42 @@ public class PulseAudioComponent extends SessionPart { if (sinks == null) { line = "== client sink: the daemon did not answer in 30 s; no fallback attempted"; } else if (sinks.contains("\tDirectAudio\t") || sinks.startsWith("DirectAudio\t") || sinks.contains("\tDirectAudio\n") || sinks.matches("(?s).*\\bDirectAudio\\b.*")) { - line = "== client sink: DirectAudio (module-directaudio-native-sink)"; + host.markSinkReady(token); + line = "== client sink: DirectAudio (module-directaudio-native-sink" + + (host.preferStandardPerformanceMode() ? ", standard mode" : "") + ")"; } else { // AAudio can refuse the first open with AAUDIO_ERROR_DISCONNECTED while Android is - // still switching the output route as the session starts (seen on a Galaxy S24 FE): - // try DirectAudio again, then the plain sink, a few times over ten seconds. + // still switching the output route (Galaxy S24 FE) or when low-latency MMAP output + // is rejected by the HAL (Samsung One UI). Retry low-latency once if it hasn't been + // disqualified yet, then fall back to performance_mode=0 (non-MMAP) on DirectAudio + // before trying the plain AAudio sink. String loadedAs = null; for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) { try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } - if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", - "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) - && pactlOk(token, "set-default-sink", "DirectAudio")) { - loadedAs = "DirectAudio on attempt " + attempt; - } else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", - "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) - && pactlOk(token, "set-default-sink", "AAudioSink")) { - loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt; + if (!host.live(token)) break; + if (attempt == 1 && !host.preferStandardPerformanceMode()) { + if (loadDirectAudioSink(token, "1")) { + loadedAs = "DirectAudio on attempt " + attempt; + break; + } + if (!host.live(token)) break; + host.markLowLatencyFailed(token); + } + if (loadDirectAudioSink(token, "0")) { + loadedAs = "DirectAudio (standard mode) on attempt " + attempt; + } else if (host.live(token) && loadPlainAAudioSink(token, "0")) { + loadedAs = "the plain AAudio sink (AAudioSink, standard mode) on attempt " + attempt; } } - line = loadedAs != null ? "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs - : "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound." - + " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this"; + if (loadedAs != null) { + host.markSinkReady(token); + line = "== client sink: DirectAudio did not come up at start; retried and got " + loadedAs; + } else if (!host.live(token)) { + line = "== client sink: audio host exited during sink recovery"; + } else { + line = "== client sink: DirectAudio did not come up and the AAudio fallback failed too after 5 retries - no client sound." + + " If audio.log shows AAUDIO_ERROR_DISCONNECTED, Android refused the audio output: rebooting the phone usually fixes this"; + } Log.w(TAG, line); } Log.i(TAG, line); @@ -407,11 +507,22 @@ public class PulseAudioComponent extends SessionPart { continue; } File destination = new File(workingDir, lib); + File temp = null; try (InputStream in = resource.openStream()) { - Files.copy(in, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); - FileUtils.chmod(destination, 0771); + temp = File.createTempFile(lib + ".", ".tmp", workingDir); + Files.copy(in, temp.toPath(), StandardCopyOption.REPLACE_EXISTING); + FileUtils.chmod(temp, 0771); + try { + Files.move(temp.toPath(), destination.toPath(), + StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(temp.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + temp = null; } catch (Exception e) { Log.w(TAG, "copy " + lib, e); + } finally { + if (temp != null) temp.delete(); } } } diff --git a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt index 63c1003b4f..f104ed089b 100644 --- a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt @@ -176,4 +176,68 @@ class PulseAudioComponentTest { pool.shutdownNow() } } + + @Test + fun startupCrashDowngradesToStandardModeAndCapsRestartLoop() { + val host = PulseAudioComponent.HostLifecycle { } + val generation = host.begin() + assertFalse(host.preferStandardPerformanceMode()) + + var pid = 31500 + for (i in 0 until PulseAudioComponent.HostLifecycle.MAX_STARTUP_CRASH_RESTARTS) { + assertTrue(host.launch(generation) { pid++ }) + assertTrue(host.exited(generation)) + val delay = host.nextRestartDelayMs(generation) + assertTrue("expected positive backoff on startup crash #$i, got $delay", delay > 0L) + assertTrue(host.preferStandardPerformanceMode()) + } + + // One more crash before any sink comes up must stop the hot crash-restart loop. + assertTrue(host.launch(generation) { pid++ }) + assertTrue(host.exited(generation)) + assertEquals(-1L, host.nextRestartDelayMs(generation)) + + // A fresh session resets both the fallback preference and the crash counter. + val next = host.begin() + assertFalse(host.preferStandardPerformanceMode()) + assertTrue(host.launch(next) { pid++ }) + assertTrue(host.exited(next)) + assertTrue(host.nextRestartDelayMs(next) > 0L) + } + + @Test + fun healthySinkResetsCrashCounterAndRestartsImmediately() { + val host = PulseAudioComponent.HostLifecycle { } + val generation = host.begin() + + // First startup crashes -> switches to standard mode with backoff. + assertTrue(host.launch(generation) { 31600 }) + assertTrue(host.exited(generation)) + assertTrue(host.nextRestartDelayMs(generation) > 0L) + assertTrue(host.preferStandardPerformanceMode()) + + // Replacement host brings up a working sink -> later runtime exit restarts immediately. + assertTrue(host.launch(generation) { 31601 }) + host.markSinkReady(host.token()) + assertTrue(host.exited(generation)) + assertEquals(0L, host.nextRestartDelayMs(generation)) + assertTrue(host.preferStandardPerformanceMode()) + } + + @Test + fun markLowLatencyFailedIgnoresStaleTokens() { + val host = PulseAudioComponent.HostLifecycle { } + val generation = host.begin() + assertTrue(host.launch(generation) { 31700 }) + val first = host.token() + val next = host.begin() + // Before the replacement launches, token still equals launches, but pid is stopped. + host.markLowLatencyFailed(first) + assertFalse(host.preferStandardPerformanceMode()) + assertTrue(host.launch(next) { 31701 }) + host.markLowLatencyFailed(first) + assertFalse(host.preferStandardPerformanceMode()) + host.markLowLatencyFailed(host.token()) + assertTrue(host.preferStandardPerformanceMode()) + } } From 34fff40b5615645104f89762c4a2d145eef93f69 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 2 Dec 2026 16:47:42 -0500 Subject: [PATCH 08/80] ci: run Kotlin unit tests separately from APK builds (#3566) Run Kotlin tests beside APK compilation while keeping merge and release checks intact. Pin the APK and test workflows to the same pull request base, retry Robolectric rate limits on both Maven Central hosts, and verify source parity when main advances. --- .github/workflows/authorship.yml | 8 +- .github/workflows/build.yml | 130 ++---------------- .github/workflows/release.yml | 7 + .github/workflows/unit-tests.yml | 182 ++++++++++++++++++++++++++ AGENTS.md | 4 +- app/build.gradle | 6 +- tools/ci/build-label.sh | 19 +++ tools/components/README.md | 7 +- tools/release/report-build.sh | 28 +--- tools/release/validate_apk.py | 62 +++++++-- tools/tests/test_ci_checks.py | 49 ++++++- tools/tests/test_validate_apk.py | 32 ++++- tools/tests/test_xbox_build_source.py | 18 ++- 13 files changed, 381 insertions(+), 171 deletions(-) create mode 100644 .github/workflows/unit-tests.yml create mode 100755 tools/ci/build-label.sh diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml index 615267b6c0..857fb68023 100644 --- a/.github/workflows/authorship.yml +++ b/.github/workflows/authorship.yml @@ -7,7 +7,7 @@ on: push: branches: [main] workflow_run: - workflows: [Build APK] + workflows: [Build APK, Unit tests] types: [completed] workflow_dispatch: inputs: @@ -21,6 +21,12 @@ permissions: pull-requests: read statuses: write +# Build APK and Unit tests each trigger a validation, and the last one to post sets the status. Queued runs for a +# commit wait, so the newest one reads both results and posts last. +concurrency: + group: build-validation-${{ github.event.pull_request.head.sha || github.event.workflow_run.head_sha || inputs.pr_number || github.sha }} + cancel-in-progress: false + jobs: validate: name: Validate source and build result diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d713d0f493..e4229729de 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,5 @@ name: Build APK -run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} +run-name: ${{ github.event_name == 'pull_request' && format('building pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('building {0} on {1}', github.ref_name, github.sha) }} on: push: @@ -57,15 +57,18 @@ jobs: - name: Pin and merge the APK source id: merge if: github.event_name == 'pull_request' + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | set -euo pipefail - git fetch --no-tags origin main - echo "base-sha=$(git rev-parse origin/main)" >> "$GITHUB_OUTPUT" + # Unit tests uses the same event snapshot, including when either workflow is rerun. + git fetch --no-tags origin "$PR_BASE_SHA" + echo "base-sha=$PR_BASE_SHA" >> "$GITHUB_OUTPUT" git config user.name "ci" git config user.email "ci@users.noreply.github.com" # Partial clone: a merged blob that only exists in a fork's history can't be lazily fetched (GitHub: "not our ref"); merge-tree writes it locally first. - git merge-tree --write-tree HEAD origin/main >/dev/null || true - git merge --no-ff --no-edit origin/main + git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true + git merge --no-ff --no-edit FETCH_HEAD - name: Resolve trusted manifest base id: trusted if: github.event_name != 'pull_request' @@ -349,7 +352,7 @@ jobs: build: needs: [source, components, xbox, build-runner] - name: Compile APK and Android tests + name: Compile APK if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ${{ fromJSON(needs.build-runner.outputs.labels) }} timeout-minutes: 45 @@ -507,23 +510,7 @@ jobs: PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} BUILD_REF: ${{ github.ref_name }} BUILD_SHA: ${{ github.sha }} - run: | - if [[ -n "$(git status --porcelain)" ]]; then - tree_state=dirty - else - tree_state=clean - fi - echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV" - if [[ -n "$PR_NUMBER" ]]; then - label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}" - else - label="${BUILD_REF} at ${BUILD_SHA:0:7}" - fi - echo "label=$label" >> "$GITHUB_OUTPUT" - echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" - echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" - echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV" - echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" + run: bash tools/ci/build-label.sh - name: Rust toolchain for the store engines (aarch64-linux-android) id: rust @@ -734,101 +721,6 @@ jobs: if-no-files-found: ignore overwrite: true - - name: Resolve the Robolectric version - id: robolectric - run: | - echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" - # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. - # The cache path sits beside the workspace because runner homes are at different depths from it, and - # actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects - # "..". Runners that keep their own ~/.m2 skip the cache. - - name: Place Robolectric's Android jars beside the workspace - id: robolectric-jars - run: | - set -euo pipefail - jars="$GITHUB_WORKSPACE/../robolectric-jars" - m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" - if [ -d "$m2" ] && [ ! -L "$m2" ]; then - echo "cache=false" >> "$GITHUB_OUTPUT" - else - mkdir -p "$jars" "$(dirname "$m2")" - jars=$(cd "$jars" && pwd) - ln -sfn "$jars" "$m2" - echo "path=$jars" >> "$GITHUB_OUTPUT" - echo "cache=true" >> "$GITHUB_OUTPUT" - fi - - name: Restore Robolectric's Android jars - id: robolectric-cache - if: steps.robolectric-jars.outputs.cache == 'true' - uses: actions/cache/restore@v4 - with: - path: ${{ steps.robolectric-jars.outputs.path }} - key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} - restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}- - - name: Count the restored Robolectric jars - if: steps.robolectric-jars.outputs.cache == 'true' - run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV" - - name: Unit tests - id: unit-tests - env: - DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} - SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} - run: | - set -o pipefail - mkdir -p app/build - # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. - for wait in 60 180 0; do - status=0 - ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$? - if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://repo\.maven\.apache\.org/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://repo\.maven\.apache\.org/)' app/build/unit-tests.log; then - exit "$status" - fi - echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" - sleep "$wait" - done - - # actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache. - # Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first. - - name: Save Robolectric's Android jars - id: robolectric-jars-final - if: always() && steps.robolectric-jars.outputs.cache == 'true' - run: | - python3 - <<'PY' - import glob, os, zipfile - root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars') - for f in glob.glob(os.path.join(root, '**', '*'), recursive=True): - if not os.path.isfile(f): - continue - try: - ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None - except Exception: - ok = False - if not ok: - os.remove(f) - PY - after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) - [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true - - name: Store Robolectric's Android jars - if: always() && steps.robolectric-jars-final.outputs.save == 'true' - uses: actions/cache/save@v4 - with: - path: ${{ steps.robolectric-jars.outputs.path }} - key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} - - - name: Upload unit test diagnostics - id: unit-test-diagnostics - if: always() && steps.unit-tests.outcome != 'skipped' - uses: actions/upload-artifact@v4 - with: - name: unit-test-results - path: | - app/build/unit-tests.log - app/build/test-results/testReleaseUnitTest/ - app/build/reports/tests/testReleaseUnitTest/ - if-no-files-found: ignore - retention-days: 14 - overwrite: true - - name: Sign with the testkey (v1 + v2 + v3) run: | set -euo pipefail @@ -884,8 +776,6 @@ jobs: PR: ${{ github.event.pull_request.number }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} BUILD_OUTCOME: ${{ steps.build.outcome }} - UNIT_TEST_OUTCOME: ${{ steps.unit-tests.outcome }} - TEST_DIAGNOSTICS_URL: ${{ steps.unit-test-diagnostics.outputs.artifact-url }} APK_OUTCOME: ${{ steps.apk-upload.outcome }} run: bash tools/release/report-build.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eabc77a358..24fd2ffa9a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -47,6 +47,13 @@ jobs: echo "::error::main ${GITHUB_SHA::7} has no successful Build APK run yet: wait for it, then release" exit 1 fi + tests=$(gh run list -R "$GITHUB_REPOSITORY" --workflow unit-tests.yml --branch main --commit "$GITHUB_SHA" \ + --json conclusion,event,headSha -L 20 | + jq -r --arg sha "$GITHUB_SHA" '[.[] | select(.headSha == $sha and (.event == "push" or .event == "workflow_dispatch"))][0].conclusion // empty') + if [ "$tests" != success ]; then + echo "::error::main ${GITHUB_SHA::7} has no passing Unit tests run (${tests:-none yet}): fix or wait for it, then release" + exit 1 + fi variants=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .) echo "run_id=$id" >> "$GITHUB_OUTPUT" echo "variants=$variants" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml new file mode 100644 index 0000000000..a525311b34 --- /dev/null +++ b/.github/workflows/unit-tests.yml @@ -0,0 +1,182 @@ +name: Unit tests +run-name: ${{ github.event_name == 'pull_request' && format('unit tests for pr {0} on {1} against {2}', github.event.pull_request.number, github.event.pull_request.head.sha, github.event.pull_request.base.sha) || format('unit tests for {0} on {1}', github.ref_name, github.sha) }} + +# Runs beside Build APK rather than inside it, so a test build is published as soon as the APK compiles. +# Build validation folds this workflow's result into the "Build APK" commit status, and Release APKs requires it. +on: + push: + branches: [ main ] + paths-ignore: + - '**/*.md' + - 'LICENSE' + - '.gitignore' + - 'docs/**' + - '.github/ISSUE_TEMPLATE/**' + pull_request: + branches: [ main ] + types: [ opened, synchronize, reopened, ready_for_review ] + paths-ignore: + - '**/*.md' + - 'LICENSE' + - '.gitignore' + - 'docs/**' + - '.github/ISSUE_TEMPLATE/**' + workflow_dispatch: + +permissions: + contents: read + actions: read + +concurrency: + group: unit-tests-${{ github.event.pull_request.number || (github.event_name == 'push' && 'main') || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' }} + +jobs: + unit-tests: + name: Unit tests + if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + sparse-checkout: | + /* + !/docs/releases/media/ + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Merge the pinned APK base + if: github.event_name == 'pull_request' + env: + PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + git config user.name "ci" + git config user.email "ci@users.noreply.github.com" + git fetch --no-tags origin "$PR_BASE_SHA" + git merge-tree --write-tree HEAD FETCH_HEAD >/dev/null || true + git merge --no-ff --no-edit FETCH_HEAD || { echo "::error::the pull request conflicts with main; Build APK lists the files"; exit 1; } + + - name: Check out MaliBridge + run: git submodule update --init external/MaliBridge + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - uses: gradle/actions/setup-gradle@v4 + with: + cache-read-only: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }} + cache-cleanup: ${{ github.event_name == 'pull_request' && 'never' || 'on-success' }} + + - name: Resolve the pinned Android NDK + run: bash tools/ci/resolve-ndk.sh + + - name: Set the APK build label + id: build-label + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_TITLE: ${{ github.event.pull_request.title }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + BUILD_REF: ${{ github.ref_name }} + BUILD_SHA: ${{ github.sha }} + run: bash tools/ci/build-label.sh + + - name: Resolve the Robolectric version + id: robolectric + run: | + echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT" + # Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes. + # The cache path sits beside the workspace because runner homes are at different depths from it, and + # actions/cache stores paths relative to the workspace. It is passed as an absolute path: the save action rejects + # "..". Runners that keep their own ~/.m2 skip the cache. + - name: Place Robolectric's Android jars beside the workspace + id: robolectric-jars + run: | + set -euo pipefail + jars="$GITHUB_WORKSPACE/../robolectric-jars" + m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented" + if [ -d "$m2" ] && [ ! -L "$m2" ]; then + echo "cache=false" >> "$GITHUB_OUTPUT" + else + mkdir -p "$jars" "$(dirname "$m2")" + jars=$(cd "$jars" && pwd) + ln -sfn "$jars" "$m2" + echo "path=$jars" >> "$GITHUB_OUTPUT" + echo "cache=true" >> "$GITHUB_OUTPUT" + fi + - name: Restore Robolectric's Android jars + id: robolectric-cache + if: steps.robolectric-jars.outputs.cache == 'true' + uses: actions/cache/restore@v4 + with: + path: ${{ steps.robolectric-jars.outputs.path }} + key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} + restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}- + - name: Count the restored Robolectric jars + if: steps.robolectric-jars.outputs.cache == 'true' + run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV" + - name: Unit tests + id: unit-tests + env: + DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }} + SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }} + run: | + set -o pipefail + mkdir -p app/build + # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. + for wait in 60 180 0; do + status=0 + ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$? + if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' app/build/unit-tests.log; then + exit "$status" + fi + echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" + sleep "$wait" + done + + # actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache. + # Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first. + - name: Save Robolectric's Android jars + id: robolectric-jars-final + if: always() && steps.robolectric-jars.outputs.cache == 'true' + run: | + python3 - <<'PY' + import glob, os, zipfile + root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars') + for f in glob.glob(os.path.join(root, '**', '*'), recursive=True): + if not os.path.isfile(f): + continue + try: + ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None + except Exception: + ok = False + if not ok: + os.remove(f) + PY + after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) + [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true + - name: Store Robolectric's Android jars + if: always() && steps.robolectric-jars-final.outputs.save == 'true' + uses: actions/cache/save@v4 + with: + path: ${{ steps.robolectric-jars.outputs.path }} + key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }} + + - name: Upload unit test diagnostics + id: unit-test-diagnostics + if: always() && steps.unit-tests.outcome != 'skipped' + uses: actions/upload-artifact@v4 + with: + name: unit-test-results + path: | + app/build/unit-tests.log + app/build/test-results/testReleaseUnitTest/ + app/build/reports/tests/testReleaseUnitTest/ + if-no-files-found: ignore + retention-days: 14 + overwrite: true diff --git a/AGENTS.md b/AGENTS.md index 97930d6563..d89bdf632c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ - For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step. - `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`. - Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout. -- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally. +- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest` in the `Unit tests` workflow, beside Build APK; when a test fails only in CI, run the release variant locally. - Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests ''` and `python3 -m unittest discover -s tools/tests -p 'test_*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI. - For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape. - After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`. @@ -31,7 +31,7 @@ - CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge. - Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors. - Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them. -- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results`. Don't call a failure a runner problem until you have read it. +- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs//logs`, or `gh run download -n unit-test-results` from the `Unit tests` workflow run. Don't call a failure a runner problem until you have read it. - Only these are known flakes worth a `gh run rerun --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real. - A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`. diff --git a/app/build.gradle b/app/build.gradle index 70336a0472..b858daf493 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -82,6 +82,8 @@ def buildBranch = providers.environmentVariable('GITHUB_HEAD_REF').getOrNull()?. ?: gitValue(['branch', '--show-current']) ?: '' def escapeJava = { String value -> value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', ' ').replace('\r', ' ') } def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' +// The Unit tests workflow compiles no APK, so it has no add-on packs to pin. +def unitTestsOnly = project.findProperty('unitTestsOnly')?.toString()?.toBoolean() ?: false def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim() def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' } def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() @@ -96,10 +98,12 @@ def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines() def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt', 'epic'].collectEntries { name -> def pack = file("build/packs/${name}.tar.zst") if (!pack.isFile()) { - if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") + if (ciBuild && !unitTestsOnly) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") if (name == 'proot' && prootPackPin.PROOT_PACK_SHA256) { return [(name): [sha256: prootPackPin.PROOT_PACK_SHA256, size: (prootPackPin.PROOT_PACK_SIZE ?: '0') as long]] } + // A CI APK pins every pack, and CI_BUILD code assumes that, so the tests see a placeholder pin. + if (unitTestsOnly) return [(name): [sha256: '0' * 64, size: 0L]] return [(name): [sha256: '', size: 0L]] } def digest = java.security.MessageDigest.getInstance('SHA-256') diff --git a/tools/ci/build-label.sh b/tools/ci/build-label.sh new file mode 100755 index 0000000000..806e0366fc --- /dev/null +++ b/tools/ci/build-label.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Exports the build metadata Gradle bakes into BuildConfig and prints the label for DROIDDECK_BUILD_LABEL. +set -euo pipefail +if [[ -n "$(git status --porcelain)" ]]; then + tree_state=dirty +else + tree_state=clean +fi +echo "DROIDDECK_BUILD_TREE_STATE=$tree_state" >> "$GITHUB_ENV" +if [[ -n "${PR_NUMBER:-}" ]]; then + label="pr${PR_NUMBER} at ${PR_HEAD_SHA:0:7}" +else + label="${BUILD_REF} at ${BUILD_SHA:0:7}" +fi +echo "label=$label" >> "$GITHUB_OUTPUT" +echo "DROIDDECK_SOURCE_COMMIT=${PR_HEAD_SHA:-$BUILD_SHA}" >> "$GITHUB_ENV" +echo "DROIDDECK_PR_NUMBER=${PR_NUMBER:-0}" >> "$GITHUB_ENV" +echo "DROIDDECK_PR_TITLE=${PR_TITLE//$'\n'/ }" >> "$GITHUB_ENV" +echo "Build: \`$label\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/tools/components/README.md b/tools/components/README.md index 782d8b9f14..d1d5276311 100644 --- a/tools/components/README.md +++ b/tools/components/README.md @@ -10,13 +10,18 @@ flowchart LR Source[Pin source tree] --> Components[Prepare verified components] Source --> Xbox[Xbox ARM64 backend] Source --> Tests[Python and native tests] - Components --> APK[Compile APK and Android tests] + Components --> APK[Compile APK] Xbox --> APK APK --> Gate[Compile and test APK gate] Tests --> Gate Gate --> Publish[Main only: signing and publishing] ``` +Kotlin unit tests run in the separate `Unit tests` workflow (`unit-tests.yml`), so a +PR test build is published as soon as the APK compiles. Build validation folds both +workflows into the `Build APK` commit status, and Release APKs requires both for the +released commit. + All workers verify the same source tree. The component artifact records that tree, recipe identities and every output hash; the APK worker verifies the inventory before building. This handoff verifies consistency within the same CI run. It is diff --git a/tools/release/report-build.sh b/tools/release/report-build.sh index 835bb6c65e..f9757e5052 100644 --- a/tools/release/report-build.sh +++ b/tools/release/report-build.sh @@ -7,37 +7,21 @@ MARK="" echo [ -f /tmp/pr-merge.md ] && cat /tmp/pr-merge.md echo - case "$BUILD_OUTCOME:$UNIT_TEST_OUTCOME:$APK_OUTCOME" in - success:success:success) + case "$BUILD_OUTCOME:$APK_OUTCOME" in + success:success) echo "### Build passed" echo - echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key." + echo "The \`droiddeck-apk\` artifact is [on this run]($RUN_URL), signed with the public test key. Unit tests run in the separate **Unit tests** workflow and must pass before merging." echo - echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds after the full build passes. Label the PR \`no-test-build\` to skip that." + echo "Same-repository PRs and PRs opened by contributors listed in \`.github/trusted-test-builds.txt\` are eligible for automatic release-signed test builds once the APK compiles. Label the PR \`no-test-build\` to skip that." echo "For other PRs, a maintainer can add the \`publish-test\` label to request a signed build." echo echo "Fallback: [open **PR Release Publish**]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/workflows/pr-release-publish.yml) on \`main\` and enter PR \`$PR\`." ;; - success:success:*) + success:*) echo "### APK publication incomplete" echo - echo "Compilation and unit tests passed, but APK publication did not complete. See [the run]($RUN_URL)." - ;; - success:failure:*) - echo "### ERROR: Unit tests failed" - echo - echo "The APK compiled, but unit tests failed. No installable artifact was published." - echo - if [ -n "$TEST_DIAGNOSTICS_URL" ]; then - echo "The [unit-test-results]($TEST_DIAGNOSTICS_URL) artifact contains the test log and any generated reports." - else - echo "The test diagnostics upload did not complete. See [the test log]($RUN_URL)." - fi - ;; - success:*) - echo "### Build incomplete" - echo - echo "The APK compiled, but unit tests did not complete successfully. See [the run]($RUN_URL)." + echo "Compilation passed, but APK publication did not complete. See [the run]($RUN_URL)." ;; failure:*) echo "### ERROR: Build failed" diff --git a/tools/release/validate_apk.py b/tools/release/validate_apk.py index 7a3fb67530..efc96317b3 100644 --- a/tools/release/validate_apk.py +++ b/tools/release/validate_apk.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import json import os +import re import subprocess import sys import time @@ -40,6 +41,39 @@ def compilation_state(run, jobs): return "failure" if run["status"] == "completed" else "pending" +def run_state(run): + if run["status"] != "completed": + return "pending" + return "success" if run["conclusion"] == "success" else "failure" + + +def latest_run(repo, workflow, sha, source_event): + query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20}) + runs = api(f"repos/{repo}/actions/workflows/{workflow}/runs?{query}")["workflow_runs"] + runs = [item for item in runs if item["head_sha"] == sha] + return max(runs, key=lambda item: item["id"]) if runs else None + + +def pull_request_run_base(run, sha): + # A PR can reopen at the same head SHA after main advances. Do not mix results + # from different event snapshots, even if both workflows individually passed. + title = run.get("display_title") or "" + match = re.search(rf" on {re.escape(sha)} against ([0-9a-f]{{40}})$", title) + return match[1] if match else None + + +def combined_state(build, tests): + if build == "failure": + return "failure", "APK compilation failed" + if tests == "failure": + return "failure", "Unit tests failed" + if build == "pending": + return "pending", "Source validated; awaiting APK compilation" + if tests == "pending": + return "pending", "APK compiled; awaiting unit tests" + return "success", "Source validation, APK compilation and unit tests passed" + + def fetch_source(ref, sha): subprocess.run(["git", "fetch", "--no-tags", "origin", ref], check=True) fetched = subprocess.check_output(["git", "rev-parse", "FETCH_HEAD"], text=True).strip() @@ -123,19 +157,25 @@ def main(): state = "success" description = "Source validated; no APK source changes" return - query = urlencode({"head_sha": sha, "event": source_event, "per_page": 20}) - runs = api(f"repos/{repo}/actions/workflows/build.yml/runs?{query}")["workflow_runs"] - runs = [item for item in runs if item["head_sha"] == sha] - if runs: - latest = max(runs, key=lambda item: item["id"]) + build_state = tests_state = "pending" + latest = latest_run(repo, "build.yml", sha, source_event) + if latest: jobs = api(f"repos/{repo}/actions/runs/{latest['id']}/jobs?per_page=100")["jobs"] - state = compilation_state(latest, jobs) + build_state = compilation_state(latest, jobs) target = latest["html_url"] - else: - state = "pending" - description = {"pending": "Source validated; awaiting APK compilation", - "success": "Source validation and APK compilation passed", - "failure": "APK compilation failed"}[state] + tests = latest_run(repo, "unit-tests.yml", sha, source_event) + if tests: + if pr and latest and build_state == "success": + build_base = pull_request_run_base(latest, sha) + tests_base = pull_request_run_base(tests, sha) + if not build_base or build_base != tests_base: + state = "pending" + description = "APK and unit tests must run against the same main commit" + return + tests_state = run_state(tests) + if tests_state == "failure" and build_state != "failure": + target = tests["html_url"] + state, description = combined_state(build_state, tests_state) finally: api(f"repos/{repo}/statuses/{sha}", "--method", "POST", "-f", "context=Build APK", "-f", f"state={state}", diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index a5982366ac..5b45850fc8 100644 --- a/tools/tests/test_ci_checks.py +++ b/tools/tests/test_ci_checks.py @@ -25,7 +25,7 @@ class CiChecksTest(unittest.TestCase): self.assertIn("gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit])", gradle) def test_robolectric_cache_saves_and_restores_the_same_absolute_path(self): - steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps'] + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] caches = [step['with'] for step in steps if step.get('uses', '').startswith('actions/cache')] for cache in caches: for path in cache['path'].split('\n'): @@ -34,13 +34,17 @@ class CiChecksTest(unittest.TestCase): self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2) def test_unit_test_retry_requires_maven_exception(self): - steps = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps'] + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] run = next(step['run'] for step in steps if step.get('id') == 'unit-tests') line = next(line for line in run.splitlines() if 'grep -Eq' in line) pattern = shlex.split(line)[shlex.split(line).index('-Eq') + 1] for log, expected in ( ("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo.maven.apache.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0), ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo.maven.apache.org/maven2/a.jar", 0), + ("Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: Could not GET 'https://repo1.maven.org/maven2/a.jar'. Received status code 429 from server: Too Many Requests", 0), + ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://repo1.maven.org/maven2/a.pom.sha512", 0), + ("Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: https://example.org/a.jar", 1), + ("Caused by: java.io.IOException: Server returned HTTP response code: 500 for URL: https://repo1.maven.org/maven2/a.jar", 1), ("SomeTest > test FAILED: Too Many Requests", 1), ("Caused by: java.lang.AssertionError: HTTP 429", 1), ): @@ -59,15 +63,46 @@ class CiChecksTest(unittest.TestCase): self.assertEqual(result.strip(), '2') def test_build_and_tests_use_identical_generated_metadata(self): - jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] - steps = {step.get('id'): step for step in jobs['build']['steps']} - self.assertEqual(steps['build']['env'], steps['unit-tests']['env']) - self.assertIn('DROIDDECK_BUILD_LABEL', steps['unit-tests']['env']) - self.assertIn('SGDB_API_KEY', steps['unit-tests']['env']) + build = {step.get('id'): step for step in + yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs']['build']['steps']} + tests = {step.get('id'): step for step in + yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps']} + self.assertEqual(build['build']['env'], tests['unit-tests']['env']) + self.assertIn('DROIDDECK_BUILD_LABEL', tests['unit-tests']['env']) + self.assertIn('SGDB_API_KEY', tests['unit-tests']['env']) + self.assertEqual(build['build-label'], tests['build-label']) gradle = (ROOT / 'app/build.gradle').read_text() self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle) self.assertIn('outputs.upToDateWhen { false }', gradle) + def test_unit_tests_do_not_hold_up_the_apk(self): + build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text()) + for step in build['jobs']['build']['steps']: + self.assertNotIn('UnitTest', step.get('run', '')) + tests = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text()) + for event in ('push', 'pull_request'): + self.assertEqual(tests[True][event], build[True][event]) + authorship = yaml.safe_load((ROOT / '.github/workflows/authorship.yml').read_text()) + self.assertEqual(set(authorship[True]['workflow_run']['workflows']), {build['name'], tests['name']}) + self.assertIn('workflow_run.head_sha', authorship['concurrency']['group']) + self.assertFalse(authorship['concurrency']['cancel-in-progress']) + self.assertIn('unit-tests.yml', (ROOT / '.github/workflows/release.yml').read_text()) + run = next(step['run'] for step in tests['jobs']['unit-tests']['steps'] if step.get('id') == 'unit-tests') + self.assertIn('-PunitTestsOnly=true', run) + + def test_apk_and_unit_tests_pin_the_same_pr_event_base(self): + for filename, job, name in ( + ("build.yml", "source", "Pin and merge the APK source"), + ("unit-tests.yml", "unit-tests", "Merge the pinned APK base"), + ): + with self.subTest(workflow=filename): + workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) + step = next(step for step in workflow["jobs"][job]["steps"] if step.get("name") == name) + self.assertEqual(step["env"]["PR_BASE_SHA"], "${{ github.event.pull_request.base.sha }}") + self.assertIn('git fetch --no-tags origin "$PR_BASE_SHA"', step["run"]) + self.assertIn("git merge --no-ff --no-edit FETCH_HEAD", step["run"]) + self.assertIn("github.event.pull_request.base.sha", workflow["run-name"]) + def test_independent_jobs_wait_only_for_the_pinned_source(self): jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] for name in ('xbox', 'python-tests', 'components-runner'): diff --git a/tools/tests/test_validate_apk.py b/tools/tests/test_validate_apk.py index 707779a9f6..f6afd33718 100644 --- a/tools/tests/test_validate_apk.py +++ b/tools/tests/test_validate_apk.py @@ -28,7 +28,7 @@ class ValidateApkTest(unittest.TestCase): def git(self, *args): return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip() - def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False): + def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write", fork=False, tests="success", build_base="a" * 40, tests_base="a" * 40): (self.root / filename).parent.mkdir(parents=True, exist_ok=True) (self.root / filename).write_text(message) self.git("add", filename) @@ -56,7 +56,16 @@ class ValidateApkTest(unittest.TestCase): if path.endswith("/pulls?state=open&head=contributor%3Afix%2Fbranch"): return [pr] if "workflows/build.yml/runs?" in path: - return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", "html_url": "https://example.org/build"}]} + title = f"building pr 1 on {sha}" + (f" against {build_base}" if build_base else "") + return {"workflow_runs": [{"id": 7, "head_sha": sha, "status": "completed", + "display_title": title, "html_url": "https://example.org/build"}]} + if "workflows/unit-tests.yml/runs?" in path: + if tests is None: + return {"workflow_runs": []} + title = f"unit tests for pr 1 on {sha}" + (f" against {tests_base}" if tests_base else "") + return {"workflow_runs": [{"id": 9, "head_sha": sha, "html_url": "https://example.org/tests", + "display_title": title, "status": "in_progress" if tests == "pending" else "completed", + "conclusion": None if tests == "pending" else tests}]} if path.endswith("/jobs?per_page=100"): return {"jobs": [{"name": "Compile and test APK", "status": "in_progress" if result == "pending" else "completed", "conclusion": result}]} raise AssertionError(path) @@ -85,6 +94,25 @@ class ValidateApkTest(unittest.TestCase): self.validate(result=result) self.assertEqual(self.statuses[-1]["state"], result) + def test_unit_tests_must_pass_too(self): + for tests, state in (("pending", "pending"), (None, "pending"), ("failure", "failure"), ("cancelled", "failure")): + with self.subTest(tests=tests): + self.validate(tests=tests) + self.assertEqual(self.statuses[-1]["state"], state) + self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/tests") + + def test_successful_runs_must_use_the_same_pr_base(self): + for build_base, tests_base in (("a" * 40, "b" * 40), ("a" * 40, None), (None, "a" * 40)): + with self.subTest(build_base=build_base, tests_base=tests_base): + self.validate(build_base=build_base, tests_base=tests_base) + self.assertEqual(self.statuses[-1]["state"], "pending") + self.assertIn("same main commit", self.statuses[-1]["description"]) + + def test_a_compile_failure_is_reported_before_test_results(self): + self.validate(result="failure", tests="failure") + self.assertEqual(self.statuses[-1]["description"], "APK compilation failed") + self.assertEqual(self.statuses[-1]["target_url"], "https://example.org/build") + def test_superseded_event_cannot_replace_current_status(self): self.validate(stale=True) self.assertEqual(self.statuses, []) diff --git a/tools/tests/test_xbox_build_source.py b/tools/tests/test_xbox_build_source.py index 427cea3425..7a3ba0030e 100644 --- a/tools/tests/test_xbox_build_source.py +++ b/tools/tests/test_xbox_build_source.py @@ -11,8 +11,10 @@ class XboxBuildSourceTest(unittest.TestCase): import yaml except ImportError: self.fail('PyYAML is required to execute workflow steps') - workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text()) - jobs = workflow['jobs'] + workflows = Path(__file__).resolve().parents[2] / '.github/workflows' + jobs = yaml.safe_load((workflows / 'build.yml').read_text())['jobs'] + unit_jobs = yaml.safe_load((workflows / 'unit-tests.yml').read_text())['jobs'] + jobs.update(unit_jobs) step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name) with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -31,13 +33,17 @@ class XboxBuildSourceTest(unittest.TestCase): git('switch', '-q', 'main') (root / 'backend').write_text('merged backend') git('commit', '-qam', 'backend changed after branch') - for name in ('source', 'xbox', 'components', 'apk', 'tests', 'dispatch'): + event_base = git('rev-parse', 'HEAD') + for name in ('source', 'xbox', 'components', 'apk', 'tests', 'unit-tests', 'dispatch'): git('clone', '-q', str(root), str(root / name)) git('checkout', '-q', head, cwd=root / name) output = root / 'output' - env['GITHUB_OUTPUT'] = str(output) + env.update(GITHUB_OUTPUT=str(output), PR_BASE_SHA=event_base) + (root / 'backend').write_text('newer main, after PR event') + git('commit', '-qam', 'main advanced before source pinning') subprocess.run(['bash', '-c', step('source', 'Pin and merge the APK source')], cwd=root / 'source', env=env, check=True, capture_output=True) base = output.read_text().strip().split('=', 1)[1] + self.assertEqual(base, event_base) tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'source') (root / 'backend').write_text('newer main, after backend build') git('commit', '-qam', 'main advanced again') @@ -51,6 +57,10 @@ class XboxBuildSourceTest(unittest.TestCase): subprocess.run(['bash', '-c', step('python-tests', 'Verify backend and test source match')], cwd=root / 'tests', env=env, check=True, capture_output=True) self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'tests'), tree) + subprocess.run(['bash', '-c', step('unit-tests', 'Merge the pinned APK base')], cwd=root / 'unit-tests', env=env, check=True, capture_output=True) + self.assertEqual((root / 'unit-tests/backend').read_text(), 'merged backend') + self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'unit-tests'), tree) + env['SOURCE_TREE'] = tree for job in ('xbox', 'components'): subprocess.run(['bash', '-c', step(job, 'Merge the pinned APK base')], cwd=root / job, env=env, check=True, capture_output=True) From 4ab9635ceb3ae73b4caa0e3ec0e22dca5c53629c Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:45:22 -0500 Subject: [PATCH 09/80] fix(desktop): run Plasma, its helpers and the apps it opens outside Android's child-process count (#3599) --- app/src/main/AndroidManifest.xml | 64 ++++++++++++++ .../launcher/runtime/GuestWorkers.kt | 87 ++++++++++++++++++- docs/phantom-processes.md | 27 +++++- tools/linuxfs/desktop/droiddeck-desktop | 16 +++- tools/linuxfs/desktop/firefox-droiddeck.js | 8 ++ .../usr/local/bin/droiddeck-pad-defaults | 23 +++-- .../overlay/usr/local/bin/droiddeck-session | 6 +- tools/nativeguest/hook/handoff.c | 27 +++++- tools/tests/test_native_hook_handoff.py | 43 ++++++++- 9 files changed, 281 insertions(+), 20 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6ec55c4825..38e888731e 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -481,5 +481,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 d0435876b7..4d6a1de6fb 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -224,6 +224,70 @@ class GuestWorker60 : GuestWorker() class GuestWorker61 : GuestWorker() class GuestWorker62 : GuestWorker() class GuestWorker63 : GuestWorker() +class GuestWorker64 : GuestWorker() +class GuestWorker65 : GuestWorker() +class GuestWorker66 : GuestWorker() +class GuestWorker67 : GuestWorker() +class GuestWorker68 : GuestWorker() +class GuestWorker69 : GuestWorker() +class GuestWorker70 : GuestWorker() +class GuestWorker71 : GuestWorker() +class GuestWorker72 : GuestWorker() +class GuestWorker73 : GuestWorker() +class GuestWorker74 : GuestWorker() +class GuestWorker75 : GuestWorker() +class GuestWorker76 : GuestWorker() +class GuestWorker77 : GuestWorker() +class GuestWorker78 : GuestWorker() +class GuestWorker79 : GuestWorker() +class GuestWorker80 : GuestWorker() +class GuestWorker81 : GuestWorker() +class GuestWorker82 : GuestWorker() +class GuestWorker83 : GuestWorker() +class GuestWorker84 : GuestWorker() +class GuestWorker85 : GuestWorker() +class GuestWorker86 : GuestWorker() +class GuestWorker87 : GuestWorker() +class GuestWorker88 : GuestWorker() +class GuestWorker89 : GuestWorker() +class GuestWorker90 : GuestWorker() +class GuestWorker91 : GuestWorker() +class GuestWorker92 : GuestWorker() +class GuestWorker93 : GuestWorker() +class GuestWorker94 : GuestWorker() +class GuestWorker95 : GuestWorker() +class GuestWorker96 : GuestWorker() +class GuestWorker97 : GuestWorker() +class GuestWorker98 : GuestWorker() +class GuestWorker99 : GuestWorker() +class GuestWorker100 : GuestWorker() +class GuestWorker101 : GuestWorker() +class GuestWorker102 : GuestWorker() +class GuestWorker103 : GuestWorker() +class GuestWorker104 : GuestWorker() +class GuestWorker105 : GuestWorker() +class GuestWorker106 : GuestWorker() +class GuestWorker107 : GuestWorker() +class GuestWorker108 : GuestWorker() +class GuestWorker109 : GuestWorker() +class GuestWorker110 : GuestWorker() +class GuestWorker111 : GuestWorker() +class GuestWorker112 : GuestWorker() +class GuestWorker113 : GuestWorker() +class GuestWorker114 : GuestWorker() +class GuestWorker115 : GuestWorker() +class GuestWorker116 : GuestWorker() +class GuestWorker117 : GuestWorker() +class GuestWorker118 : GuestWorker() +class GuestWorker119 : GuestWorker() +class GuestWorker120 : GuestWorker() +class GuestWorker121 : GuestWorker() +class GuestWorker122 : GuestWorker() +class GuestWorker123 : GuestWorker() +class GuestWorker124 : GuestWorker() +class GuestWorker125 : GuestWorker() +class GuestWorker126 : GuestWorker() +class GuestWorker127 : GuestWorker() /** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */ object GuestWorkers { @@ -250,7 +314,28 @@ object GuestWorkers { GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java, GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java, GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java, - GuestWorker63::class.java, + GuestWorker63::class.java, GuestWorker64::class.java, GuestWorker65::class.java, + GuestWorker66::class.java, GuestWorker67::class.java, GuestWorker68::class.java, + GuestWorker69::class.java, GuestWorker70::class.java, GuestWorker71::class.java, + GuestWorker72::class.java, GuestWorker73::class.java, GuestWorker74::class.java, + GuestWorker75::class.java, GuestWorker76::class.java, GuestWorker77::class.java, + GuestWorker78::class.java, GuestWorker79::class.java, GuestWorker80::class.java, + GuestWorker81::class.java, GuestWorker82::class.java, GuestWorker83::class.java, + GuestWorker84::class.java, GuestWorker85::class.java, GuestWorker86::class.java, + GuestWorker87::class.java, GuestWorker88::class.java, GuestWorker89::class.java, + GuestWorker90::class.java, GuestWorker91::class.java, GuestWorker92::class.java, + GuestWorker93::class.java, GuestWorker94::class.java, GuestWorker95::class.java, + GuestWorker96::class.java, GuestWorker97::class.java, GuestWorker98::class.java, + GuestWorker99::class.java, GuestWorker100::class.java, GuestWorker101::class.java, + GuestWorker102::class.java, GuestWorker103::class.java, GuestWorker104::class.java, + GuestWorker105::class.java, GuestWorker106::class.java, GuestWorker107::class.java, + GuestWorker108::class.java, GuestWorker109::class.java, GuestWorker110::class.java, + GuestWorker111::class.java, GuestWorker112::class.java, GuestWorker113::class.java, + GuestWorker114::class.java, GuestWorker115::class.java, GuestWorker116::class.java, + GuestWorker117::class.java, GuestWorker118::class.java, GuestWorker119::class.java, + GuestWorker120::class.java, GuestWorker121::class.java, GuestWorker122::class.java, + GuestWorker123::class.java, GuestWorker124::class.java, GuestWorker125::class.java, + GuestWorker126::class.java, GuestWorker127::class.java, ) private class Slot(val index: Int) { diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md index 54355c931f..e4dd4ff9ac 100644 --- a/docs/phantom-processes.md +++ b/docs/phantom-processes.md @@ -172,7 +172,7 @@ there. ### B. Exec-in-place workers for long-lived processes -Declare a pool of `android:process` services (`:g0`…`:g95`). Each long-lived program runs as the +Declare a pool of `android:process` services (`:g0`…`:g127`). Each long-lived program runs as the main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc` (same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits: @@ -262,8 +262,29 @@ vfork-safe (Python's subprocess execs under `vfork`). Details that mattered: session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at 61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a - `make -j` and its compilers), the D-Bus daemon's activation helpers (forks that never exec) and - the desktop's own programs started by KDE's launchers. + `make -j` and its compilers) and the D-Bus daemon's activation helpers (forks that never exec). +- **The desktop.** Plasma's own programs are listed (`startplasma-wayland`, `plasma_session`, + KWin, `kded6`, `ksmserver`, `plasmashell`, PowerDevil, KDE Connect, the KIO workers, the D-Bus + activated portal, dconf and activity manager) along with DroidDeck's desktop helpers. Discover's + update notifier, GeoClue's demo agent and the global-menu proxy are off in the user's Autostart. + A program a desktop launcher starts (`DD_HANDOFF_LAUNCHERS`: Plasma's shell, KRunner, Dolphin) + goes to a worker when it is a plain fork and exec: in the launcher's process group and session, + with no controlling terminal. Those launchers are Qt programs, which wait with `waitpid()` once + the hook has taken their pidfds away. A terminal's shell (its own session and terminal) stays. + Firefox runs with fission off, at most two web content processes and no crash helper. The + desktop and its apps use about 80 workers with Steam and a game running, hence 128. + + Counted children on the Thor (main: the session as #3338 and #3594 left it): + + | | main | this | + |---|---|---| + | desktop at rest | 30 | 0 | + | Dolphin, Konsole, Firefox, Kate and System Settings open | not measured (49 on a Pocket FIT without Firefox, the terminal running 40 jobs) | 7 | + | those, the desktop's Steam client and Bully running | not measured | 20 (30 with 64 workers: Wine's services were refused one) | + + With Bully running, six scans forced with the stock limit of 32 killed nothing. What stays + counted then: Steam's client and launch chain (10), Firefox's helpers (6), Konsole's shell, + Proton's script and `wineserver`. Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's `gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`. diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index 132bc8523a..d2463c5128 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -9,7 +9,7 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1 export SHELL=/bin/bash export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1 export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1 -export MOZ_SHM_NO_SEALS=1 +export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1 export QTWEBENGINE_DISABLE_SANDBOX=1 export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe export KWIN_USE_OVERLAYS=0 @@ -142,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64 Icon=steam Categories=System; ENTRY -python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /' -( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) & +python3 /usr/local/bin/droiddeck-pad-defaults --every 30 & python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /' /usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /' -( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) & +python3 /usr/local/bin/droiddeck-library-perms 2>&1 & mkdir -p /usr/local/share/applications cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY' [Desktop Entry] @@ -175,6 +174,15 @@ fi if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 & fi +# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them +# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it +# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the +# global-menu proxy (the panel has no global menu). +mkdir -p "$HOME/.config/autostart" +for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do + [ -e "$HOME/.config/autostart/$entry.desktop" ] || + printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop" +done skel_done=$HOME/.local/share/droiddeck/skel-copied if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then cp -rn /etc/skel/. "$HOME/" 2>/dev/null diff --git a/tools/linuxfs/desktop/firefox-droiddeck.js b/tools/linuxfs/desktop/firefox-droiddeck.js index 053d7d03a3..f729aba2e0 100644 --- a/tools/linuxfs/desktop/firefox-droiddeck.js +++ b/tools/linuxfs/desktop/firefox-droiddeck.js @@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false); pref("browser.aboutwelcome.enabled", false); pref("browser.startup.homepage", "about:blank"); pref("layout.css.devPixelsPerPx", "1.25"); +// Android counts each of Firefox's processes against the app's limit of 32: one web content process +// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and +// about: pages in the processes that already exist. +pref("fission.autostart", false); +pref("dom.ipc.processCount", 2); +pref("dom.ipc.processPrelaunch.enabled", false); +pref("browser.tabs.remote.separatePrivilegedContentProcess", false); +pref("extensions.webextensions.remote", false); diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults b/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults index 5ecdc61a36..ceec469d71 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-pad-defaults @@ -1,6 +1,8 @@ #!/usr/bin/python3 import glob import os +import sys +import time HOME = os.environ.get("HOME", "/root") CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config")) @@ -1048,8 +1050,19 @@ def switch_emulators(): print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})") -for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators): - try: - step() - except Exception as e: - print(f"droiddeck-pad-defaults: {step.__name__}: {e}") +def run_all(): + for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators): + try: + step() + except Exception as e: + print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True) + + +# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process +# for the whole desktop session rather than a shell loop starting a new one each time. +sys.stdout.reconfigure(line_buffering=True) +run_all() +if len(sys.argv) == 3 and sys.argv[1] == "--every": + while True: + time.sleep(float(sys.argv[2])) + run_all() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 9f8776b07d..2210ef98d6 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -63,9 +63,11 @@ dd_job() { # window's app by walking its process's parents) or its utility processes (the client only accepts # its transport from its own children). if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then - export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver} + export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker} + # The programs these start for the user (an app from the panel, a file opened in Dolphin) + export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin} else - unset DD_HANDOFF + unset DD_HANDOFF DD_HANDOFF_LAUNCHERS fi steam_setup_failed() { echo "== steam: the Steam client could not be set up (status $1)" diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 2d61fb8add..966cf67c84 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -1274,6 +1274,30 @@ static int ddh_job_control_job(void) { return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent); } +// Whether this is a program a desktop launcher starts for the user (DD_HANDOFF_LAUNCHERS names the +// launchers: Plasma's shell, KRunner, Dolphin): a plain fork and exec, still in the launcher's process +// group and session, with no controlling terminal. Those launchers are Qt programs, which wait with +// waitpid() once they have no pidfds (privileged.c), so the program's exit reaches them. A child the +// launcher set up as a terminal's (a session and a terminal of its own) stays its own child. +static int ddh_launched(const char *filename, char *const argv[], char *const envp[]) { + const char *list = ddh_env(envp, "DD_HANDOFF_LAUNCHERS"); + if (!list || !*list || ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv)) return 0; + pid_t parent = (pid_t)syscall(SYS_getppid); + char path[48], name[32]; + snprintf(path, sizeof(path), "/proc/%d/comm", (int)parent); + if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0; + name[strcspn(name, "\n")] = 0; + if (!ddh_listed(list, name, NULL)) return 0; + if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent) || + (pid_t)syscall(SYS_getsid, 0) != (pid_t)syscall(SYS_getsid, parent)) + return 0; + // /dev/tty opens only for a process with a controlling terminal + int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty", + O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0); + if (tty >= 0) syscall(SYS_close, tty); + return tty < 0; +} + static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) { if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0; // Not a job in the foreground of its controlling terminal: a handed-off program has none (the @@ -1364,7 +1388,8 @@ static void ddh_try_as(const char *filename, char *const argv[], char *const env ddh_debug(envp, "a job-control job:", filename); return; } - if (!ddh_program_listed(list, match_file, match_argv) && !ddh_pressed(match_file, match_argv, envp)) { + if (!ddh_program_listed(list, match_file, match_argv) && !ddh_launched(match_file, match_argv, envp) && + !ddh_pressed(match_file, match_argv, envp)) { ddh_debug(envp, "not listed:", filename); return; } diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index 3e9f5bec74..f0e8752f01 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -1480,7 +1480,7 @@ class NativeHookHandoffTest(unittest.TestCase): raise RuntimeError("workers that may still run: %s" % failed) def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False, - delay=0, extra_env=None): + delay=0, extra_env=None, parent_name=None): name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook) spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay) spawner.start() @@ -1496,9 +1496,9 @@ class NativeHookHandoffTest(unittest.TestCase): hook_env["QEMU_LD_PREFIX"] = self.prefix[self.prefix.index("-L") + 1] env = {k: v for k, v in os.environ.items() if k not in hook_env} prefix, parent = list(self.prefix or []), str(self.parent) - if as_shell: - # the hook tells a shell's child by its parent's name (qemu-user takes the program's) - shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / "bash" + if as_shell or parent_name: + # the hook tells a shell's or a launcher's child by its parent's name (qemu-user takes the program's) + shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / (parent_name or "bash") shell.parent.mkdir(exist_ok=True) shutil.copy(parent, shell) parent = str(shell) @@ -1707,6 +1707,41 @@ class NativeHookHandoffTest(unittest.TestCase): self.assertEqual([], requests) self.assertEqual(self.child_status, result.get("exit"), out.stdout) + def run_launcher(self, *argv, parent_name="plasmashell", **kwargs): + return self.run_parent(*argv, handoff="other", pressure=1000, parent_name=parent_name, + extra_env={"DD_HANDOFF_LAUNCHERS": "plasmashell:krunner"}, **kwargs) + + def test_a_program_a_desktop_launcher_starts_is_handed_off(self): + # an app from Plasma's panel: unlisted, far from the limit, still its own app process + result, requests, out = self.run_launcher("wait", "7") + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual(["target", "7"], requests[0]["argv"]) + self.assertEqual("7", result.get("exit"), out.stdout) + + def test_a_child_of_a_program_not_named_a_launcher_is_not(self): + result, requests, out = self.run_launcher("wait", "3", parent_name="konsole") + self.assertEqual([], requests, out.stderr) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_a_launchers_child_in_a_process_group_of_its_own_is_not(self): + result, requests, out = self.run_launcher("group", "4") + self.assertEqual([], requests, out.stderr) + self.assertEqual("4" if self.child_status == "3" else "127", result.get("exit"), out.stdout) + + def test_a_launchers_child_on_a_terminal_is_not(self): + # a terminal's shell, set up by its launcher (Konsole's part in Dolphin): the terminal is its own + result, requests, out = self.run_launcher("wait", "3", terminal=True) + self.assertEqual([], requests, out.stderr) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + + def test_the_steam_client_a_launcher_starts_is_not(self): + steam = self.root / "bin/steam" + if not steam.exists(): + shutil.copy(self.root / "bin/target", steam) + result, requests, out = self.run_launcher("wait", "3", "/bin/steam") + self.assertEqual([], requests, out.stderr) + self.assertEqual(self.child_status, result.get("exit"), out.stdout) + def test_near_the_limit_a_child_of_another_program_is_not(self): result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0) self.assertEqual([], requests) From 20df8b18586f1e47ebe5692140b95e1d91b1a63a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:31:58 -0500 Subject: [PATCH 10/80] fix(nativeguest): reap the zombies session processes adopt as subreapers and never wait for (#3610) --- docs/phantom-processes.md | 29 +++ tools/bionic-runtime/handoff.c | 7 + .../overlay/usr/local/bin/droiddeck-session | 7 +- tools/nativeguest/hook/exec.c | 2 + tools/nativeguest/hook/handoff.c | 164 ++++++++++++++++- tools/nativeguest/hook/signals.c | 84 +++++++++ tools/tests/test_native_hook_handoff.py | 173 ++++++++++++++++++ 7 files changed, 464 insertions(+), 2 deletions(-) diff --git a/docs/phantom-processes.md b/docs/phantom-processes.md index e4dd4ff9ac..b3bee82824 100644 --- a/docs/phantom-processes.md +++ b/docs/phantom-processes.md @@ -531,6 +531,35 @@ the old behavior and the old requirement. 7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket broker and keeps the GPU outside. +## Zombies + +Every session process is a child subreaper (`tools/linuxfs/preload/subreaper.c`, so that a +double-forked Xwayland is not left to init, which some vendor kernels kill), and most programs +never wait for a child they did not fork. What they adopted stayed a zombie: the grandchildren of +Qt's `startDetached()` under Plasma's shell, KWin and kaccess, Wine's double-forked processes, +wlroots' Xwayland under gamescope. A parent that never waits at all (Plasma's shell, for what it +launches) also kept the forked child of each program it handed off. On the Thor, main had 4 +zombies in Steam mode at rest and 19 in Bully, and the desktop gained one per app closed. + +The hook now reaps them from SIGCHLD (`ddh_reap_unclaimed()`): + +- **Adopted:** each process records, at its pid, the parent that started it and its own start + time, in one file for the session (`DD_PARENTS`). A fork's child does it at the fork, any other + program at its start. A zombie child whose record names another parent was adopted. An own child + (recorded with this parent, or with no record, such as a static program a `vfork()` started) is + left for its program's wait. +- **A handed-off program's forked child,** as a wait's look reaps it: the program's exit stays in + the table for the parent's wait. + +The program's SIGCHLD action runs first, and `sigaction()` shows it as the program set it. +`SIG_IGN` and `SA_NOCLDWAIT` stay the kernel's. A program that leaves SIGCHLD alone gets the +handler only when `DD_REAP_ADOPTED` names it (Plasma's programs, D-Bus, gamescope, Wine's +launchers, Decky's loader): with a handler, `poll()`, `sleep()` and the like return `EINTR` when a +child exits. With these changes there are no zombies left in either mode, Bully included. + +qemu-user has no `PR_SET_CHILD_SUBREAPER`, so the adoption tests skip under it (CI) and were run on +the Thor's kernel. + ## Robustness - Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app diff --git a/tools/bionic-runtime/handoff.c b/tools/bionic-runtime/handoff.c index 406b19e7fe..a20f16fa42 100644 --- a/tools/bionic-runtime/handoff.c +++ b/tools/bionic-runtime/handoff.c @@ -87,6 +87,11 @@ static const char *rewrite_path(const char *path, char *out, size_t size) { return path; } +// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their +// first parent for the session's subreapers, and reap nothing themselves. +static void ddnatv_manage_sigchld(void) {} +static void ddh_reap_unclaimed(void) __attribute__((unused)); + #include "../nativeguest/hook/kept.c" #include "../nativeguest/hook/handoff.c" @@ -315,12 +320,14 @@ pid_t fork(void) { } ddh_prepare(); pid_t forker = (pid_t)syscall(SYS_gettid); + pid_t forking = (pid_t)syscall(SYS_getpid); pid_t pid = orig_fork(); if (pid == 0) { kept_forked(); kept_close_forked(); ddh_drop_worker_binder(); ddh_forked(forker); + ddh_record_parent((pid_t)syscall(SYS_getpid), forking); } else if (pid > 0) { ddh_child_created(pid, 1); } diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 2210ef98d6..e8a0f83db4 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -66,8 +66,13 @@ if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker} # The programs these start for the user (an app from the panel, a file opened in Dolphin) export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin} + # Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and + # the programs that reap them even while they leave SIGCHLD alone (hook/signals.c) + rm -f /run/droiddeck-parents.* 2>/dev/null + export DD_PARENTS=/run/droiddeck-parents.$$ + export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real} else - unset DD_HANDOFF DD_HANDOFF_LAUNCHERS + unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED fi steam_setup_failed() { echo "== steam: the Steam client could not be set up (status $1)" diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 2f92fe9a0d..db55262540 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -661,12 +661,14 @@ pid_t fork(void) { } ddh_prepare(); pid_t forker = (pid_t)syscall(SYS_gettid); + pid_t forking = (pid_t)syscall(SYS_getpid); pid_t pid = orig_fork(); if (pid == 0) { kept_forked(); kept_close_forked(); ddh_drop_worker_binder(); ddh_forked(forker); + ddh_record_parent((pid_t)syscall(SYS_getpid), forking); } else if (pid > 0) { ddh_child_created(pid, 1); } diff --git a/tools/nativeguest/hook/handoff.c b/tools/nativeguest/hook/handoff.c index 966cf67c84..0827c29823 100644 --- a/tools/nativeguest/hook/handoff.c +++ b/tools/nativeguest/hook/handoff.c @@ -878,6 +878,9 @@ static void ddh_apply_inherited(void) { } } +static void ddh_open_parents(void); +static void ddh_record_own_parent(void); + __attribute__((constructor)) static void ddh_init(void) { ddh_apply_inherited(); ddh_find_worker_binder(); @@ -885,6 +888,9 @@ __attribute__((constructor)) static void ddh_init(void) { ddh_find_parent_table(); // tests only: as when the table could not be made here, and the first fork makes it if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare(); + ddh_open_parents(); + ddh_record_own_parent(); + ddnatv_manage_sigchld(); } static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) { @@ -1326,7 +1332,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename struct ddh_buf b = {line, 0, sizeof(line) - 1}; ddh_puts(&b, "ddnatv handoff: "); ddh_putint(&b, getpid()); - ddh_puts(&b, " "); + ddh_puts(&b, " (parent "); + ddh_putint(&b, (long)syscall(SYS_getppid)); + ddh_puts(&b, ", session "); + ddh_putint(&b, (long)syscall(SYS_getsid, 0)); + ddh_puts(&b, ") "); ddh_puts(&b, what); ddh_puts(&b, " "); ddh_puts(&b, filename ? filename : "?"); @@ -1669,6 +1679,158 @@ static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) { return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0; } +// ---- children no wait will come for ------------------------------------------------------------ +// +// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose +// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels +// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the +// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records +// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the +// session): a zombie whose record names another parent was adopted. +static uint64_t *g_ddh_parents; + +static void ddh_open_parents(void) { + const char *name = getenv("DD_PARENTS"); + if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return; + char path[PATH_MAX]; + const char *real = rewrite_path(name, path, sizeof(path)); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real, + O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0); + if (fd < 0) return; + size_t size = (size_t)DDH_FORKS * sizeof(uint64_t); + struct stat st; + if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size) + call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0); + // past the file's end a page would fault (SIGBUS): mapped only once the file has its size + void *map = MAP_FAILED; + if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size) + map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + syscall(SYS_close, fd); + if (map == MAP_FAILED) return; + uint64_t *none = NULL; + if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) + munmap(map, size); +} + +static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; } + +static void ddh_record_parent(pid_t me, pid_t parent) { + uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE); + if (!map || me <= 0) return; + int saved = errno; + long start = ddh_start_time(me); + errno = saved; + if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE); +} + +// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own +// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is +// still the one that started it (a vfork()'s waits for the exec). +static void ddh_record_own_parent(void) { + uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE); + if (!map) return; + pid_t me = (pid_t)syscall(SYS_getpid); + int saved = errno; + long start = ddh_start_time(me); + errno = saved; + if (start <= 0) return; + uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE); + if ((uint32_t)r == (uint32_t)start && r >> 32) return; + __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE); +} + +// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read. +static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) { + char path[48] = "/proc/", digits[16], stat[512]; + int n = 0, len = 6; + for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10); + while (n) path[len++] = digits[--n]; + memcpy(path + len, "/stat", 6); + int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0); + if (fd < 0) return 0; + long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0); + call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0); + if (got <= 0) return 0; + stat[got] = 0; + char *p = strrchr(stat, ')'); + if (!p || p[1] != ' ' || !p[2]) return 0; + *state = p[2]; + // ") S PPID": field 4; starttime is field 22 + long parent = 0; + for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0'); + *ppid = (pid_t)parent; + for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' '); + long t = 0; + for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0'); + *start = t; + return 1; +} + +// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's +// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this +// process adopted. 1 when it did. +static int ddh_reap_unwaited(pid_t me, pid_t child) { + char state = 0; + long start = 0; + pid_t ppid = 0; + if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0; + struct ddh_entry *e = ddh_find(child); + int32_t gen = e ? ddh_gen_of(e, child) : 0; + if (gen) { + if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0; + ddh_mark_reaped(e, gen); + return 1; + } + uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE); + uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0; + if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0; + return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child; +} + +// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will +// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc. +static void ddh_reap_unclaimed(void) { + if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return; + int saved = errno; + pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0); + // past 64 reaped this way, the rest from /proc too + int scan = 1; + for (int i = 0; i < 64; i++) { + siginfo_t si; + memset(&si, 0, sizeof(si)); + if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) { + scan = 0; + break; + } + if (!ddh_reap_unwaited(me, si.si_pid)) { + break; + } + } + int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc", + O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1; + char buf[2048]; + while (dir >= 0) { + long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0); + if (n <= 0) break; + for (long off = 0; off < n;) { + struct ddh_reap_dirent { + uint64_t ino; + int64_t off; + unsigned short reclen; + unsigned char type; + char name[]; + } *d = (struct ddh_reap_dirent *)(buf + off); + off += d->reclen; + long pid = 0; + const char *c = d->name; + for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0'); + if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid); + } + } + if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0); + errno = saved; +} + // Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it. static int ddh_take(struct ddh_entry *e) { int expected = DDH_EXITED; diff --git a/tools/nativeguest/hook/signals.c b/tools/nativeguest/hook/signals.c index c2999885d4..4ed9522da4 100644 --- a/tools/nativeguest/hook/signals.c +++ b/tools/nativeguest/hook/signals.c @@ -174,10 +174,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) { real_sig(SIGSYS, &sa, NULL); } +// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it +// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for +// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD +// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the +// like return EINTR when a child exits, which a program that never had one may not expect. +static struct sigaction g_app_sigchld; +static int g_sigchld_managed; +static int g_sigchld_on_default; + +static void ddh_reap_unclaimed(void); +static int ddh_listed(const char *list, const char *name, char *const argv[]); +static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)); + +static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) { + struct sigaction app = g_app_sigchld; + if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) { + if (app.sa_flags & SA_RESETHAND) { + // as the kernel would: the default from now on, with the handler only for a named program + g_app_sigchld.sa_handler = SIG_DFL; + g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND); + int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); + int saved = errno; + if (real_sig) ddnatv_apply_sigchld(real_sig); + errno = saved; + } + if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx); + else app.sa_handler(sig); + } + ddh_reap_unclaimed(); +} + +// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN, +// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above. +static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) { + const struct sigaction *app = &g_app_sigchld; + int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN; + if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default)) + return real_sig(SIGCHLD, app, NULL); + struct sigaction k; + memset(&k, 0, sizeof(k)); + k.sa_sigaction = ddnatv_sigchld_handler; + k.sa_mask = app->sa_mask; + k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP)); + return real_sig(SIGCHLD, &k, NULL); +} + +static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *), + const struct sigaction *act, struct sigaction *oldact) { + struct sigaction prev = g_app_sigchld; + if (act) { + g_app_sigchld = *act; + if (ddnatv_apply_sigchld(real_sig) != 0) { + int err = errno; + g_app_sigchld = prev; + errno = err; + return -1; + } + } + if (oldact) *oldact = prev; + return 0; +} + +// From the hook's start (handoff.c), once the parents file is open +static void ddnatv_manage_sigchld(void) { + if (!getenv("DD_PARENTS")) return; + int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); + if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return; + const char *named = getenv("DD_REAP_ADOPTED"); + g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL); + if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1; +} + int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); if (!real_sig) return -1; + if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact); if (signum == SIGSYS) { if (act && act->sa_sigaction == ddnatv_sigsys_handler) { return real_sig(signum, act, oldact); @@ -192,6 +265,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL; if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction"); + if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact); if (signum == SIGSYS) { if (act && act->sa_sigaction == ddnatv_sigsys_handler) { return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0; @@ -210,6 +284,16 @@ typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler) { static sighandler_t (*orig_signal)(int, sighandler_t) = NULL; if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal"); + if (signum == SIGCHLD && g_sigchld_managed) { + // glibc's signal(): BSD semantics + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + act.sa_handler = handler; + act.sa_flags = SA_RESTART; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGCHLD); + return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR; + } if (signum == SIGSYS) { struct sigaction act, old; memset(&act, 0, sizeof(act)); diff --git a/tools/tests/test_native_hook_handoff.py b/tools/tests/test_native_hook_handoff.py index f0e8752f01..6862da426f 100644 --- a/tools/tests/test_native_hook_handoff.py +++ b/tools/tests/test_native_hook_handoff.py @@ -1025,6 +1025,19 @@ int main(int argc, char **argv) { errno = 0; printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH); } + if (strcmp(argv[1], "nowait") == 0) { + // no wait until the program has long exited, as Plasma's shell never waits for what it launches + usleep(2000000); + char path[64], line[256] = ""; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + FILE *f = fopen(path, "r"); + if (f) { + if (!fgets(line, sizeof(line), f)) line[0] = 0; + fclose(f); + } + char *s = strrchr(line, ')'); + printf("zombie\t%d\n", s && s[1] == ' ' && s[2] == 'Z'); + } int group = strcmp(argv[1], "group") == 0; if (group) { setpgid(pid, pid); @@ -1139,6 +1152,93 @@ int main(void) { } """ +# A child subreaper, as every session process is (preload/subreaper.c), that never waits for a child +# it did not fork. adopt: a child that exits at once leaves a grandchild, which exits once the child is +# gone; own: its own child, which it waits for only later; vfork: one vfork() made, its program static +# (no hook, so no record of it); handler: as adopt, with a SIGCHLD handler of its own; ignore: SIGCHLD +# ignored, so the kernel reaps. +ORPHANS = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t calls; +static void counted(int sig) { (void)sig; calls++; } + +static void nap(long ms) { + struct timespec t = {ms / 1000, (ms % 1000) * 1000000L}; + while (nanosleep(&t, &t) != 0 && errno == EINTR) {} +} + +static int zombie(pid_t pid) { + char path[64], line[256] = ""; + snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + FILE *f = fopen(path, "r"); + if (!f) return 0; + if (!fgets(line, sizeof(line), f)) line[0] = 0; + fclose(f); + char *s = strrchr(line, ')'); + return s && s[1] == ' ' && s[2] == 'Z'; +} + +int main(int argc, char **argv) { + const char *mode = argv[1]; + int subreaper = 0; + printf("subreaper\t%d\n", prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 && prctl(PR_GET_CHILD_SUBREAPER, &subreaper) == 0 && subreaper); + fflush(stdout); + if (strcmp(mode, "handler") == 0) { + struct sigaction sa, seen; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = counted; + sa.sa_flags = SA_RESTART; + sigaction(SIGCHLD, &sa, NULL); + sigaction(SIGCHLD, NULL, &seen); + printf("view\t%d\n", seen.sa_handler == counted); + } + if (strcmp(mode, "ignore") == 0) signal(SIGCHLD, SIG_IGN); + if (strcmp(mode, "own") == 0 || strcmp(mode, "vfork") == 0) { + pid_t child = strcmp(mode, "vfork") == 0 ? vfork() : fork(); + if (child == 0) { + if (argc > 2) execl(argv[2], "target", "7", (char *)NULL); + _exit(7); + } + nap(1500); + int status = 0; + pid_t r = waitpid(child, &status, 0); + printf("own\t%d\n", r == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1); + return 0; + } + int pipefd[2]; + if (pipe(pipefd) != 0) return 1; + pid_t middle = fork(); + if (middle == 0) { + pid_t grandchild = fork(); + if (grandchild == 0) { + nap(300); // its parent is gone by then + _exit(5); + } + if (write(pipefd[1], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) _exit(1); + _exit(0); + } + pid_t grandchild = 0; + if (read(pipefd[0], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) return 1; + int status = 0; + printf("middle\t%d\n", waitpid(middle, &status, 0) == middle); + nap(1500); + printf("orphan\t%d\n", zombie(grandchild)); + printf("adopted\t%d\n", waitpid(grandchild, &status, WNOHANG) == grandchild); + if (strcmp(mode, "handler") == 0) printf("calls\t%d\n", calls > 0); + return 0; +} +""" + DUPRACE = r""" #define _GNU_SOURCE #include @@ -2280,6 +2380,79 @@ class NativeHookHandoffTest(unittest.TestCase): pass_fds=(table,)) return parent, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out + def run_orphans(self, mode, named=True, parents=True, *args): + tmp = Path(self.tmp.name) + probe = tmp / "orphans" + if not probe.exists(): + (tmp / "orphans.c").write_text(ORPHANS) + subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "orphans.c")], check=True) + (self.root / "run").mkdir(exist_ok=True) + env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)} + if parents: + env["DD_PARENTS"] = "/run/parents-%s" % self.id().rsplit(".", 1)[-1] + if named: + env["DD_REAP_ADOPTED"] = "other:orphans" + # not a session's own settings, when run inside one + inherited = {k: v for k, v in os.environ.items() if k not in ("DD_PARENTS", "DD_REAP_ADOPTED")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in env.items() for arg in ("-E", f"{key}={value}")] + run_env = inherited + else: + cmd = [] + run_env = dict(inherited, **env) + out = subprocess.run(cmd + [str(probe), mode, *args], env=run_env, capture_output=True, text=True, timeout=60) + result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line) + if mode == "adopt" and result.get("subreaper") != "1": + self.skipTest("no child subreaper here (qemu-user has no PR_SET_CHILD_SUBREAPER)") + return result, out + + def test_a_subreaper_reaps_the_zombie_it_adopted(self): + result, out = self.run_orphans("adopt") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual("1", result.get("middle"), out.stdout) + self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr) + self.assertEqual("0", result.get("adopted"), out.stdout) + + def test_a_program_not_named_keeps_its_default_sigchld_and_its_adopted_zombie(self): + result, out = self.run_orphans("adopt", False) + self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr) + self.assertEqual("1", result.get("adopted"), out.stdout) + + def test_without_a_parents_file_nothing_is_reaped(self): + result, out = self.run_orphans("adopt", True, False) + self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr) + + def test_a_subreapers_own_child_waits_for_its_wait(self): + result, out = self.run_orphans("own") + self.assertEqual("7", result.get("own"), out.stdout + out.stderr) + + def test_a_vfork_child_with_no_record_waits_for_its_parents_wait(self): + result, out = self.run_orphans("vfork", True, True, "/bin/target") + self.assertEqual("7", result.get("own"), out.stdout + out.stderr) + + def test_a_programs_own_sigchld_handler_runs_and_shows_as_its_own(self): + result, out = self.run_orphans("handler", False) + self.assertEqual("1", result.get("view"), out.stdout + out.stderr) + self.assertEqual("1", result.get("calls"), out.stdout) + if result.get("subreaper") == "1": + self.assertEqual("0", result.get("orphan"), out.stdout) + + def test_an_ignored_sigchld_stays_the_kernels(self): + result, out = self.run_orphans("ignore") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr) + + def test_an_unwaited_handoffs_child_is_reaped(self): + # a parent that never waits until its program has long exited, as Plasma's shell + (self.root / "run").mkdir(exist_ok=True) + env = {"DD_PARENTS": "/run/parents-nowait", "DD_REAP_ADOPTED": "parent"} + result, requests, out = self.run_parent("nowait", "6", extra_env=env) + self.assertEqual(1, len(requests), out.stderr) + self.assertEqual("0", result.get("zombie"), out.stdout + out.stderr) + # its program's exit, still there for the wait that comes at last + self.assertEqual("1", result.get("same"), out.stdout) + self.assertEqual("6", result.get("exit"), out.stdout) + def test_a_guest_sees_no_pidfd_support_so_its_waits_go_through_the_handoff(self): parent, result, out = self.run_worker_program("pidfd", PIDFD_PROBE) self.assertEqual(0, out.returncode, out.stderr) From e3faee459fc3a552cf612bb53bc8e407205c7456 Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:54:39 -0400 Subject: [PATCH 11/80] Fix frame generation controls in Library and Steam settings (#3597) Restore the frame generation controls and make the Steam menu focus its first enabled option for controller and keyboard navigation. --- .../com/droiddeck/launcher/ui/FrameGenMenu.kt | 69 ++++++++++++++++++- .../droiddeck/launcher/ui/FrontEndSetup.kt | 61 ++++++++-------- .../com/droiddeck/launcher/ui/SheetRows.kt | 29 +++++++- 3 files changed, 128 insertions(+), 31 deletions(-) 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 c978f14161..2ebf1d07b8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -41,8 +41,73 @@ internal fun FrameGenMenu( val colors = MaterialTheme.colorScheme val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG") + if (legacyButtons) { + val context = LocalContext.current + val options = buildList { + add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) } + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) } + FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) } + } + Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) { + options.forEachIndexed { index, option -> + val selected = mode == option || + (option.engine == FrameGen.ENGINE_OFF && selectedEngine == null) + val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected + val pick = { onPick(option) } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth() + .padding(top = if (index == 0) 0.dp else 6.dp) + .controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(FrameGen.label(context, option)) } + } + if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { + Text( + need.orEmpty(), + color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 6.dp), + ) + } + if (gameProfileId != null) { + val resetGame = onResetGame + OutlinedButton( + onClick = resetGame, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp) + .controllerConfirm(onClick = resetGame), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + 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 + } + Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) { - if (!legacyButtons) OutlinedButton( + OutlinedButton( onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, modifier = Modifier.fillMaxWidth().controllerConfirm( onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, @@ -54,7 +119,7 @@ internal fun FrameGenMenu( ), ) { Text(offLabel) } - Row(Modifier.fillMaxWidth().then(if (legacyButtons) Modifier else Modifier.padding(top = 8.dp)), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { val focusIndex = engines.indexOfFirst { (engine, _) -> selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready } 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 c2058c277e..834de6f4d1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -887,6 +887,34 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m -> Box(m) { GameSettingsCard(host, game, steamScope) } } else null + val frameGenMenuContent: @Composable () -> Unit = { + FrameGenMenu( + mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen, + lossless = s.lossless, + onPick = { mode -> + val key = frameGenProfileKey + if (key == null) { + a.onFrameGenPick(mode) + } else { + com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode) + gameFrameGenMode = mode + gameFrameGenOverride = true + } + }, + onImportLossless = a.onImportLossless, + legacyButtons = true, + gameProfileId = frameGenProfileKey, + hasGameOverride = gameFrameGenOverride, + onResetGame = { + val key = frameGenProfileKey + if (key != null) { + com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key) + gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context) + gameFrameGenOverride = false + } + }, + ) + } val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> { add { m -> val back = stringResource(R.string.hop_from_games) @@ -908,33 +936,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost ) { host.open = if (host.open == "fg") null else "fg" } - if (host.open == "fg") FrameGenMenu( - mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen, - lossless = s.lossless, - onPick = { mode -> - val key = frameGenProfileKey - if (key == null) { - a.onFrameGenPick(mode) - } else { - com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode) - gameFrameGenMode = mode - gameFrameGenOverride = true - } - }, - onImportLossless = a.onImportLossless, - legacyButtons = true, - gameProfileId = frameGenProfileKey, - hasGameOverride = gameFrameGenOverride, - onResetGame = { - val key = frameGenProfileKey - if (key != null) { - com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key) - gameFrameGenMode = - com.droiddeck.launcher.gpu.FrameGen.mode(context) - gameFrameGenOverride = false - } - } - ) + } } if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) } @@ -966,6 +968,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost repeat(columns - row.size) { Spacer(Modifier.weight(1f)) } } } + if (host.open == "fg") { + Box(Modifier.fillMaxWidth().padding(top = 4.dp)) { + frameGenMenuContent() + } + } } } 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 e715c0030d..0917f56d8a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt @@ -2,7 +2,10 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp import com.droiddeck.launcher.R @@ -12,8 +15,30 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) { SettingsGroup(stringResource(R.string.frame_gen_title)) { SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint), highlighted = host.open == "fg") { Box { - ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" } - if (host.open == "fg") FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless) + val open = host.open == "fg" + ValueChip(s.frameGenLabel, open) { host.open = if (open) null else "fg" } + AnchoredMenu( + open = open, + onDismiss = { if (host.open == "fg") host.open = null }, + title = stringResource(R.string.frame_gen_title), + compact = true, + minWidth = 220.dp, + ) { firstItemFocus -> + FrameGenMenu( + mode = s.frameGen, + lossless = s.lossless, + onPick = { mode -> + a.onFrameGenPick(mode) + host.open = null + }, + onImportLossless = { + a.onImportLossless() + host.open = null + }, + focusModifier = Modifier.focusRequester(firstItemFocus), + legacyButtons = true, + ) + } } } } From 8cf1e60cc2672782c2f85f9bc6bbf0e7d4d89946 Mon Sep 17 00:00:00 2001 From: FryMcNugget Date: Thu, 3 Dec 2026 03:22:52 +0000 Subject: [PATCH 12/80] fix(runtime): thermal zone binds no longer leak into the stand-in for PCI devices (#3595) --- .../droiddeck/launcher/runtime/LegacyNames.kt | 33 ++++++++++++++++++- .../launcher/runtime/LinuxRuntime.java | 2 +- .../launcher/runtime/LegacyNamesTest.kt | 31 +++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt index 3f4589ae13..8008cf82ed 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt @@ -35,9 +35,40 @@ object LegacyNames { @Synchronized fun migrateEtc(root: File) { for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new)) - File(root, "etc/droiddeck/empty").mkdirs() + clearEmptyStandIn(root) + File(root, NO_THERMAL).mkdirs() } + /** + * It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot + * parse; older builds let thermal bind mount points leak into it. The guest can write here, so a + * link is never followed: one in place of the folder is removed, and one above it stops the cleanup. + */ + private fun clearEmptyStandIn(root: File) { + val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) } + if (linkedAbove != null) { + Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link") + return + } + val empty = File(root, "etc/droiddeck/empty") + if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) } + .onFailure { Log.w(TAG, "could not remove the link at $empty", it); return } + empty.mkdirs() + empty.listFiles()?.forEach { entry -> + runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) } + } + } + + private fun deleteWithoutFollowing(path: java.nio.file.Path) { + if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) { + Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) } + } + Files.deleteIfExists(path) + } + + /** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */ + const val NO_THERMAL = "etc/droiddeck/no-thermal" + @Synchronized fun migrateRootfs(root: File) { migrateEtc(root) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 142d4e90bc..327e7fc1ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -248,7 +248,7 @@ public final class LinuxRuntime { // A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort // at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its // wrapper gave up: it lists the directory for CPU temperatures. Empty there instead. - if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal"); + if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal"); bind(cmd, context.getFilesDir().getPath()); bind(cmd, context.getCacheDir().getPath()); bind(cmd, liveDir(context).getPath()); diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt index 027ed9359b..bb9d5e4671 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt @@ -35,6 +35,37 @@ class LegacyNamesTest { assertEquals("droiddeck", link("etc/bannerlator")) } + @Test fun theEmptyStandInIsEmptiedAndThermalZonesGetTheirOwn() { + write("etc/droiddeck/empty/thermal_zone26/temp", "") + LegacyNames.migrateEtc(root) + assertEquals(emptyList(), File(root, "etc/droiddeck/empty").list()!!.toList()) + assertTrue(File(root, LegacyNames.NO_THERMAL).isDirectory) + } + + @Test fun clearingTheEmptyStandInRemovesLinksWithoutTouchingWhatTheyPointAt() { + write("home/keep/file", "kept") + val links = File(root, "etc/droiddeck/empty").apply { mkdirs() } + val made = runCatching { + Files.createSymbolicLink(File(links, "dir").toPath(), File(root, "home/keep").toPath()) + Files.createSymbolicLink(File(links, "dangling").toPath(), File(root, "missing").toPath()) + }.isSuccess + org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made) + LegacyNames.migrateEtc(root) + assertEquals(emptyList(), links.list()!!.toList()) + assertEquals("kept", File(root, "home/keep/file").readText()) + } + + @Test fun aLinkInPlaceOfTheEmptyStandInIsReplacedWithoutTouchingItsTarget() { + write("home/keep/file", "kept") + val empty = File(root, "etc/droiddeck/empty").also { it.parentFile!!.mkdirs() } + val made = runCatching { Files.createSymbolicLink(empty.toPath(), File(root, "home/keep").toPath()) }.isSuccess + org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made) + LegacyNames.migrateEtc(root) + assertFalse(Files.isSymbolicLink(empty.toPath())) + assertEquals(emptyList(), empty.list()!!.toList()) + assertEquals("kept", File(root, "home/keep/file").readText()) + } + @Test fun aFreshRuntimeGetsNoOldNames() { write("usr/local/bin/droiddeck-session", "new") LegacyNames.migrateRootfs(root) From affb0da37fa73bac99063e590d9eb630d6dc2d98 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Thu, 3 Dec 2026 07:13:39 -0500 Subject: [PATCH 13/80] fix(fex): keep the guest stack clear of the host stack's growth reserve (#3623) --- docs/development/x86-64-steam-client.md | 10 +++ ...st-stack-clear-of-host-stack-reserve.patch | 45 ++++++++++++ tools/tests/test_fex_guest_stack_reserve.py | 73 +++++++++++++++++++ 3 files changed, 128 insertions(+) create mode 100644 tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch create mode 100644 tools/tests/test_fex_guest_stack_reserve.py diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 1a02e3420f..ced25e4c70 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -303,6 +303,16 @@ alone would then read as an installed client. hook records the guest handler as it does for `sigaction()` and keeps its own installed, so a program that sets a crash handler is no longer killed by the next blocked system call (`tools/tests/test_native_hook_sigsys_mask.py`). + - `0020-guest-stack-clear-of-host-stack-reserve`: FEX places the guest's 128 MB stack range + with `MAP_FIXED_NOREPLACE`, scanning down from the top of the address space. With a 39-bit address + space the host stack sits in that top range in about one start in eight, and the guest stack then + landed directly below it, inside the space the kernel keeps free for the host stack to grow + (`RLIMIT_STACK`, at least 128 MB). A deep host call chain (the native userland's `execve` hook + and libc `syscall()` wrappers) then grew the host stack into the top of the guest stack, where + the guest's argument and environment strings live, and the next program started with a corrupted + environment (Proton failing with `KeyError: 'PWD'` or "No compat data path"). The guest stack is + now placed below that reserve. On a Retroid Pocket Duo, 100 nested Proton starts ran clean, 10 of + them with the host stack at the top; without the patch 3 of 25 were corrupted. - **Building and publishing.** Droid-Deck/DroidDeck-Components' `build-fex.yml` builds `tools/fex` from this repository at a chosen ref (default `main`) with host thunks, in the same Arch Linux ARM container with a read-only token, then a separate job replaces `fex.tzst` on Components' single `fex` release, diff --git a/tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch b/tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch new file mode 100644 index 0000000000..31b8f2a557 --- /dev/null +++ b/tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch @@ -0,0 +1,45 @@ +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index cebf1f5..b1a72d2 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -32,6 +32,7 @@ + #include + #include + #include ++#include + + #define PAGE_START(x) ((x) & ~(uintptr_t)(4095)) + #define PAGE_OFFSET(x) ((x) & 4095) +@@ -505,7 +506,12 @@ public: + auto PageSize = sysconf(_SC_PAGESIZE); + PageSize = PageSize > 0 ? PageSize : FEXCore::Utils::FEX_PAGE_SIZE; + ++ const auto [HostStackLow, HostStackHigh] = HostStackReservation(PageSize); ++ + do { ++ if (StackHint < HostStackHigh && StackHint + FULL_STACK_SIZE > HostStackLow && HostStackLow > FULL_STACK_SIZE) { ++ StackHint = (HostStackLow - FULL_STACK_SIZE) & ~static_cast(PageSize - 1); ++ } + // Allocate the base of the full 128MB stack range. + StackPointerBase = Handler->GuestMmap(Thread, reinterpret_cast(StackHint), FULL_STACK_SIZE, PROT_NONE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_GROWSDOWN | MAP_NORESERVE | MAP_FIXED_NOREPLACE, -1, 0); +@@ -793,6 +799,19 @@ public: + *AuxTabSize = sizeof(AuxType) * AuxVariables.size(); + } + ++ static std::pair HostStackReservation(uint64_t PageSize) { ++ struct prctl_mm_map map {}; ++ uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast(__builtin_frame_address(0)); ++ Top = (Top + PageSize - 1) & ~(PageSize - 1); ++ ++ constexpr uint64_t MinGap = 128ULL * 1024 * 1024; ++ const uint64_t MaxGap = std::max(Top / 6 * 5, MinGap); ++ struct rlimit Limit {}; ++ uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast(Limit.rlim_cur) : MinGap; ++ Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize; ++ return {Top > Gap ? Top - Gap : 0, Top}; ++ } ++ + // Get the current memory map from /proc/self/stat + static bool GetCurrentMap(struct prctl_mm_map& map) { + diff --git a/tools/tests/test_fex_guest_stack_reserve.py b/tools/tests/test_fex_guest_stack_reserve.py new file mode 100644 index 0000000000..d965aa6ba6 --- /dev/null +++ b/tools/tests/test_fex_guest_stack_reserve.py @@ -0,0 +1,73 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0020-guest-stack-clear-of-host-stack-reserve.patch" +LOADER = "Source/Tools/FEXInterpreter/ELFCodeLoader.h" +MIN_GAP = 128 * 1024 * 1024 +STACK = 128 * 1024 * 1024 +PAGE = 4096 + + +def lines(sign): + return [line[1:].strip() for line in PATCH.read_text().splitlines() if line.startswith(sign) and not line.startswith(sign * 3)] + + +def reservation(top, rlimit): + top = (top + PAGE - 1) & ~(PAGE - 1) + gap = min(max(rlimit, MIN_GAP), max(top // 6 * 5, MIN_GAP)) + 256 * PAGE + return (top - gap if top > gap else 0, top) + + +def place(hint, low, high): + if hint < high and hint + STACK > low and low > STACK: + hint = (low - STACK) & ~(PAGE - 1) + return hint + + +class FexGuestStackReserveTest(unittest.TestCase): + def test_only_the_elf_loader_changes(self): + self.assertEqual([LOADER], re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M)) + + def test_nothing_is_removed(self): + self.assertEqual([], lines("-")) + + def test_the_reserve_starts_at_the_end_of_the_host_environment(self): + added = lines("+") + self.assertIn("uint64_t Top = GetCurrentMap(map) && map.env_end ? map.env_end : reinterpret_cast(__builtin_frame_address(0));", added) + self.assertIn("uint64_t Gap = getrlimit(RLIMIT_STACK, &Limit) == 0 ? static_cast(Limit.rlim_cur) : MinGap;", added) + self.assertIn("Gap = std::clamp(Gap, MinGap, MaxGap) + 256 * PageSize;", added) + + def test_every_stack_hint_is_checked_against_the_reserve(self): + text = PATCH.read_text() + self.assertLess(text.index("HostStackReservation(PageSize);"), text.index("do {")) + self.assertLess(text.index("do {"), text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)")) + self.assertLess(text.index("StackHint = (HostStackLow - FULL_STACK_SIZE)"), text.index("// Allocate the base of the full 128MB stack range.")) + + def test_a_guest_stack_overlapping_the_reserve_moves_below_it(self): + host_env_end = 0x7FFC391000 + low, high = reservation(host_env_end, 8 * 1024 * 1024) + hint = place((1 << 39) - STACK, low, high) + self.assertLessEqual(hint + STACK, low) + self.assertGreaterEqual(host_env_end - (hint + STACK), MIN_GAP) + + def test_a_guest_stack_clear_of_the_reserve_stays_put(self): + low, high = reservation(0x7FC491C000, 8 * 1024 * 1024) + hint = (1 << 39) - STACK + self.assertEqual(hint, place(hint, low, high)) + + def test_a_larger_stack_limit_widens_the_reserve(self): + low, _ = reservation(0x7FFC391000, 512 * 1024 * 1024) + self.assertEqual(0x7FFC391000 - 512 * 1024 * 1024 - 256 * PAGE, low) + + def test_an_unlimited_stack_limit_keeps_room_for_the_guest(self): + low, _ = reservation(0x7FFC391000, (1 << 64) - 1) + self.assertGreater(low, STACK) + + def test_no_comments_are_added(self): + self.assertFalse([line for line in lines("+") if line.startswith(("//", "/*"))]) + + +if __name__ == "__main__": + unittest.main() From cec2e4ed70c8537a3b1f4335c92afe167762f045 Mon Sep 17 00:00:00 2001 From: MicroCool Date: Thu, 3 Dec 2026 21:26:11 +0900 Subject: [PATCH 14/80] Retry rate-limited Robolectric downloads with a Maven Central mirror (#3620) --- .github/workflows/unit-tests.yml | 24 ++++++++-- app/build.gradle | 3 ++ settings.gradle | 12 +++++ tools/tests/test_ci_checks.py | 79 ++++++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 3 deletions(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index a525311b34..a2ef6cfe8e 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -128,14 +128,32 @@ jobs: run: | set -o pipefail mkdir -p app/build + log=app/build/unit-tests.log + attempt_log=app/build/unit-tests-attempt.log + : > "$log" + mirror=() + central='https://(repo1\.maven\.org|repo\.maven\.apache\.org)/maven2/org/robolectric/' + gradle_error='((Caused by: )?org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: |>[[:space:]]+)?' + java_error='((Caused by: )?java\.io\.IOException: )?' # A Maven 429 fails every test class that needs the missing jar. The jars an attempt did get stay for the next. for wait in 60 180 0; do status=0 - ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log || status=$? - if [ "$status" = 0 ] || [ "$wait" = 0 ] || ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' app/build/unit-tests.log; then + ./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PskipRust=true -PunitTestsOnly=true -PndkVersion="$NDK_VERSION" "${mirror[@]}" 2>&1 | tee "$attempt_log" || status=$? + cat "$attempt_log" >> "$log" + if [ "$status" = 0 ] || [ "$wait" = 0 ]; then exit "$status" fi - echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" + if [ "${#mirror[@]}" = 0 ] && grep -qE \ + -e "^[[:space:]]*${gradle_error}Could not (GET|HEAD) '?${central}[^'[:space:]]+'?\. Received status code 429([[:space:]]|$)" \ + -e "^[[:space:]]*${java_error}Server returned HTTP response code: 429 for URL: ${central}[^[:space:]]+" "$attempt_log"; then + mirror=(-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2) + echo "::notice::Maven Central rate limited Robolectric. Retrying unit tests with the Google Cloud mirror." | tee -a "$log" + continue + fi + if ! grep -Eq '^[[:space:]]*(Caused by: org\.gradle\.internal\.resource\.transport\.http\.HttpErrorStatusCodeException: Could not GET .*https://(repo\.maven\.apache\.org|repo1\.maven\.org)/.*Received status code 429 from server|Caused by: java\.io\.IOException: Server returned HTTP response code: 429 for URL: https://(repo\.maven\.apache\.org|repo1\.maven\.org)/)' "$attempt_log"; then + exit "$status" + fi + echo "::warning::Maven Central answered 429; running the unit tests again in ${wait}s" | tee -a "$log" sleep "$wait" done diff --git a/app/build.gradle b/app/build.gradle index b858daf493..513fdef6aa 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -242,6 +242,9 @@ android { doFirst { jvmTemp.mkdirs() } def logTarget = providers.systemProperty('robolectric.logging').orNull if (logTarget != null) systemProperty 'robolectric.logging', logTarget + // Robolectric resolves Android SDK jars inside the test JVM independently of Gradle. + def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull + if (robolectricMirror) systemProperty 'robolectric.dependency.repo.url', robolectricMirror } } diff --git a/settings.gradle b/settings.gradle index 6abc4f6609..21bd4f6605 100644 --- a/settings.gradle +++ b/settings.gradle @@ -8,6 +8,18 @@ pluginManagement { dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { + def robolectricMirror = providers.gradleProperty('robolectricMavenMirror').orNull + if (robolectricMirror) { + exclusiveContent { + forRepository { + maven { + name = 'robolectricMirror' + url = uri(robolectricMirror) + } + } + filter { includeGroup 'org.robolectric' } + } + } google() mavenCentral() maven { url 'https://jitpack.io' } diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index 5b45850fc8..8e3b7e9880 100644 --- a/tools/tests/test_ci_checks.py +++ b/tools/tests/test_ci_checks.py @@ -75,6 +75,85 @@ class CiChecksTest(unittest.TestCase): self.assertIn("outputs.doNotCacheIf('CI executes the test suite on every run') { true }", gradle) self.assertIn('outputs.upToDateWhen { false }', gradle) + def test_unit_tests_switch_mirrors_only_for_robolectric_rate_limits(self): + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] + script = next(step['run'] for step in steps if step.get('id') == 'unit-tests') + central = 'https://repo.maven.apache.org/maven2/' + native = f'{central}org/robolectric/nativeruntime-dist-compat/1.0.18/nativeruntime-dist-compat-1.0.18.jar' + sdk = 'https://repo1.maven.org/maven2/org/robolectric/android-all-instrumented/sdk.jar.sha512' + gradle_error = 'org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException' + get_error = f"Could not GET '{native}'. Received status code 429 from server: Too Many Requests" + mirror = '-ProbolectricMavenMirror=https://maven-central.storage-download.googleapis.com/maven2' + # These two resolvers report the status and URL in opposite orders. + cases = [ + ('ok', 0, 0, 0, 1), + (f'Could not GET {native}. Received status code 429', 1, 0, 0, 2), + (f'Server returned HTTP response code: 429 for URL: {sdk}', 1, 9, 9, 2), + (f' Caused by: {gradle_error}: {get_error}', 1, 0, 0, 2), + (f' Caused by: java.io.IOException: Server returned HTTP response code: 429 for URL: {sdk}', 1, 0, 0, 2), + (f'Failed to get resource: GET. [HTTP HTTP/1.1 429 Too Many Requests: {native})]\n' + 'java.lang.AssertionError: expected a visible window', 7, 0, 7, 1), + ('AssertionError: expected 429', 7, 0, 7, 1), + (f'AssertionError: expected status code 429 for URL: {sdk}', 7, 0, 7, 1), + (f'Caused by: java.lang.AssertionError: {get_error}', 7, 0, 7, 1), + (f'Could not GET {central}other/group/lib.jar. Received status code 429', 8, 0, 8, 1), + ] + for message, first, retry, expected, attempts in cases: + with self.subTest(message=message), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + gradle = root / 'gradlew' + gradle.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n' + 'case "$*" in *-ProbolectricMavenMirror=*) exit "$RETRY";; esac\n' + 'echo "$MESSAGE"\nexit "$FIRST"\n') + gradle.chmod(0o755) + sleep = root / 'sleep' + sleep.write_text('#!/bin/sh\necho "sleep $*" >> calls\n') + sleep.chmod(0o755) + env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], + NDK_VERSION='test', MESSAGE=message, FIRST=str(first), RETRY=str(retry)) + result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, capture_output=True, timeout=15) + self.assertEqual(result.returncode, expected, result.stdout) + calls = (root / 'calls').read_text().splitlines() + self.assertEqual(len(calls), attempts) + self.assertNotIn(mirror, calls[0]) + if attempts == 2: + self.assertEqual(calls[1].split(), [*calls[0].split(), mirror]) + + def test_unit_tests_back_off_on_maven_central_rate_limits(self): + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] + script = next(step['run'] for step in steps if step.get('id') == 'unit-tests') + rate_limit = ( + "Caused by: org.gradle.internal.resource.transport.http.HttpErrorStatusCodeException: " + "Could not GET 'https://repo.maven.apache.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar'. " + "Received status code 429 from server: Too Many Requests" + ) + for exit_codes, expected_status, expected_events in ( + ([7, 0], 0, ['gradle', 'sleep 60', 'gradle']), + ([7, 9, 23, 0], 23, ['gradle', 'sleep 60', 'gradle', 'sleep 180', 'gradle']), + ): + with self.subTest(exit_codes=exit_codes), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'statuses').write_text(''.join(f'{code}\n' for code in exit_codes)) + gradle = root / 'gradlew' + gradle.write_text('#!/bin/sh\n' + 'echo gradle >> events\n' + 'echo "$*" >> gradle-args\n' + 'attempt=$(wc -l < gradle-args)\n' + 'status=$(sed -n "${attempt}p" statuses)\n' + 'if [ "$status" != 0 ]; then echo "$MAVEN_ERROR"; fi\n' + 'exit "${status:-99}"\n') + gradle.chmod(0o755) + sleep = root / 'sleep' + sleep.write_text('#!/bin/sh\necho "sleep $*" >> events\n') + sleep.chmod(0o755) + env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], + NDK_VERSION='test', MAVEN_ERROR=rate_limit) + result = subprocess.run(['bash', '-e', '-c', script], cwd=root, env=env, + capture_output=True, text=True, timeout=15) + self.assertEqual(result.returncode, expected_status, result.stdout + result.stderr) + self.assertEqual((root / 'events').read_text().splitlines(), expected_events) + self.assertNotIn('-ProbolectricMavenMirror=', (root / 'gradle-args').read_text()) + def test_unit_tests_do_not_hold_up_the_apk(self): build = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text()) for step in build['jobs']['build']['steps']: From 153c87389856b76ab83446e94cb27714b13715eb Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:56:39 +0530 Subject: [PATCH 15/80] fix(ui): LB, RB, LT and RT close the keyboard and menus of the page they leave (#3619) --- .../droiddeck/launcher/FrontEndActivity.kt | 5 +- .../droiddeck/launcher/ui/FrontEndScreen.kt | 12 +++ .../com/droiddeck/launcher/ui/GameDetail.kt | 4 +- .../com/droiddeck/launcher/ui/LibraryPage.kt | 28 ++++--- .../com/droiddeck/launcher/ui/ScreenTaps.kt | 9 +++ .../droiddeck/launcher/ui/SettingsWidgets.kt | 74 +++++++++++++++++-- .../java/com/droiddeck/launcher/ui/StepOut.kt | 29 +++++++- 7 files changed, 135 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 1ebd5b7bdf..9192d4371f 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -2247,7 +2247,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet return true } return try { - super.dispatchKeyEvent(event) + super.dispatchKeyEvent(event) || com.droiddeck.launcher.ui.PageBumpers.handle(event) } catch (e: IllegalStateException) { if (e.message?.contains("active focus target") != true) throw e android.util.Log.w("MainActivity", "key ${event.keyCode} dropped: ${e.message}") @@ -2256,6 +2256,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private val triggerKeys = com.droiddeck.launcher.input.TriggerKeys { dispatchKeyEvent(it) } + + internal fun onMenuMotion(event: MotionEvent) = triggerKeys.onMotion(event) + private val rightStickLayouts = HashMap() private val rightStickScrollHandler = android.os.Handler(android.os.Looper.getMainLooper()) private var rightStickScrollDeviceId = -1 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 eb70d0a10b..868d911534 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -457,6 +457,15 @@ internal suspend fun focusWithinFrames(done: () -> Boolean, target: () -> FocusR } } +internal suspend fun holdFocus(held: () -> Boolean, target: () -> FocusRequester?) { + val since = MainTabSteps.otherKeys + repeat(RAIL_HOLD_FRAMES) { frame -> + androidx.compose.runtime.withFrameNanos { } + if (MainTabSteps.otherKeys != since) return + if (frame == 0 || !held()) runCatching { target()?.requestFocus() } + } +} + internal suspend fun focusSoon(target: () -> FocusRequester) { repeat(30) { androidx.compose.runtime.withFrameNanos { } @@ -786,10 +795,13 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val stepScope = androidx.compose.runtime.rememberCoroutineScope() val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey) var railHold by remember { mutableStateOf(null) } + val stepView = androidx.compose.ui.platform.LocalView.current val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int -> if (!processSettingsPageVisible) { val keys = navigationKeys(s) keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key -> + releaseFocusedTextField(stepView) + OpenMenus.leaveAll(withPage = true) PageSwipe.direction = step if (s.dualScreen) { onRailSelect(key); return@let } showRailPage(key, false) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 6d64f033b9..36075081e6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -235,7 +235,7 @@ internal fun GameDetail( steppedTo = null return@LaunchedEffect } - focusSoon { tabFocus.getValue(t) } + holdFocus({ onStrip }) { tabFocus.getValue(t) } steppedTo = null } fun cycle(step: Int) { @@ -243,7 +243,7 @@ internal fun GameDetail( val at = tabs.indexOf(tab).coerceAtLeast(0) val next = tabs[(at + step + tabs.size) % tabs.size] picked = next - if (inPage) steppedTo = next + steppedTo = next } val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 4a7575d275..0b9d0b399e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -531,13 +531,11 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val grid = remember { LazyGridState() } val detailScroll = rememberScrollState() var cycled by remember { mutableIntStateOf(0) } - var gridFocused by remember { mutableStateOf(false) } LaunchedEffect(source, sort) { grid.scrollToItem(0) } LaunchedEffect(cycled) { if (cycled == 0 || ff == null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect - focusWithinFrames({ gridFocused }) { - if (ff.firstTileAttached > 0) ff.firstTile else ff.items["libchip:$source"] ?: FocusRequester.Default - } + val chip = "libchip:$source" + holdFocus({ ff.last == chip }) { ff.items[chip] } } CardDetailHost( open, detailScroll, @@ -563,7 +561,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, else { focusManager.clearFocus(force = true); onSelect(it) } }, searchCleared = open != null, - onFocus = { gridFocused = it }, + onFocus = {}, soundMode = soundMode, wallArt = { wallTiles(all.filterNot(concealed).mapNotNull { entryArt(it, tall = true) }) }, emptyText = when { @@ -753,20 +751,23 @@ private fun LibraryGrid( } } } + val manage = !soundMode && !s.shortcutPicker LazyVerticalGrid( columns = if (listMode) GridCells.Fixed(1) else remember(baseWidth, level) { LevelCells(baseWidth, level) }, state = grid, - modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup().bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }).onSizeChanged { - val gap = with(density) { 10.dp.roundToPx() } - columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level) - gridH = it.height - }, + modifier = Modifier.fillMaxSize().onFocusChanged { onFocus(it.hasFocus) }.focusGroup() + .then(if (sourceChipsShown(sources, manage)) Modifier.bumpers(onPrevious = { onCycle(-1) }, onNext = { onCycle(1) }) else Modifier) + .onSizeChanged { + val gap = with(density) { 10.dp.roundToPx() } + columns = if (listMode) 1 else libraryColumns(it.width, with(density) { baseWidth.roundToPx() }, gap, level) + gridH = it.height + }, horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), contentPadding = PaddingValues(top = 4.dp, bottom = 16.dp), ) { val header: @Composable () -> Unit = { LibraryHeader(s, a, if (soundMode) total else visible.size + hiddenUninstalled, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections, source = source) } - val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage = !soundMode && !s.shortcutPicker) } + val filters: @Composable () -> Unit = { LibraryFilters(sources, source, onSource, manage) } item(key = if (soundMode) "header" else "filters", span = { GridItemSpan(maxLineSpan) }) { Box(Modifier.onSizeChanged { chipsH = it.height }) { Rise(0) { if (soundMode) header() else filters() } } } @@ -908,10 +909,13 @@ private fun LibraryHeader( if (s.steamGamesX64 && narrow) Box(Modifier.padding(top = 4.dp)) { ClientTag() } } +private fun sourceChipsShown(sources: List, manage: Boolean): Boolean = + (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN + @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable private fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit, manage: Boolean) { - val chips = (manage && sources.isNotEmpty()) || sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN + val chips = sourceChipsShown(sources, manage) if (!chips && !manage) return val pal = LocalPalette.current val keys = if (chips) listOf(LIBRARY_ALL) + sources else emptyList() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt index 20c942dea6..d61e51bdd7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScreenTaps.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.ui import android.content.Context +import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.compose.foundation.gestures.awaitEachGesture @@ -48,10 +49,18 @@ internal fun releaseTextField(field: EditText, origin: IntArray, x: Float, y: Fl val insideX = x >= origin[0] - margin && x <= origin[0] + field.width + margin val insideY = y >= origin[1] - margin && y <= origin[1] + field.height + margin if (insideX && insideY) return + releaseTextField(field) +} + +internal fun releaseTextField(field: EditText) { field.clearFocus() (field.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(field.windowToken, 0) } +internal fun releaseFocusedTextField(view: View) { + (view.rootView.findFocus() as? EditText)?.let(::releaseTextField) +} + /** A dialog's touches never reach the activity, so a dialog holding a search field counts its taps and releases the field itself. */ internal fun Modifier.releaseTextFieldOnTap(): Modifier = composed { val view = LocalView.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index d1889d6fb9..2c51442cd1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -87,6 +87,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.node.currentValueOf import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures @@ -152,14 +153,43 @@ internal fun Modifier.blockTouches(): Modifier = pointerInput(Unit) { detectTapG internal fun Modifier.tapOutside(onTap: () -> Unit): Modifier = pointerInput(onTap) { detectTapGestures(onTap = { onTap() }) } -internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = onPreviewKeyEvent { event -> - val keyEvent = event.nativeKeyEvent - val previous = keyEvent.keyCode == KeyEvent.KEYCODE_BUTTON_L1 - if (!previous && keyEvent.keyCode != KeyEvent.KEYCODE_BUTTON_R1) { - false - } else { - if (keyEvent.action == KeyEvent.ACTION_DOWN && keyEvent.repeatCount == 0) { if (previous) onPrevious() else onNext() } - true +internal fun Modifier.bumpers(onPrevious: () -> Unit, onNext: () -> Unit): Modifier = this then BumpersElement(onPrevious, onNext) + +private data class BumpersElement(val onPrevious: () -> Unit, val onNext: () -> Unit) : + androidx.compose.ui.node.ModifierNodeElement() { + override fun create() = BumpersNode(onPrevious, onNext) + override fun update(node: BumpersNode) { + node.onPrevious = onPrevious + node.onNext = onNext + } +} + +internal class BumpersNode(var onPrevious: () -> Unit, var onNext: () -> Unit) : + Modifier.Node(), androidx.compose.ui.input.key.KeyInputModifierNode, androidx.compose.ui.node.CompositionLocalConsumerModifierNode { + override fun onAttach() { PageBumpers.attached += this } + override fun onDetach() { PageBumpers.attached -= this } + override fun onPreKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = PageBumpers.handle(event.nativeKeyEvent, this) + override fun onKeyEvent(event: androidx.compose.ui.input.key.KeyEvent): Boolean = false + + @OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) + fun step(previous: Boolean) { + releaseFocusedTextField(currentValueOf(androidx.compose.ui.platform.LocalView)) + OpenMenus.leaveAll(withPage = false) + if (previous) onPrevious() else onNext() + // Android keeps touch mode through gamepad buttons, and the pages move the focus only outside it. + val input = currentValueOf(LocalInputModeManager) + if (input.inputMode != InputMode.Keyboard) input.requestInputMode(InputMode.Keyboard) + } +} + +internal object PageBumpers { + val attached = ArrayList() + + fun handle(event: KeyEvent, node: BumpersNode? = attached.lastOrNull()): Boolean { + val previous = event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 + if (node == null || (!previous && event.keyCode != KeyEvent.KEYCODE_BUTTON_R1)) return false + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) node.step(previous) + return true } } @@ -267,6 +297,25 @@ private class BelowEndProvider(private val gap: Int) : PopupPositionProvider { } } +private val StepKeys = setOf(KeyEvent.KEYCODE_BUTTON_L1, KeyEvent.KEYCODE_BUTTON_R1, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2) + +private fun launcherOf(view: android.view.View) = view.context.findActivity() as? com.droiddeck.launcher.FrontEndActivity + +// A popup is a window of its own, so controller input sent to it never reaches the launcher's. +private fun Modifier.passSteps(host: android.view.View): Modifier = onPreviewKeyEvent { event -> + event.nativeKeyEvent.keyCode in StepKeys && launcherOf(host) != null && host.rootView.dispatchKeyEvent(event.nativeKeyEvent) +} + +@Composable +private fun PassTriggerMotion(host: android.view.View) { + val popup = androidx.compose.ui.platform.LocalView.current + androidx.compose.runtime.DisposableEffect(popup, host) { + val launcher = launcherOf(host)?.takeIf { it.window.decorView === host.rootView } + if (launcher != null) popup.setOnGenericMotionListener { _, event -> launcher.onMenuMotion(event); false } + onDispose { popup.setOnGenericMotionListener(null) } + } +} + @OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) @Composable fun AnchoredMenu( @@ -277,6 +326,13 @@ fun AnchoredMenu( val state = remember { MutableTransitionState(false) } state.targetState = open if (!state.currentState && !state.targetState && state.isIdle) return + val dismissNow = rememberUpdatedState(onDismiss) + if (open) androidx.compose.runtime.DisposableEffect(Unit) { + val leave = { _: Boolean -> dismissNow.value() } + OpenMenus.leave += leave + onDispose { OpenMenus.leave -= leave } + } + val hostView = androidx.compose.ui.platform.LocalView.current val firstItemFocus = remember { FocusRequester() } val inputMode = LocalInputModeManager.current.inputMode LaunchedEffect(open, inputMode) { @@ -294,6 +350,7 @@ fun AnchoredMenu( val pal = LocalPalette.current Popup(popupPositionProvider = provider, onDismissRequest = onDismiss, properties = PopupProperties(focusable = true)) { TrackKeyWindow() + PassTriggerMotion(hostView) val popupInput = LocalInputModeManager.current LaunchedEffect(open, inputMode) { if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect @@ -323,6 +380,7 @@ fun AnchoredMenu( .clip(RowShape) .background(pal.surfaceVariant.copy(alpha = 0.95f)) .border(1.dp, pal.signal.copy(alpha = 0.22f), RowShape) + .passSteps(hostView) .controllerBack(onDismiss) .padding(6.dp), ) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt index 084de26ccd..20a18aa845 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StepOut.kt @@ -145,6 +145,12 @@ internal class StepOutScope(private val items: List Unit>() + + fun leaveAll(withPage: Boolean) = leave.toList().forEach { it(withPage) } +} + private val OutPull = 6.dp private val OutBoxCorner = 16.dp private val OutFillet = 10.dp @@ -194,13 +200,25 @@ private fun StepOutPanel( val glide = LocalFocusGlide.current val opener = remember { arrayOfNulls(1) } val openNow = androidx.compose.runtime.rememberUpdatedState(open) + val dismissNow = androidx.compose.runtime.rememberUpdatedState(onDismiss) + val leavesWithPage = remember { booleanArrayOf(false) } + val presence = remember { Animatable(1f) } + if (open) androidx.compose.runtime.DisposableEffect(Unit) { + val leave = { withPage: Boolean -> + opener[0] = null + leavesWithPage[0] = withPage + dismissNow.value() + } + OpenMenus.leave += leave + onDispose { OpenMenus.leave -= leave } + } var moving by remember { mutableStateOf(false) } val placed = remember { arrayOfNulls(3) } if (moving) VeilRing() val pull = with(density) { OutPull.toPx() } val corner = pillCorner?.let { with(density) { it.toPx() } } ?: minOf(pill.height, pill.width) / 2f - BoxWithConstraints(Modifier.fillMaxSize()) { + BoxWithConstraints(Modifier.fillMaxSize().graphicsLayer { alpha = presence.value }) { val hostWidth = constraints.maxWidth.toFloat() val hostHeight = constraints.maxHeight.toFloat() val availableHeight = with(density) { @@ -221,9 +239,11 @@ private fun StepOutPanel( if (grown && flipped) edge.snapTo(if (open) out else rest) val boxBottom = pill.bottom + pull + c.height if (open) { + leavesWithPage[0] = false + presence.snapTo(1f) if (!grown) { opener[0] = glide?.current - edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f) + edge.snapTo(rest); bottom.snapTo(pill.bottom); tint.snapTo(0f); dim.snapTo(0f) pieces.forEach { it.snapTo(0f) } grown = true } @@ -241,7 +261,10 @@ private fun StepOutPanel( } else { opener[0]?.let { o -> if (inputMode.inputMode == InputMode.Keyboard) runCatching { o.requester.requestFocus() } } opener[0] = null - coroutineScope { + if (leavesWithPage[0]) { + moving = true + presence.animateTo(0f, Motion.tw(160)) + } else coroutineScope { pieces.forEach { launch { it.animateTo(0f, Motion.tw(90)) } } launch { delay(Motion.ms(60).toLong()); dim.animateTo(0f, Motion.tw(300)) } moving = true From 673675b45e31bc1976da2c69335b0b59cebe705c Mon Sep 17 00:00:00 2001 From: FryMcNugget Date: Thu, 3 Dec 2026 12:28:05 +0000 Subject: [PATCH 16/80] feat(quest): DroidDeck's menu, agent pet and keyboards float in the immersive SteamVR view (#3596) --- app/src/main/AndroidManifest.xml | 11 + app/src/main/cpp/questxr/CMakeLists.txt | 2 +- app/src/main/cpp/questxr/quest_xr.cpp | 346 +++++++++- app/src/main/cpp/questxr/xr_host.h | 91 +++ app/src/main/cpp/questxr/xr_overlay.h | 229 +++++++ .../com/droiddeck/launcher/QuestXrActivity.kt | 31 +- .../com/droiddeck/launcher/SessionActivity.kt | 156 ++++- .../launcher/agent/AgentChatActivity.kt | 48 ++ .../droiddeck/launcher/agent/AgentGuest.kt | 2 +- .../launcher/session/xr/XrGesture.kt | 68 ++ .../droiddeck/launcher/session/xr/XrHost.kt | 160 +++++ .../launcher/session/xr/XrInteraction.kt | 303 +++++++++ .../launcher/session/xr/XrKeyboard.kt | 283 ++++++++ .../droiddeck/launcher/session/xr/XrMath.kt | 61 ++ .../launcher/session/xr/XrPanelChrome.kt | 126 ++++ .../launcher/session/xr/XrPanelWindow.kt | 271 ++++++++ .../droiddeck/launcher/session/xr/XrPanels.kt | 611 ++++++++++++++++++ .../launcher/session/xr/XrSteamScreen.kt | 16 + .../com/droiddeck/launcher/ui/AgentPet.kt | 20 +- .../droiddeck/launcher/ui/DrawerEntryHint.kt | 27 + .../droiddeck/launcher/ui/FrontEndSetup.kt | 2 +- .../com/droiddeck/launcher/ui/PcKeyboard.kt | 57 +- .../launcher/session/xr/XrGestureTest.kt | 53 ++ .../launcher/session/xr/XrHostTest.kt | 84 +++ .../launcher/session/xr/XrInteractionTest.kt | 246 +++++++ .../launcher/session/xr/XrPanelsGateTest.kt | 113 ++++ .../launcher/session/xr/XrPcTextTest.kt | 72 +++ .../launcher/session/xr/XrPlacementTest.kt | 67 ++ .../launcher/session/xr/XrSteamScreenTest.kt | 23 + .../launcher/ui/AgentPetQuestTest.kt | 24 + tools/release/sign-apk.sh | 2 +- 31 files changed, 3543 insertions(+), 62 deletions(-) create mode 100644 app/src/main/cpp/questxr/xr_host.h create mode 100644 app/src/main/cpp/questxr/xr_overlay.h create mode 100644 app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 38e888731e..5db5b11509 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -277,6 +277,17 @@ android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" android:theme="@style/AppTheme" /> + + + + #include #include +#include #include #include #include @@ -22,10 +23,14 @@ #include #include #include +#include +#include #include "xr_tracking.h" #include "xr_frame_channel.h" #include "xr_frame_math.h" #include "gpu_frames.h" +#include "xr_host.h" +#include "xr_overlay.h" static void check(XrResult result, const char *operation) { if (XR_FAILED(result)) throw std::runtime_error(std::string(operation) + ": " + std::to_string(result)); @@ -37,6 +42,15 @@ struct Eye { std::vector images; }; +struct SurfaceLayer { + XrSwapchain swapchain = XR_NULL_HANDLE; + jobject surface = nullptr; + int width = 0, height = 0; +}; + +class QuestXR; +static QuestXR *g_runtime = nullptr; + class QuestXR { public: explicit QuestXR(android_app *app) : app_(app) {} @@ -76,21 +90,74 @@ public: "\"headPosition\":[%.6f,%.6f,%.6f],\"controllersActive\":[%s,%s]," "\"periodNs\":%lld,\"surfaceSwapchain\":%s,\"source\":\"%s\",\"guestFrames\":%lld,\"steamvrState\":%d," "\"receivedFrames\":%llu,\"rejectedFrames\":%llu,\"uploadedFrames\":%llu,\"sourceFrameId\":%llu," - "\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u,\"error\":\"%s\"}\n", + "\"gpuReceivedFrames\":%llu,\"gpuDroppedFrames\":%llu,\"gpuVerifiedFrameId\":%llu,\"gpuChecksum\":%u," + "\"hostVersion\":%u,\"visibleLayers\":%d,\"overlay\":%s,\"error\":\"%s\"}\n", (unsigned long long)frames_, (unsigned long long)rendered_, state_, (unsigned long long)head_.locationFlags, head_.pose.position.x, head_.pose.position.y, head_.pose.position.z, handActive_[0] ? "true" : "false", handActive_[1] ? "true" : "false", - (long long)period_, "false", "frames", + (long long)period_, surfaceSupported_ ? "true" : "false", "frames", 0LL, steamvrState, (unsigned long long)(receiver_.Received() + gpuFrames_.Received()), (unsigned long long)(receiver_.Rejected() + gpuFrames_.Rejected()), (unsigned long long)uploadedFrames_, (unsigned long long)sourceHeader_.frame_id, (unsigned long long)gpuFrames_.Received(), (unsigned long long)gpuFrames_.Dropped(), - (unsigned long long)verifiedFrame_, gpuChecksum_, error); + (unsigned long long)verifiedFrame_, gpuChecksum_, + hostBuffers_ ? DROIDDECK_XR_HOST_VERSION : 0u, visibleLayers_, + XrOverlay::active(hostControl_) ? "true" : "false", error); std::fclose(file); std::rename(temp.c_str(), path.c_str()); } + bool onXrThread() const { return pthread_equal(pthread_self(), xrThread_); } + + int createLayer(JNIEnv *env, int width, int height) { + if (!onXrThread() || !createSurfaceSwapchain_ || session_ == XR_NULL_HANDLE || width <= 0 || height <= 0) return -1; + for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) { + SurfaceLayer &layer = layers_[index]; + if (layer.swapchain) continue; + XrSwapchainCreateInfo create{XR_TYPE_SWAPCHAIN_CREATE_INFO}; + create.usageFlags = XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT; + create.width = width; create.height = height; + jobject surface = nullptr; + XrResult result = createSurfaceSwapchain_(session_, &create, &layer.swapchain, &surface); + if (XR_FAILED(result) || !surface) { + __android_log_print(ANDROID_LOG_ERROR, "DroidDeckXR", "surface layer %dx%d failed: %d", width, height, result); + if (layer.swapchain) xrDestroySwapchain(layer.swapchain); + layer = {}; + return -1; + } + layer.surface = env->NewGlobalRef(surface); + layer.width = width; layer.height = height; + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface layer %d created %dx%d", index, width, height); + return index; + } + return -1; + } + + jobject layerSurface(JNIEnv *env, int index) { + if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS || !layers_[index].surface) return nullptr; + return env->NewLocalRef(layers_[index].surface); + } + + void setOrbImage(JNIEnv *env, jobject bitmap) { + if (!onXrThread() || !bitmap) return; + AndroidBitmapInfo info{}; + void *pixels = nullptr; + if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS + || info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) return; + if (AndroidBitmap_lockPixels(env, bitmap, &pixels) != ANDROID_BITMAP_RESULT_SUCCESS) return; + overlay_.setLogo(pixels, (int)info.width, (int)info.height, (int)info.stride); + AndroidBitmap_unlockPixels(env, bitmap); + } + + void destroyLayer(JNIEnv *env, int index) { + if (!onXrThread() || index < 0 || index >= DROIDDECK_XR_HOST_LAYERS) return; + SurfaceLayer &layer = layers_[index]; + if (layer.swapchain) xrDestroySwapchain(layer.swapchain); + if (layer.surface) env->DeleteGlobalRef(layer.surface); + layer = {}; + } + private: android_app *app_; JNIEnv *env_ = nullptr; @@ -104,6 +171,20 @@ private: XrAction primary_ = XR_NULL_HANDLE, secondary_ = XR_NULL_HANDLE, menu_ = XR_NULL_HANDLE; XrAction triggerTouch_ = XR_NULL_HANDLE, stickTouch_ = XR_NULL_HANDLE, primaryTouch_ = XR_NULL_HANDLE; XrAction secondaryTouch_ = XR_NULL_HANDLE, thumbrestTouch_ = XR_NULL_HANDLE; + PFN_xrCreateSwapchainAndroidSurfaceKHR createSurfaceSwapchain_ = nullptr; + bool surfaceSupported_ = false; + bool imageLayoutSupported_ = false; + pthread_t xrThread_{}; + SurfaceLayer layers_[DROIDDECK_XR_HOST_LAYERS]; + DroidDeckXrHostState hostState_{}; + DroidDeckXrHostControl hostControl_{}; + bool hostBuffers_ = false; + jmethodID hostFrameCallback_ = nullptr; + uint64_t hostPulse_[2]{}; + int visibleLayers_ = 0; + XrOverlay overlay_; + Eye overlayEyes_[2]; + GLuint overlayDepth_[2]{}; DroidDeckXrHand inputs_[2]{}; PFN_xrConvertTimeToTimespecTimeKHR convertTime_ = nullptr; bool timespecSupported_ = false; @@ -220,6 +301,8 @@ private: void initialize() { app_->userData = this; + xrThread_ = pthread_self(); + g_runtime = this; app_->onInputEvent = [](android_app *app, AInputEvent *event) -> int32_t { if (AInputEvent_getType(event) != AINPUT_EVENT_TYPE_KEY || AKeyEvent_getKeyCode(event) != AKEYCODE_BACK || AKeyEvent_getAction(event) != AKEY_EVENT_ACTION_UP) return 0; @@ -244,6 +327,10 @@ private: frameCallback_ = env_->GetMethodID(activityClass, "onXrFrame", "(J)V"); statusCallback_ = env_->GetMethodID(activityClass, "onXrStatus", "()I"); if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("XR activity bridge methods unavailable"); } + hostFrameCallback_ = env_->GetMethodID(activityClass, "onXrHostFrame", "()V"); + jmethodID hostBuffersCallback = hostFrameCallback_ ? + env_->GetMethodID(activityClass, "onXrHostBuffers", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)V") : nullptr; + if (env_->ExceptionCheck()) { env_->ExceptionClear(); hostFrameCallback_ = nullptr; hostBuffersCallback = nullptr; } env_->DeleteLocalRef(intentClass); env_->DeleteLocalRef(intent); env_->DeleteLocalRef(activityClass); PFN_xrInitializeLoaderKHR initializeLoader = nullptr; check(xrGetInstanceProcAddr(XR_NULL_HANDLE, "xrInitializeLoaderKHR", @@ -261,10 +348,21 @@ private: timespecSupported_ = true; if (!std::strcmp(extension.extensionName, XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME)) performanceSupported_ = true; + if (!std::strcmp(extension.extensionName, XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME)) + surfaceSupported_ = true; + if (!std::strcmp(extension.extensionName, XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME)) + imageLayoutSupported_ = true; } + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "surface swapchain available=%d image layout=%d", + surfaceSupported_, imageLayoutSupported_); + // A surface swapchain's image arrives upside down, and a quad's back face is not drawn, so + // panels need the layout flag to flip it. + surfaceSupported_ = surfaceSupported_ && imageLayoutSupported_; std::vector enabled{XR_KHR_ANDROID_CREATE_INSTANCE_EXTENSION_NAME, XR_KHR_OPENGL_ES_ENABLE_EXTENSION_NAME}; if (timespecSupported_) enabled.push_back(XR_KHR_CONVERT_TIMESPEC_TIME_EXTENSION_NAME); if (performanceSupported_) enabled.push_back(XR_EXT_PERFORMANCE_SETTINGS_EXTENSION_NAME); + if (surfaceSupported_) enabled.push_back(XR_KHR_ANDROID_SURFACE_SWAPCHAIN_EXTENSION_NAME); + if (surfaceSupported_) enabled.push_back(XR_FB_COMPOSITION_LAYER_IMAGE_LAYOUT_EXTENSION_NAME); XrInstanceCreateInfoAndroidKHR androidInfo{XR_TYPE_INSTANCE_CREATE_INFO_ANDROID_KHR}; androidInfo.applicationVM = app_->activity->vm; androidInfo.applicationActivity = app_->activity->clazz; @@ -281,6 +379,11 @@ private: reinterpret_cast(&setPerformance_)); if (XR_FAILED(result)) setPerformance_ = nullptr; } + if (surfaceSupported_ && XR_FAILED(xrGetInstanceProcAddr(instance_, "xrCreateSwapchainAndroidSurfaceKHR", + reinterpret_cast(&createSurfaceSwapchain_)))) { + createSurfaceSwapchain_ = nullptr; + surfaceSupported_ = false; + } if (timespecSupported_) check(xrGetInstanceProcAddr(instance_, "xrConvertTimeToTimespecTimeKHR", reinterpret_cast(&convertTime_)), "time conversion entrypoint"); XrSystemGetInfo systemInfo{XR_TYPE_SYSTEM_GET_INFO}; @@ -334,6 +437,16 @@ private: bool gpu = !verifyPixels_ && gpuFrames_.Start(std::string(app_->activity->internalDataPath) + "/.wayland-rt/" DROIDDECK_XR_GPU_SOCKET, display_); __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "GPU frame channel available=%d", gpu); } + overlay_.initialize(); + hostState_.version = DROIDDECK_XR_HOST_VERSION; + if (hostBuffersCallback) { + jobject state = env_->NewDirectByteBuffer(&hostState_, sizeof(hostState_)); + jobject control = env_->NewDirectByteBuffer(&hostControl_, sizeof(hostControl_)); + env_->CallVoidMethod(app_->activity->clazz, hostBuffersCallback, state, control); + if (env_->ExceptionCheck()) { env_->ExceptionDescribe(); env_->ExceptionClear(); hostFrameCallback_ = nullptr; } + else hostBuffers_ = true; + env_->DeleteLocalRef(state); env_->DeleteLocalRef(control); + } health(); } @@ -422,6 +535,13 @@ private: target.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR}); check(xrEnumerateSwapchainImages(target.swapchain, count, &count, reinterpret_cast(target.images.data())), "images"); + Eye &overlay = overlayEyes_[eye]; + overlay.width = target.width; overlay.height = target.height; + check(xrCreateSwapchain(session_, &create, &overlay.swapchain), "overlay swapchain"); + check(xrEnumerateSwapchainImages(overlay.swapchain, 0, &count, nullptr), "overlay image count"); + overlay.images.resize(count, {XR_TYPE_SWAPCHAIN_IMAGE_OPENGL_ES_KHR}); + check(xrEnumerateSwapchainImages(overlay.swapchain, count, &count, + reinterpret_cast(overlay.images.data())), "overlay images"); } } @@ -530,6 +650,12 @@ private: void initializeGraphics() { glGenFramebuffers(1, &framebuffer_); + glGenRenderbuffers(2, overlayDepth_); + for (int eye = 0; eye < 2; eye++) { + glBindRenderbuffer(GL_RENDERBUFFER, overlayDepth_[eye]); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, overlayEyes_[eye].width, overlayEyes_[eye].height); + } + glBindRenderbuffer(GL_RENDERBUFFER, 0); glGenVertexArrays(1, &vertexArray_); GLuint vertex = shader(GL_VERTEX_SHADER, "#version 300 es\nout vec2 uv; uniform float eye; void main(){vec2 coordinate=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));uv=vec2(coordinate.x*0.5+eye*0.5,1.0-coordinate.y);gl_Position=vec4(coordinate*2.0-1.0,0.0,1.0);}"); @@ -584,24 +710,46 @@ private: if (verifyPixels_ || uploadedFrames_ % 72 == 1) health(); } - void render(Eye &eye, uint32_t image) { + void render(Eye &eye, uint32_t image, bool source, const XrPosef &pose, const XrFovf &fov, float seconds) { glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw std::runtime_error("Incomplete eye framebuffer"); - { - glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST); + glViewport(0, 0, eye.width, eye.height); glDisable(GL_DEPTH_TEST); + if (source) { glUseProgram(sourceProgram_); glBindVertexArray(vertexArray_); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sourceTexture_); glUniform1i(glGetUniformLocation(sourceProgram_, "source"), 0); glUniform1f(glGetUniformLocation(sourceProgram_, "eye"), &eye == &eyes_[1] ? 1.f : 0.f); glDrawArrays(GL_TRIANGLES, 0, 3); + } else { + glClearColor(0.f, 0.f, 0.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT); } glBindFramebuffer(GL_FRAMEBUFFER, 0); if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL render error"); glFlush(); } + // Lasers and the orb go in their own layer above the panels, which only the panels' depth hides. + void renderOverlay(int index, uint32_t image, const XrPosef &pose, const XrFovf &fov, float seconds) { + Eye &eye = overlayEyes_[index]; + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eye.images[image].image, 0); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, overlayDepth_[index]); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + throw std::runtime_error("Incomplete overlay framebuffer"); + glViewport(0, 0, eye.width, eye.height); + glClearColor(0.f, 0.f, 0.f, 0.f); glClearDepthf(1.f); + glDepthMask(GL_TRUE); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + overlay_.draw(pose, fov, hostControl_, hostState_, seconds); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + if (glGetError() != GL_NO_ERROR) throw std::runtime_error("OpenGL overlay error"); + glFlush(); + } + void pollEvents() { XrEventDataBuffer event{XR_TYPE_EVENT_DATA_BUFFER}; XrResult result; @@ -685,6 +833,7 @@ private: XrViewState viewState{XR_TYPE_VIEW_STATE}; uint32_t count = 0; XrView views[2]{{XR_TYPE_VIEW}, {XR_TYPE_VIEW}}; check(xrLocateViews(session_, &locate, &viewState, 2, &count, views), "xrLocateViews"); + hostFrame(frameState.predictedDisplayTime); publishTracking(views, frameState.predictedDisplayTime); if (guestAttached_) { timespec now{}; clock_gettime(CLOCK_MONOTONIC, &now); @@ -692,29 +841,34 @@ private: if (env_->ExceptionCheck()) { env_->ExceptionClear(); throw std::runtime_error("Guest frame callback failed"); } } XrCompositionLayerProjectionView projection[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}}; - bool valid = frameState.shouldRender && count == 2 && + const bool viewsValid = frameState.shouldRender && count == 2 && (viewState.viewStateFlags & (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT)) == (XR_VIEW_STATE_ORIENTATION_VALID_BIT | XR_VIEW_STATE_POSITION_VALID_BIT); - { - valid = valid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL; - if (valid) for (int eye = 0; eye < 2; eye++) { - auto source = xr_frame_view(sourceHeader_, eye); - views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]}; - views[eye].pose.position = {source.position[0], source.position[1], source.position[2]}; - views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]}; - } + bool valid = viewsValid && sourceHeader_.frame_id && xr_frame_now() - sourceHeader_.captured_ns < 500000000LL; + if (valid) for (int eye = 0; eye < 2; eye++) { + auto source = xr_frame_view(sourceHeader_, eye); + views[eye].pose.orientation = {source.orientation[0], source.orientation[1], source.orientation[2], source.orientation[3]}; + views[eye].pose.position = {source.position[0], source.position[1], source.position[2]}; + views[eye].fov = {source.fov[0], source.fov[1], source.fov[2], source.fov[3]}; } + std::vector quads; + std::vector layouts; + if (viewsValid) collectQuads(quads, layouts); + const bool uiOnly = !valid && viewsValid && !quads.empty(); + const bool draw = valid || uiOnly; const std::string capture = captureRequest(); bool captured = valid; if (!capture.empty() && valid) captured = captureTexture(sourceTexture_, sourceHeader_.width, sourceHeader_.height, "source"); - if (valid) for (int eye = 0; eye < 2; eye++) { + timespec clock{}; clock_gettime(CLOCK_MONOTONIC, &clock); + const float seconds = (float)(clock.tv_sec % 3600) + clock.tv_nsec * 1e-9f; + if (draw) for (int eye = 0; eye < 2; eye++) { uint32_t image = 0; XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; check(xrAcquireSwapchainImage(eyes_[eye].swapchain, &acquire, &image), "acquire image"); XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION; check(xrWaitSwapchainImage(eyes_[eye].swapchain, &imageWait), "wait image"); - render(eyes_[eye], image); + render(eyes_[eye], image, valid, views[eye].pose, views[eye].fov, seconds); if (!capture.empty()) captured = captureTexture(eyes_[eye].images[image].image, eyes_[eye].width, eyes_[eye].height, eye ? "right" : "left") && captured; XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; check(xrReleaseSwapchainImage(eyes_[eye].swapchain, &release), "release image"); @@ -722,19 +876,143 @@ private: projection[eye].subImage.swapchain = eyes_[eye].swapchain; projection[eye].subImage.imageRect.extent = {eyes_[eye].width, eyes_[eye].height}; } + const bool overlay = viewsValid && hostBuffers_ && XrOverlay::active(hostControl_); + XrCompositionLayerProjectionView overlayViews[2]{{XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}, {XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW}}; + if (overlay) for (int eye = 0; eye < 2; eye++) { + uint32_t image = 0; + XrSwapchainImageAcquireInfo acquire{XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO}; + check(xrAcquireSwapchainImage(overlayEyes_[eye].swapchain, &acquire, &image), "acquire overlay image"); + XrSwapchainImageWaitInfo imageWait{XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO}; imageWait.timeout = XR_INFINITE_DURATION; + check(xrWaitSwapchainImage(overlayEyes_[eye].swapchain, &imageWait), "wait overlay image"); + renderOverlay(eye, image, views[eye].pose, views[eye].fov, seconds); + XrSwapchainImageReleaseInfo release{XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO}; + check(xrReleaseSwapchainImage(overlayEyes_[eye].swapchain, &release), "release overlay image"); + overlayViews[eye].pose = views[eye].pose; overlayViews[eye].fov = views[eye].fov; + overlayViews[eye].subImage.swapchain = overlayEyes_[eye].swapchain; + overlayViews[eye].subImage.imageRect.extent = {overlayEyes_[eye].width, overlayEyes_[eye].height}; + } XrCompositionLayerProjection layer{XR_TYPE_COMPOSITION_LAYER_PROJECTION}; layer.space = world_; layer.viewCount = 2; layer.views = projection; - const XrCompositionLayerBaseHeader *layers[] = {reinterpret_cast(&layer)}; + XrCompositionLayerProjection overlayLayer{XR_TYPE_COMPOSITION_LAYER_PROJECTION}; + overlayLayer.layerFlags = XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT; + overlayLayer.space = world_; overlayLayer.viewCount = 2; overlayLayer.views = overlayViews; + std::vector layers; + if (draw) layers.push_back(reinterpret_cast(&layer)); + for (auto &quad : quads) layers.push_back(reinterpret_cast(&quad)); + if (overlay) layers.push_back(reinterpret_cast(&overlayLayer)); + visibleLayers_ = (int)quads.size(); XrFrameEndInfo end{XR_TYPE_FRAME_END_INFO}; end.displayTime = frameState.predictedDisplayTime; - end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; end.layerCount = valid ? 1 : 0; end.layers = layers; + end.environmentBlendMode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE; + end.layerCount = (uint32_t)layers.size(); end.layers = layers.data(); check(xrEndFrame(session_, &end), "xrEndFrame"); if (!capture.empty()) captureResult(capture, captured, valid, projection, frameState.predictedDisplayTime); frames_++; if (valid) rendered_++; if (frames_ % 72 == 0) { health(); - __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld", + __android_log_print(ANDROID_LOG_INFO, "DroidDeckXR", "frames=%llu rendered=%llu head=%llu hands=%d,%d period=%lld layers=%d", (unsigned long long)frames_, (unsigned long long)rendered_, (unsigned long long)head_.locationFlags, - handActive_[0], handActive_[1], (long long)period_); + handActive_[0], handActive_[1], (long long)period_, visibleLayers_); + } + } + + // Android surfaces are stored top row first, while OpenXR samples images bottom row first. + void collectQuads(std::vector &quads, std::vector &layouts) { + if (!hostBuffers_) return; + quads.reserve(DROIDDECK_XR_HOST_LAYERS); + layouts.reserve(DROIDDECK_XR_HOST_LAYERS); + const DroidDeckXrHostLayer *ordered[DROIDDECK_XR_HOST_LAYERS]; + int visible = 0; + for (const auto &layer : hostControl_.layers) { + if (!layer.visible || layer.id < 0 || layer.id >= DROIDDECK_XR_HOST_LAYERS || !layers_[layer.id].swapchain) continue; + if (!(layer.width > 0.f) || !(layer.height > 0.f)) continue; + ordered[visible++] = &layer; + } + std::sort(ordered, ordered + visible, [](const DroidDeckXrHostLayer *a, const DroidDeckXrHostLayer *b) { return a->order < b->order; }); + for (int index = 0; index < visible; index++) { + const auto &layer = *ordered[index]; + const SurfaceLayer &surface = layers_[layer.id]; + XrCompositionLayerQuad quad{XR_TYPE_COMPOSITION_LAYER_QUAD}; + quad.layerFlags = (layer.flags & DROIDDECK_XR_HOST_LAYER_ALPHA) ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT : 0; + quad.space = (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) ? view_ : world_; + quad.eyeVisibility = XR_EYE_VISIBILITY_BOTH; + quad.subImage.swapchain = surface.swapchain; + quad.subImage.imageRect.extent = {surface.width, surface.height}; + quad.pose.orientation = {layer.pose.orientation[0], layer.pose.orientation[1], layer.pose.orientation[2], layer.pose.orientation[3]}; + quad.pose.position = {layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]}; + quad.size = {layer.width, layer.height}; + layouts.push_back({XR_TYPE_COMPOSITION_LAYER_IMAGE_LAYOUT_FB, nullptr, XR_COMPOSITION_LAYER_IMAGE_LAYOUT_VERTICAL_FLIP_BIT_FB}); + quad.next = &layouts.back(); + quads.push_back(quad); + } + } + + // SteamVR draws its laser from the "tip" of the Quest Touch render model the driver names + // (resources/rendermodels/oculus_quest_plus_controller_*), placed on the raw grip pose; panels + // use the same ray so there is one laser per controller. + static DroidDeckXrPose steamVrPointer(const XrSpaceLocation &grip, int hand) { + const float q[4] = {grip.pose.orientation.x, grip.pose.orientation.y, grip.pose.orientation.z, grip.pose.orientation.w}; + const XrVec3 tip{hand == 0 ? 0.016694f : -0.016694f, -0.02522f, 0.024687f}; + const XrVec3 at = XrVec3{grip.pose.position.x, grip.pose.position.y, grip.pose.position.z} + rotate(q, tip); + const float tx = -0.320613f, tw = 0.947210f; + DroidDeckXrPose pose{}; + pose.orientation[0] = q[3] * tx + q[0] * tw; + pose.orientation[1] = q[1] * tw + q[2] * tx; + pose.orientation[2] = q[2] * tw - q[1] * tx; + pose.orientation[3] = q[3] * tw - q[0] * tx; + pose.position[0] = at.x; pose.position[1] = at.y; pose.position[2] = at.z; + pose.flags = (uint32_t)grip.locationFlags; + return pose; + } + + void hostFrame(XrTime predicted) { + if (!hostBuffers_ || !hostFrameCallback_) return; + hostState_.version = DROIDDECK_XR_HOST_VERSION; + hostState_.session_state = state_; + hostState_.flags = (surfaceSupported_ ? DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN : 0u) | + (state_ == XR_SESSION_STATE_FOCUSED ? DROIDDECK_XR_HOST_FOCUSED : 0u); + hostState_.frame = (int64_t)frames_; + hostState_.display_time_ns = 0; + if (convertTime_) { + timespec displayTime{}; + if (XR_SUCCEEDED(convertTime_(instance_, predicted, &displayTime))) + hostState_.display_time_ns = (int64_t)displayTime.tv_sec * 1000000000LL + displayTime.tv_nsec; + } + hostState_.head = posePacket(head_.pose, head_.locationFlags); + const XrSpaceLocationFlags tracked = XR_SPACE_LOCATION_ORIENTATION_VALID_BIT | XR_SPACE_LOCATION_POSITION_VALID_BIT; + for (int hand = 0; hand < 2; hand++) { + auto &out = hostState_.hands[hand]; + out.grip = posePacket(handLocations_[hand].pose, handLocations_[hand].locationFlags); + out.aim = steamVrPointer(handLocations_[hand], hand); + out.trigger = inputs_[hand].trigger; out.squeeze = inputs_[hand].squeeze; + out.stick[0] = inputs_[hand].stick[0]; out.stick[1] = inputs_[hand].stick[1]; + out.buttons = inputs_[hand].buttons; + out.active = handActive_[hand] && (handLocations_[hand].locationFlags & tracked) == tracked; + } + env_->CallVoidMethod(app_->activity->clazz, hostFrameCallback_); + if (env_->ExceptionCheck()) { + env_->ExceptionDescribe(); env_->ExceptionClear(); + hostControl_ = {}; + return; + } + if (hostControl_.version != DROIDDECK_XR_HOST_VERSION) { hostControl_ = {}; return; } + for (int hand = 0; hand < 2; hand++) { + const auto &control = hostControl_.hands[hand]; + if (control.mask & DROIDDECK_XR_HOST_MASK_INPUT) { + inputs_[hand].trigger = 0; inputs_[hand].squeeze = 0; + inputs_[hand].stick[0] = inputs_[hand].stick[1] = 0; + inputs_[hand].buttons = 0; + } + const auto &pulse = control.haptic; + if (pulse.id == hostPulse_[hand]) continue; + hostPulse_[hand] = pulse.id; + if (state_ != XR_SESSION_STATE_FOCUSED || !handActive_[hand] + || pulse.duration_ns < 1000000 || pulse.duration_ns > 1000000000 + || !std::isfinite(pulse.amplitude) || pulse.amplitude < 0 || pulse.amplitude > 1 + || !std::isfinite(pulse.frequency) || pulse.frequency < 0) continue; + XrHapticActionInfo info{XR_TYPE_HAPTIC_ACTION_INFO}; info.action = vibration_; info.subactionPath = hands_[hand]; + XrHapticVibration vibration{XR_TYPE_HAPTIC_VIBRATION}; + vibration.duration = pulse.duration_ns; vibration.amplitude = pulse.amplitude; vibration.frequency = pulse.frequency; + check(xrApplyHapticFeedback(session_, &info, reinterpret_cast(&vibration)), "host haptics"); } } @@ -749,11 +1027,17 @@ private: munmap(tracking_, sizeof(DroidDeckXrTracking)); } if (haptics_) munmap(haptics_, sizeof(DroidDeckXrHaptics)); + g_runtime = nullptr; + hostBuffers_ = false; if (display_ != EGL_NO_DISPLAY && context_ != EGL_NO_CONTEXT) { glDeleteFramebuffers(1, &framebuffer_); glDeleteVertexArrays(1, &vertexArray_); glDeleteTextures(1, &cpuTexture_); glDeleteProgram(sourceProgram_); + glDeleteRenderbuffers(2, overlayDepth_); + overlay_.destroy(); } + if (env_) for (int index = 0; index < DROIDDECK_XR_HOST_LAYERS; index++) destroyLayer(env_, index); for (auto &eye : eyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain); + for (auto &eye : overlayEyes_) if (eye.swapchain) xrDestroySwapchain(eye.swapchain); for (auto space : handSpaces_) if (space) xrDestroySpace(space); if (view_) xrDestroySpace(view_); if (world_) xrDestroySpace(world_); if (session_) xrDestroySession(session_); @@ -769,6 +1053,26 @@ private: } }; +extern "C" JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeCreateLayer(JNIEnv *env, jobject, jint width, jint height) { + return g_runtime ? g_runtime->createLayer(env, width, height) : -1; +} + +extern "C" JNIEXPORT jobject JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeLayerSurface(JNIEnv *env, jobject, jint index) { + return g_runtime ? g_runtime->layerSurface(env, index) : nullptr; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeDestroyLayer(JNIEnv *env, jobject, jint index) { + if (g_runtime) g_runtime->destroyLayer(env, index); +} + +extern "C" JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_QuestXrActivity_nativeSetOrbImage(JNIEnv *env, jobject, jobject bitmap) { + if (g_runtime) g_runtime->setOrbImage(env, bitmap); +} + void android_main(android_app *app) { QuestXR runtime(app); try { runtime.run(); } diff --git a/app/src/main/cpp/questxr/xr_host.h b/app/src/main/cpp/questxr/xr_host.h new file mode 100644 index 0000000000..9f08c32537 --- /dev/null +++ b/app/src/main/cpp/questxr/xr_host.h @@ -0,0 +1,91 @@ +#pragma once +#include +#include +#include "xr_tracking.h" + +// Shared with com.droiddeck.launcher.session.xr.XrHost, which reads and writes these through direct +// ByteBuffers by fixed offset: any layout change must bump the version and update both sides. +#define DROIDDECK_XR_HOST_VERSION 1u +#define DROIDDECK_XR_HOST_LAYERS 6 + +#define DROIDDECK_XR_HOST_SURFACE_SWAPCHAIN (1u << 0) +#define DROIDDECK_XR_HOST_FOCUSED (1u << 1) + +#define DROIDDECK_XR_HOST_MASK_INPUT (1u << 0) + +#define DROIDDECK_XR_HOST_LAYER_ALPHA (1u << 0) +#define DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED (1u << 1) + +struct DroidDeckXrHostHand { + DroidDeckXrPose grip; + DroidDeckXrPose aim; + float trigger, squeeze, stick[2]; + uint32_t buttons, active; + uint32_t reserved[2]; +}; + +struct DroidDeckXrHostState { + uint32_t version, session_state, flags, reserved0; + int64_t frame, display_time_ns; + DroidDeckXrPose head; + DroidDeckXrHostHand hands[2]; + uint32_t reserved[8]; +}; + +struct DroidDeckXrHostHaptic { + uint64_t id; + int64_t duration_ns; + float amplitude, frequency; +}; + +struct DroidDeckXrHostHandControl { + uint32_t mask; + float laser; + DroidDeckXrHostHaptic haptic; + uint32_t reserved[2]; +}; + +struct DroidDeckXrHostOrb { + uint32_t visible; + float progress, burst, radius; + DroidDeckXrPose pose; +}; + +struct DroidDeckXrHostLayer { + int32_t id; + uint32_t visible, flags; + int32_t order; + DroidDeckXrPose pose; + float width, height; + uint32_t reserved[2]; +}; + +struct DroidDeckXrHostControl { + uint32_t version, reserved0; + DroidDeckXrHostHandControl hands[2]; + DroidDeckXrHostOrb orb; + DroidDeckXrHostLayer layers[DROIDDECK_XR_HOST_LAYERS]; + uint32_t reserved[8]; +}; + +static_assert(sizeof(DroidDeckXrHostHand) == 96, "XR host hand layout"); +static_assert(offsetof(DroidDeckXrHostHand, aim) == 32 && offsetof(DroidDeckXrHostHand, trigger) == 64 && + offsetof(DroidDeckXrHostHand, stick) == 72 && offsetof(DroidDeckXrHostHand, buttons) == 80 && + offsetof(DroidDeckXrHostHand, active) == 84, "XR host hand layout"); +static_assert(offsetof(DroidDeckXrHostState, flags) == 8 && offsetof(DroidDeckXrHostState, frame) == 16 && + offsetof(DroidDeckXrHostState, head) == 32, "XR host state layout"); +static_assert(offsetof(DroidDeckXrHostHandControl, laser) == 4 && offsetof(DroidDeckXrHostHandControl, haptic) == 8, + "XR host hand control layout"); +static_assert(offsetof(DroidDeckXrHostHaptic, duration_ns) == 8 && offsetof(DroidDeckXrHostHaptic, amplitude) == 16, + "XR host haptic layout"); +static_assert(offsetof(DroidDeckXrHostOrb, progress) == 4 && offsetof(DroidDeckXrHostOrb, pose) == 16, "XR host orb layout"); +static_assert(offsetof(DroidDeckXrHostLayer, order) == 12 && offsetof(DroidDeckXrHostLayer, pose) == 16 && + offsetof(DroidDeckXrHostLayer, width) == 48, "XR host layer layout"); +static_assert(sizeof(DroidDeckXrHostState) == 288, "XR host state layout"); +static_assert(offsetof(DroidDeckXrHostState, hands) == 64, "XR host state layout"); +static_assert(sizeof(DroidDeckXrHostHandControl) == 40, "XR host hand control layout"); +static_assert(sizeof(DroidDeckXrHostOrb) == 48, "XR host orb layout"); +static_assert(sizeof(DroidDeckXrHostLayer) == 64, "XR host layer layout"); +static_assert(offsetof(DroidDeckXrHostControl, orb) == 88, "XR host control layout"); +static_assert(offsetof(DroidDeckXrHostControl, layers) == 136, "XR host control layout"); +static_assert(sizeof(DroidDeckXrHostControl) == 552, "XR host control layout"); diff --git a/app/src/main/cpp/questxr/xr_overlay.h b/app/src/main/cpp/questxr/xr_overlay.h new file mode 100644 index 0000000000..5078e27b16 --- /dev/null +++ b/app/src/main/cpp/questxr/xr_overlay.h @@ -0,0 +1,229 @@ +#pragma once +#include +#include +#include +#include +#include +#include "xr_host.h" + +struct XrVec3 { float x, y, z; }; + +static inline XrVec3 xrv(float x, float y, float z) { return {x, y, z}; } +static inline XrVec3 operator+(XrVec3 a, XrVec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; } +static inline XrVec3 operator-(XrVec3 a, XrVec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; } +static inline XrVec3 operator*(XrVec3 a, float s) { return {a.x * s, a.y * s, a.z * s}; } +static inline float dot(XrVec3 a, XrVec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } +static inline XrVec3 cross(XrVec3 a, XrVec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; } +static inline XrVec3 normalized(XrVec3 a) { + float length = std::sqrt(dot(a, a)); + return length > 1e-6f ? a * (1.f / length) : xrv(0, 0, 0); +} + +static inline XrVec3 rotate(const float q[4], XrVec3 v) { + XrVec3 u{q[0], q[1], q[2]}; + float s = q[3]; + return u * (2.f * dot(u, v)) + v * (s * s - dot(u, u)) + cross(u, v) * (2.f * s); +} + +class XrOverlay { +public: + void initialize() { + GLuint vertex = compile(GL_VERTEX_SHADER, + "#version 300 es\nlayout(location=0) in vec3 position; layout(location=1) in vec2 coordinate;" + "uniform mat4 viewProjection; out vec2 uv;" + "void main(){uv=coordinate;gl_Position=viewProjection*vec4(position,1.0);}"); + GLuint fragment = compile(GL_FRAGMENT_SHADER, + "#version 300 es\nprecision highp float; in vec2 uv; uniform int mode; uniform float progress, burst, time;" + "uniform vec3 color; uniform sampler2D logo; uniform int hasLogo; out vec4 outputColor;" + "void main(){" + " if(mode==0){float across=1.0-abs(uv.y); float a=smoothstep(0.0,0.7,across)*mix(0.95,0.35,uv.x);" + " outputColor=vec4(color*a,a);return;}" + " if(mode==1){float r=length(uv); float a=1.0-smoothstep(0.55,1.0,r); outputColor=vec4(vec3(1.0)*a,a);return;}" + " float r=length(uv); vec3 c=vec3(0.0); float a=0.0;" + " float pulse=0.5+0.5*sin(time*6.0);" + " float glow=exp(-pow(max(r-0.45,0.0)*6.0,2.0))*(0.25+0.2*pulse)*step(0.5,r); c+=color*glow; a=max(a,glow*0.7);" + " if(hasLogo==1&&r<0.52){vec4 l=texture(logo,vec2(0.5+uv.x/1.04,0.5-uv.y/1.04)); c=c*(1.0-l.a)+l.rgb; a=a*(1.0-l.a)+l.a;}" + " else if(r<0.5){float core=1.0-smoothstep(0.46,0.5,r); c+=color*core; a=max(a,core);}" + " float angle=atan(uv.x,uv.y); float sweep=(angle<0.0?angle+6.2831853:angle)/6.2831853;" + " float band=1.0-smoothstep(0.0,0.03,abs(r-0.64));" + " float track=band*0.25; float fill=band*step(sweep,progress);" + " c+=vec3(1.0)*track+color*fill*1.4; a=max(a,max(track,fill));" + " if(burst>0.0){float ring=(1.0-smoothstep(0.0,0.06,abs(r-(0.64+burst*0.3))))*(1.0-burst); c+=color*ring*2.0; a=max(a,ring);}" + " a=clamp(a,0.0,1.0); outputColor=vec4(c*a,a);" + "}"); + program_ = glCreateProgram(); + glAttachShader(program_, vertex); glAttachShader(program_, fragment); + glLinkProgram(program_); glDeleteShader(vertex); glDeleteShader(fragment); + GLint linked = 0; glGetProgramiv(program_, GL_LINK_STATUS, &linked); + if (!linked) throw std::runtime_error("Overlay shader link failed"); + viewProjection_ = glGetUniformLocation(program_, "viewProjection"); + mode_ = glGetUniformLocation(program_, "mode"); + progress_ = glGetUniformLocation(program_, "progress"); + burst_ = glGetUniformLocation(program_, "burst"); + time_ = glGetUniformLocation(program_, "time"); + color_ = glGetUniformLocation(program_, "color"); + logoSampler_ = glGetUniformLocation(program_, "logo"); + hasLogo_ = glGetUniformLocation(program_, "hasLogo"); + glGenVertexArrays(1, &vertexArray_); + glGenBuffers(1, &buffer_); + glBindVertexArray(vertexArray_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_); + glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 5 * 6, nullptr, GL_DYNAMIC_DRAW); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, nullptr); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, reinterpret_cast(sizeof(float) * 3)); + glBindVertexArray(0); + } + + /** [pixels] are premultiplied RGBA rows, top row first, as an Android ARGB_8888 bitmap holds them. */ + void setLogo(const void *pixels, int width, int height, int stride) { + if (!logo_) glGenTextures(1, &logo_); + glBindTexture(GL_TEXTURE_2D, logo_); + glPixelStorei(GL_UNPACK_ROW_LENGTH, stride / 4); + glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glGenerateMipmap(GL_TEXTURE_2D); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + + void destroy() { + if (logo_) glDeleteTextures(1, &logo_); + logo_ = 0; + if (program_) glDeleteProgram(program_); + if (buffer_) glDeleteBuffers(1, &buffer_); + if (vertexArray_) glDeleteVertexArrays(1, &vertexArray_); + program_ = buffer_ = vertexArray_ = 0; + } + + static bool active(const DroidDeckXrHostControl &control) { + return control.orb.visible || control.hands[0].laser > 0.f || control.hands[1].laser > 0.f; + } + + void draw(const XrPosef &eye, const XrFovf &fov, const DroidDeckXrHostControl &control, + const DroidDeckXrHostState &state, float seconds) { + if (!active(control)) return; + float matrix[16]; + viewProjectionOf(eye, fov, matrix); + const float eyeOrientation[4] = {eye.orientation.x, eye.orientation.y, eye.orientation.z, eye.orientation.w}; + const XrVec3 eyePosition{eye.position.x, eye.position.y, eye.position.z}; + glUseProgram(program_); + glUniformMatrix4fv(viewProjection_, 1, GL_FALSE, matrix); + glUniform3f(color_, 0.12f, 0.62f, 1.0f); + glUniform1f(time_, seconds); + glBindVertexArray(vertexArray_); + glBindBuffer(GL_ARRAY_BUFFER, buffer_); + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_LEQUAL); + glDepthMask(GL_TRUE); + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + glDisable(GL_BLEND); + glUniform1i(mode_, 0); + for (const auto &layer : control.layers) { + if (!layer.visible || !(layer.width > 0.f) || !(layer.height > 0.f)) continue; + if (layer.flags & DROIDDECK_XR_HOST_LAYER_HEAD_LOCKED) continue; + XrVec3 center{layer.pose.position[0], layer.pose.position[1], layer.pose.position[2]}; + XrVec3 right = rotate(layer.pose.orientation, xrv(layer.width / 2.f, 0, 0)); + XrVec3 up = rotate(layer.pose.orientation, xrv(0, layer.height / 2.f, 0)); + quad(center - right - up, center + right - up, center - right + up, center + right + up, 0.f, 1.f); + } + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + glDepthMask(GL_FALSE); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + for (int hand = 0; hand < 2; hand++) { + float length = control.hands[hand].laser; + if (!(length > 0.f) || !state.hands[hand].active) continue; + const auto &aim = state.hands[hand].aim; + XrVec3 start{aim.position[0], aim.position[1], aim.position[2]}; + XrVec3 direction = normalized(rotate(aim.orientation, xrv(0, 0, -1))); + XrVec3 end = start + direction * std::max(length - 0.004f, 0.f); + XrVec3 side = normalized(cross(direction, eyePosition - start)) * 0.0022f; + glUniform1i(mode_, 0); + quad(start - side, start + side, end - side, end + side, 0.f, 1.f); + XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * 0.007f; + XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * 0.007f; + glUniform1i(mode_, 1); + billboard(end + normalized(eyePosition - end) * 0.008f, right, up); + } + if (control.orb.visible) { + const auto &pose = control.orb.pose; + XrVec3 center{pose.position[0], pose.position[1], pose.position[2]}; + float size = control.orb.radius * 1.25f; + XrVec3 right = rotate(eyeOrientation, xrv(1, 0, 0)) * size; + XrVec3 up = rotate(eyeOrientation, xrv(0, 1, 0)) * size; + glUniform1i(mode_, 2); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, logo_); + glUniform1i(logoSampler_, 0); + glUniform1i(hasLogo_, logo_ ? 1 : 0); + glUniform1f(progress_, control.orb.progress); + glUniform1f(burst_, control.orb.burst); + billboard(center, right, up); + } + glBindVertexArray(0); + glDisable(GL_BLEND); + glDisable(GL_DEPTH_TEST); + glDepthMask(GL_TRUE); + } + +private: + GLuint program_ = 0, buffer_ = 0, vertexArray_ = 0, logo_ = 0; + GLint viewProjection_ = -1, mode_ = -1, progress_ = -1, burst_ = -1, time_ = -1, color_ = -1; + GLint logoSampler_ = -1, hasLogo_ = -1; + + static GLuint compile(GLenum type, const char *text) { + GLuint handle = glCreateShader(type); + glShaderSource(handle, 1, &text, nullptr); glCompileShader(handle); + GLint success = 0; glGetShaderiv(handle, GL_COMPILE_STATUS, &success); + if (!success) { glDeleteShader(handle); throw std::runtime_error("Overlay shader compile failed"); } + return handle; + } + + void billboard(XrVec3 center, XrVec3 right, XrVec3 up) { + quadUv(center - right - up, center + right - up, center - right + up, center + right + up); + } + + void quad(XrVec3 a0, XrVec3 a1, XrVec3 b0, XrVec3 b1, float from, float to) { + const float vertices[] = { + a0.x, a0.y, a0.z, from, -1, a1.x, a1.y, a1.z, from, 1, b0.x, b0.y, b0.z, to, -1, + b0.x, b0.y, b0.z, to, -1, a1.x, a1.y, a1.z, from, 1, b1.x, b1.y, b1.z, to, 1}; + glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + + void quadUv(XrVec3 bottomLeft, XrVec3 bottomRight, XrVec3 topLeft, XrVec3 topRight) { + const float vertices[] = { + bottomLeft.x, bottomLeft.y, bottomLeft.z, -1, -1, bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, + topLeft.x, topLeft.y, topLeft.z, -1, 1, topLeft.x, topLeft.y, topLeft.z, -1, 1, + bottomRight.x, bottomRight.y, bottomRight.z, 1, -1, topRight.x, topRight.y, topRight.z, 1, 1}; + glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + + static void viewProjectionOf(const XrPosef &pose, const XrFovf &fov, float out[16]) { + const float q[4] = {pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w}; + XrVec3 xAxis = rotate(q, xrv(1, 0, 0)), yAxis = rotate(q, xrv(0, 1, 0)), zAxis = rotate(q, xrv(0, 0, 1)); + XrVec3 position{pose.position.x, pose.position.y, pose.position.z}; + float view[16] = { + xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, + -dot(xAxis, position), -dot(yAxis, position), -dot(zAxis, position), 1}; + const float nearZ = 0.05f, farZ = 100.f; + float left = std::tan(fov.angleLeft), right = std::tan(fov.angleRight); + float up = std::tan(fov.angleUp), down = std::tan(fov.angleDown); + float width = right - left, height = up - down; + float projection[16] = { + 2.f / width, 0, 0, 0, 0, 2.f / height, 0, 0, + (right + left) / width, (up + down) / height, -(farZ + nearZ) / (farZ - nearZ), -1, + 0, 0, -2.f * farZ * nearZ / (farZ - nearZ), 0}; + for (int column = 0; column < 4; column++) + for (int row = 0; row < 4; row++) { + float sum = 0; + for (int k = 0; k < 4; k++) sum += projection[k * 4 + row] * view[column * 4 + k]; + out[column * 4 + row] = sum; + } + } +}; diff --git a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt index 5bde3ef872..9a6db04cc5 100644 --- a/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/QuestXrActivity.kt @@ -4,25 +4,32 @@ import android.app.NativeActivity import android.os.Bundle import android.os.SystemClock import android.util.Log +import android.view.Surface import android.widget.Toast import com.droiddeck.launcher.gpu.SteamVr import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.session.xr.XrLayerSource +import com.droiddeck.launcher.session.xr.XrPanels import com.droiddeck.launcher.wayland.CompositorHost import com.droiddeck.launcher.wayland.WaylandCompositor -class QuestXrActivity : NativeActivity() { +class QuestXrActivity : NativeActivity(), XrLayerSource { private var steamVrStarted = false @Volatile private var closing = false @Volatile private var steamVrStatus = SteamVr.Status.UNAVAILABLE private var sessionId: String? = null override fun onCreate(savedInstanceState: Bundle?) { + // NativeActivity opens the library itself, but the layer host's JNI methods resolve only + // through a System.loadLibrary. + System.loadLibrary("droiddeckxr") sessionId = SessionState.sessionId SessionService.setXrActivityVisible(this, true) super.onCreate(savedInstanceState) } fun onXrActive(active: Boolean) { + XrPanels.setDrawing(active) if (active) { check(CompositorHost.isStarted) { "DroidDeck compositor is not running" } SessionService.resume(this) @@ -100,8 +107,30 @@ class QuestXrActivity : NativeActivity() { fun onXrStatus(): Int = steamVrStatus.ordinal + fun onXrHostBuffers(state: java.nio.ByteBuffer, control: java.nio.ByteBuffer) { + runOnUiThread { if (!closing) XrPanels.attach(this, state, control) } + } + + fun onXrHostFrame() = XrPanels.frame() + + override val context: android.content.Context get() = this + override fun createLayer(width: Int, height: Int) = nativeCreateLayer(width, height) + override fun layerSurface(id: Int) = nativeLayerSurface(id) + override fun destroyLayer(id: Int) = nativeDestroyLayer(id) + override fun setOrbImage(image: android.graphics.Bitmap) = nativeSetOrbImage(image) + override fun leave() { + closing = true + finish() + } + + private external fun nativeCreateLayer(width: Int, height: Int): Int + private external fun nativeLayerSurface(id: Int): Surface? + private external fun nativeDestroyLayer(id: Int) + private external fun nativeSetOrbImage(image: android.graphics.Bitmap) + override fun onDestroy() { closing = true + XrPanels.detach() SessionService.setXrActivityVisible(this, false) super.onDestroy() } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 8c92f5cf5f..d94320a5e2 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -162,7 +162,8 @@ import kotlin.math.abs private const val SCREEN_EFFECTS_TARGET_AUTO = "auto" private const val SCREEN_EFFECTS_TARGET_GLOBAL = "global" -class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost { +class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droiddeck.launcher.ui.AgentPetHost, + com.droiddeck.launcher.session.xr.XrMenuHost { override fun attachBaseContext(newBase: android.content.Context) { super.attachBaseContext(newBase) com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) @@ -546,6 +547,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerOpenState by mutableStateOf(false) private var typingReturnMode: SecondScreenMode? = null private var drawerDocked by mutableStateOf(false) + /** The menu is open as a floating panel in the immersive Quest view instead of over this window. */ + private var drawerXr by mutableStateOf(false) private var drawerPinned by mutableStateOf(false) private var drawerLayerOpen = false private var drawerBackRequests by mutableIntStateOf(0) @@ -563,9 +566,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawerPinned = false if (value) { releaseHeldKeys() - drawerDocked = dockDrawer() && openDockedMenu() + drawerXr = com.droiddeck.launcher.session.xr.XrPanels.showMenu() + drawerDocked = !drawerXr && dockDrawer() && openDockedMenu() } drawerOpenState = value + if (!value && drawerXr) { + drawerXr = false + com.droiddeck.launcher.session.xr.XrPanels.hideMenu() + } if (!value && drawerDocked) closeDockedMenu() } private val dockedMenuIdle: Boolean get() = com.droiddeck.launcher.input.DualScreen.menuIdleOnBottom(drawerOpen, drawerDocked, drawerPinned, dockedMenuController) @@ -850,6 +858,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + com.droiddeck.launcher.session.xr.XrPanels.setMenuHost(this) AgentGuest.readyListener = agentReadyListener com.droiddeck.launcher.agent.AgentAttachments.gameFrame = gameFrame if (com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.isRemoving() || @@ -1193,7 +1202,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val cursorHidden = cursorHiddenByUi() androidx.compose.runtime.SideEffect { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, - (drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING) + (drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && !drawerXr && steamVrStatus != SteamVr.Status.RUNNING) } androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) } androidx.compose.runtime.DisposableEffect(Unit) { @@ -1272,6 +1281,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!drawerOpen && !pcKeyboardOpen && !loading.visible) { com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true } if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true } + if (com.droiddeck.launcher.session.QuestExperimental.isSupported()) + com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() } } if (loading.visible) LoadingOverlay( loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended, @@ -1475,11 +1486,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() }, onClose = { pcKeyboardOpen = false }, ) - if (!drawerDocked) SessionMenu( + if (!drawerDocked && !drawerXr) SessionMenu( docked = false, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget, ) + if (drawerOpen && !drawerDocked && !drawerXr && com.droiddeck.launcher.session.QuestExperimental.isSupported()) + com.droiddeck.launcher.ui.DrawerEdgeSwipe { onBackPressedDispatcher.onBackPressed() } LaunchedEffect(achievementsOpen) { if (achievementsOpen) { releasePads() @@ -1528,6 +1541,70 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } + @androidx.compose.runtime.Composable + override fun XrMenuContent() { + val activeEffectsProfileId = currentScreenEffectsProfileId() + val effectsEditorTarget = if (drawerOpen) screenEffectsTarget else null + val effectsEditorProfileId = activeEffectsProfileId.takeIf { effectsEditorTarget == SCREEN_EFFECTS_TARGET_AUTO } + androidx.compose.runtime.LaunchedEffect(effectsEditorTarget, effectsEditorProfileId) { + when (effectsEditorTarget) { + SCREEN_EFFECTS_TARGET_AUTO -> syncActiveScreenEffectsProfile() + null -> Unit + else -> syncScreenEffectsTarget(effectsEditorTarget) + } + } + SessionMenu(docked = true, effectsEditorProfileId = effectsEditorProfileId, effectsEditorTarget = effectsEditorTarget) + } + + override fun xrSetMenuOpen(open: Boolean) { + if (open != drawerOpen) drawerOpen = open + } + + /** + * In the immersive Quest view, Stop takes the user back to this window with the session still + * running, and Stop SteamVR leaves at once instead of after the stop is noticed. + */ + private fun leaveXrMenu() { + if (!drawerXr) return + drawerOpen = false + com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive() + } + + override fun xrMenuBack() { + if (drawerLayerOpen) drawerBackRequests++ else drawerOpen = false + } + + override fun xrSendKey(code: Int, down: Boolean) { + if (CompositorHost.isStarted) sendGuestKey(code, down, 32) + } + + override fun xrTypeText(text: String) = xrKeys.type(text) + + override fun xrImmersiveChanged(active: Boolean) { + if (active) { + if (immersiveFlatSize == null) immersiveFlatSize = SessionState.outputSize + resizeOutputForWindow(surfaceW, surfaceH) + return + } + val flat = immersiveFlatSize + immersiveFlatSize = null + if (windowOutputSize(surfaceW, surfaceH) == null && flat != null) applyOutputSize(flat) + else resizeOutputForWindow(surfaceW, surfaceH) + } + + /** The output's size when the immersive view opened; this window may have no surface while it is up. */ + private var immersiveFlatSize: Pair? = null + + override fun xrTapKey(keyCode: Int) = xrKeys.tap(keyCode) + + /** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */ + private val xrKeys by lazy { + com.droiddeck.launcher.input.KeyboardHost(this) { event -> + CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) && + com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) } + } + } + @androidx.compose.runtime.Composable private fun SessionMenu( docked: Boolean, @@ -1906,9 +1983,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.suspendPolicyChanged(this@SessionActivity) }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, - onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true }, + onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true }, onInputSelection = { releasePads(); refreshInputProfile() }, - onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true }, + onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true }, touchActive = drawerTouchMode(), directHoldBehavior = directHoldBehavior, onDirectHoldBehavior = { value -> @@ -2005,18 +2082,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController, onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) }, onShareLogs = { drawerOpen = false; shareCurrentSessionLogs() }, - onStop = { drawerOpen = false; SessionService.stop(this@SessionActivity); finish() }, + onStop = { + if (drawerXr) leaveXrMenu() else { + drawerOpen = false + SessionService.stop(this@SessionActivity) + finish() + } + }, onStopFrom = { onScreen -> - drawerOpen = false - if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) { - if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() } - } else { - val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) } - quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat()) + if (drawerXr) leaveXrMenu() else { + drawerOpen = false + if (onScreen == null || com.droiddeck.launcher.ui.Motion.scale == 0f || quitFrom != null) { + if (quitFrom == null) { SessionService.stop(this@SessionActivity); finish() } + } else { + val at = IntArray(2).also { sessionOverlay.getLocationOnScreen(it) } + quitFrom = onScreen.translate(-at[0].toFloat(), -at[1].toFloat()) + } } }, onClose = { drawerOpen = false }, - onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null, + onDismissScreen = if (docked && !drawerXr) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null, components = drawerComponents, onComponentsRefresh = { refreshDrawerComponents() @@ -2094,7 +2179,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde }) else null, onKeyboard = { togglePrimaryKeyboard() }, onSessionMenu = { drawerOpen = true }, - onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null, + onStopSteamVr = if (vr) ({ leaveXrMenu(); steamVrAction("stop") }) else null, brightness = glasses.brightness, brightnessMax = glasses.brightnessMax, onBrightness = if (glasses.canControl && glasses.hardwareControls) Glasses::setBrightness else null, @@ -2133,6 +2218,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun togglePcKeyboard() { drawerOpen = false + if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = true)) return hidePrimaryKeyboard() onScreenControls?.releaseAll() bottomInputControls?.releaseAll() @@ -2142,12 +2228,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun showPrimaryKeyboard() { pendingFieldKeyboard = false fieldKeyboardOnPrimary = false + if (com.droiddeck.launcher.session.xr.XrPanels.showGameKeyboard(pc = false)) return keyboard?.show() } private fun togglePrimaryKeyboard() { pendingFieldKeyboard = false fieldKeyboardOnPrimary = false + if (com.droiddeck.launcher.session.xr.XrPanels.toggleGameKeyboard(pc = false)) return keyboard?.toggle() } @@ -3045,6 +3133,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun windowOutputSize(width: Int, height: Int): Pair? { + if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) { + val flat = immersiveFlatSize ?: SessionState.outputSize + return if (steamScreenShown()) vrOutputSize(flat) else flat + } if (width <= 0 || height <= 0 || isInPictureInPictureMode) return null if (bottomGame != null) return when { SessionState.followScreen -> @@ -3058,9 +3150,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde else if (glassesScreen == null) outputSize() else null } + /** These editors draw in this window, which the immersive view hides, so they open after leaving it. */ + private fun leaveImmersiveForDialog() { + if (com.droiddeck.launcher.session.xr.XrPanels.immersiveActive) com.droiddeck.launcher.session.xr.XrPanels.leaveImmersive() + } + + /** Steam's own screen is up with no game holding a window; with no focus report, a game may be running. */ + private fun steamScreenShown(): Boolean { + if (SessionState.mode != SessionService.MODE_STEAM) return false + val focus = com.droiddeck.launcher.agent.AgentGuest.focus(this) ?: return false + return com.droiddeck.launcher.session.xr.XrSteamScreen.shown( + focus.takeUnless { it.isNull("focusedApp") }?.optLong("focusedApp"), + focus.optJSONArray("focusableApps")?.let { list -> (0 until list.length()).map { list.optLong(it) } }, + ) + } + + /** + * SteamVR shows Steam's own screen as its floating Steam window, so in the headset that screen is drawn + * tall enough for the window to stay sharp. A flat game keeps the flat size, so the output keeps it + * while one is running. + */ + private fun vrOutputSize(flat: Pair): Pair { + if (flat.second >= VR_OUTPUT_HEIGHT) return flat + val width = (flat.first.toLong() * VR_OUTPUT_HEIGHT / flat.second.coerceAtLeast(1)).toInt() and 1.inv() + return width to VR_OUTPUT_HEIGHT + } + private fun resizeOutputForWindow(width: Int, height: Int) { + applyOutputSize(windowOutputSize(width, height) ?: return) + } + + private fun applyOutputSize(size: Pair) { if (!CompositorHost.isStarted) return - val size = windowOutputSize(width, height) ?: return if (size == SessionState.outputSize) return Log.i(TAG, "output resized: ${SessionState.outputSize.first}x${SessionState.outputSize.second} -> ${size.first}x${size.second}") SessionState.outputSize = size @@ -7150,6 +7271,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { + com.droiddeck.launcher.session.xr.XrPanels.clearMenuHost(this) + if (drawerXr) com.droiddeck.launcher.session.xr.XrPanels.hideMenu() uiHandler.removeCallbacks(panelHeldCheck) uiHandler.removeCallbacks(panelHeldRetry) synchronized(frameGenGlobalLock) { @@ -7274,6 +7397,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde const val EXTRA_RETURN_HOME = "returnHome" private const val BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT" private const val REQUEST_BLUETOOTH = 31 + private const val VR_OUTPUT_HEIGHT = 1080 const val EXTRA_LINK_TASK = "linkTask" const val EXTRA_STEAMVR = "steamVr" const val EXTRA_PLAYED_GAME = "com.droiddeck.launcher.PLAYED_GAME" diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt new file mode 100644 index 0000000000..02f1a84e86 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentChatActivity.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.agent + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.core.AppUiPrefs +import com.droiddeck.launcher.ui.AgentPage +import com.droiddeck.launcher.ui.DroidDeckTheme + +/** + * The agent's chat in a window of its own, for Quest's flat mode: opened in its own task, it is a + * separate Horizon panel the user can move, resize and close like any other. + */ +class AgentChatActivity : ComponentActivity() { + override fun attachBaseContext(newBase: Context) { + super.attachBaseContext(newBase) + com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + DroidDeckTheme(appScale = AppUiPrefs.scale(this)) { + AgentPage( + Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(horizontal = 12.dp, vertical = 6.dp), + visible = true, startTyping = AgentHost.entries.isEmpty(), + ) + } + } + } + + companion object { + fun open(context: Context) { + context.startActivity( + Intent(context, AgentChatActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT), + ) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt index abe8abb3a3..c1ad86bfc3 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt @@ -19,7 +19,7 @@ import java.util.UUID object AgentGuest { private val main by lazy { Handler(Looper.getMainLooper()) } var focusRevision by mutableIntStateOf(0) - private set + @androidx.annotation.VisibleForTesting internal set var steamKeyboard by mutableStateOf(false) private set var desktopTextField by mutableStateOf(false) diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt new file mode 100644 index 0000000000..cbd66f1964 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrGesture.kt @@ -0,0 +1,68 @@ +package com.droiddeck.launcher.session.xr + +/** + * The menu gesture: both controllers held together. It arms when the two aim points come within + * [ARM_METRES], cancels once they part beyond [CANCEL_METRES], and fires after [HOLD_MS] held. + * It needs both controllers apart again before it can arm a second time. + */ +internal class XrGesture { + enum class Phase { IDLE, ARMING, FIRED } + + var phase = Phase.IDLE + private set + var progress = 0f + private set + var midpoint = Vec3.ZERO + private set + private var startedMs = 0L + private var needsRelease = false + + /** Returns true on the frame the gesture completes. */ + fun update(left: XrHand, right: XrHand, nowMs: Long): Boolean { + if (!left.active || !right.active) { + reset(release = false) + return false + } + val a = left.aim.position + val b = right.aim.position + val distance = (a - b).length + midpoint = Vec3.lerp(a, b, 0.5f) + if (needsRelease) { + if (distance > CANCEL_METRES) needsRelease = false + phase = Phase.IDLE + progress = 0f + return false + } + when (phase) { + Phase.IDLE, Phase.FIRED -> if (distance < ARM_METRES) { + phase = Phase.ARMING + startedMs = nowMs + progress = 0f + } + Phase.ARMING -> if (distance > CANCEL_METRES) { + phase = Phase.IDLE + progress = 0f + } else { + progress = ((nowMs - startedMs).toFloat() / HOLD_MS).coerceIn(0f, 1f) + if (progress >= 1f) { + phase = Phase.FIRED + needsRelease = true + return true + } + } + } + return false + } + + fun reset(release: Boolean) { + phase = Phase.IDLE + progress = 0f + if (release) needsRelease = true + } + + companion object { + const val ARM_METRES = 0.09f + const val CANCEL_METRES = 0.14f + const val HOLD_MS = 1500L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt new file mode 100644 index 0000000000..48424cccbf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrHost.kt @@ -0,0 +1,160 @@ +package com.droiddeck.launcher.session.xr + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/** + * Typed access to the two buffers quest_xr.cpp shares each frame (app/src/main/cpp/questxr/xr_host.h). + * The offsets here must match that header. + */ +internal object XrHostLayout { + const val VERSION = 1 + const val LAYERS = 6 + const val STATE_SIZE = 288 + const val CONTROL_SIZE = 552 + const val POSE_SIZE = 32 + const val HAND_SIZE = 96 + const val STATE_HEAD = 32 + const val STATE_HANDS = 64 + const val HAND_GRIP = 0 + const val HAND_AIM = 32 + const val HAND_TRIGGER = 64 + const val HAND_SQUEEZE = 68 + const val HAND_STICK = 72 + const val HAND_BUTTONS = 80 + const val HAND_ACTIVE = 84 + const val CONTROL_HANDS = 8 + const val HAND_CONTROL_SIZE = 40 + const val HAND_CONTROL_MASK = 0 + const val HAND_CONTROL_LASER = 4 + const val HAND_CONTROL_HAPTIC = 8 + const val CONTROL_ORB = 88 + const val CONTROL_LAYERS = 136 + const val LAYER_SIZE = 64 + + const val FLAG_SURFACE_SWAPCHAIN = 1 + const val FLAG_FOCUSED = 2 + const val MASK_INPUT = 1 + const val LAYER_ALPHA = 1 + const val LAYER_HEAD_LOCKED = 2 + + const val SECONDARY_CLICK = 1 shl 2 +} + +internal class XrHand( + val grip: Pose, + val aim: Pose, + val trigger: Float, + val squeeze: Float, + val stickX: Float, + val stickY: Float, + val buttons: Int, + val active: Boolean, +) { + val secondary: Boolean get() = buttons and XrHostLayout.SECONDARY_CLICK != 0 + + companion object { + val IDLE = XrHand(Pose(), Pose(), 0f, 0f, 0f, 0f, 0, false) + } +} + +internal class XrFrame(val flags: Int, val frame: Long, val displayTimeNs: Long, val head: Pose, val hands: List) { + val focused: Boolean get() = flags and XrHostLayout.FLAG_FOCUSED != 0 + val surfaces: Boolean get() = flags and XrHostLayout.FLAG_SURFACE_SWAPCHAIN != 0 +} + +internal class XrHaptic(val durationMs: Int, val amplitude: Float, val frequency: Float = 0f) + +internal class XrLayerOut( + val id: Int, + val pose: Pose, + val width: Float, + val height: Float, + val order: Int, + val alpha: Boolean = true, +) + +internal class XrControlOut { + val masks = BooleanArray(2) + val lasers = FloatArray(2) + val haptics = arrayOfNulls(2) + var orb: Orb? = null + val layers = mutableListOf() + + class Orb(val position: Vec3, val radius: Float, val progress: Float, val burst: Float) +} + +internal class XrHost(state: ByteBuffer, control: ByteBuffer) { + private val state = state.order(ByteOrder.nativeOrder()) + private val control = control.order(ByteOrder.nativeOrder()) + private val hapticIds = LongArray(2) + + init { + require(state.capacity() >= XrHostLayout.STATE_SIZE && control.capacity() >= XrHostLayout.CONTROL_SIZE) { "XR host buffers too small" } + } + + fun read(): XrFrame = readFrame(state) + + fun write(out: XrControlOut) = writeControl(control, out, hapticIds) + + companion object { + fun readPose(b: ByteBuffer, at: Int) = Pose( + Quat(b.getFloat(at), b.getFloat(at + 4), b.getFloat(at + 8), b.getFloat(at + 12)), + Vec3(b.getFloat(at + 16), b.getFloat(at + 20), b.getFloat(at + 24)), + ) + + fun writePose(b: ByteBuffer, at: Int, pose: Pose) { + b.putFloat(at, pose.orientation.x); b.putFloat(at + 4, pose.orientation.y) + b.putFloat(at + 8, pose.orientation.z); b.putFloat(at + 12, pose.orientation.w) + b.putFloat(at + 16, pose.position.x); b.putFloat(at + 20, pose.position.y); b.putFloat(at + 24, pose.position.z) + b.putInt(at + 28, 0) + } + + fun readFrame(b: ByteBuffer): XrFrame { + val hands = (0 until 2).map { hand -> + val at = XrHostLayout.STATE_HANDS + hand * XrHostLayout.HAND_SIZE + XrHand( + readPose(b, at + XrHostLayout.HAND_GRIP), readPose(b, at + XrHostLayout.HAND_AIM), + b.getFloat(at + XrHostLayout.HAND_TRIGGER), b.getFloat(at + XrHostLayout.HAND_SQUEEZE), + b.getFloat(at + XrHostLayout.HAND_STICK), b.getFloat(at + XrHostLayout.HAND_STICK + 4), + b.getInt(at + XrHostLayout.HAND_BUTTONS), b.getInt(at + XrHostLayout.HAND_ACTIVE) != 0, + ) + } + return XrFrame(b.getInt(8), b.getLong(16), b.getLong(24), readPose(b, XrHostLayout.STATE_HEAD), hands) + } + + fun writeControl(b: ByteBuffer, out: XrControlOut, hapticIds: LongArray) { + for (i in 0 until XrHostLayout.CONTROL_SIZE step 4) b.putInt(i, 0) + b.putInt(0, XrHostLayout.VERSION) + for (hand in 0 until 2) { + val at = XrHostLayout.CONTROL_HANDS + hand * XrHostLayout.HAND_CONTROL_SIZE + b.putInt(at + XrHostLayout.HAND_CONTROL_MASK, if (out.masks[hand]) XrHostLayout.MASK_INPUT else 0) + b.putFloat(at + XrHostLayout.HAND_CONTROL_LASER, out.lasers[hand]) + out.haptics[hand]?.let { hapticIds[hand]++ } + val haptic = at + XrHostLayout.HAND_CONTROL_HAPTIC + b.putLong(haptic, hapticIds[hand]) + out.haptics[hand]?.let { + b.putLong(haptic + 8, it.durationMs * 1_000_000L) + b.putFloat(haptic + 16, it.amplitude) + b.putFloat(haptic + 20, it.frequency) + } + } + out.orb?.let { orb -> + val at = XrHostLayout.CONTROL_ORB + b.putInt(at, 1) + b.putFloat(at + 4, orb.progress); b.putFloat(at + 8, orb.burst); b.putFloat(at + 12, orb.radius) + writePose(b, at + 16, Pose(position = orb.position)) + } + out.layers.take(XrHostLayout.LAYERS).forEachIndexed { index, layer -> + val at = XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE + b.putInt(at, layer.id) + b.putInt(at + 4, 1) + b.putInt(at + 8, if (layer.alpha) XrHostLayout.LAYER_ALPHA else 0) + b.putInt(at + 12, layer.order) + writePose(b, at + 16, layer.pose) + b.putFloat(at + 48, layer.width); b.putFloat(at + 52, layer.height) + } + for (index in out.layers.size until XrHostLayout.LAYERS) b.putInt(XrHostLayout.CONTROL_LAYERS + index * XrHostLayout.LAYER_SIZE, -1) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt new file mode 100644 index 0000000000..d045a87663 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrInteraction.kt @@ -0,0 +1,303 @@ +package com.droiddeck.launcher.session.xr + +import kotlin.math.PI +import kotlin.math.abs + +/** + * [barButton]: the grab bar has a button at its left end; the menu has its own close button instead. + * [tilt]: how far the panel leans back from upright, in radians, as a keyboard lies on a desk. + */ +internal enum class XrPanelKind( + val key: String, val resizable: Boolean, val chrome: Boolean, val barButton: Boolean = false, val tilt: Float = 0f, +) { + MENU("menu", resizable = true, chrome = true), + PET_HEAD("pet_head", resizable = false, chrome = false), + PET_CHAT("pet_chat", resizable = true, chrome = true, barButton = true), + KEYBOARD("keyboard_desk", resizable = true, chrome = true, barButton = true, tilt = (PI / 4).toFloat()); + + /** Turned towards [head] about the vertical axis, then leant back by [tilt]. */ + fun orient(position: Vec3, head: Vec3): Quat = facing(position, head) * Quat.pitch(-tilt) +} + +/** Where a panel is and how big, in metres; [pixelWidth] and [pixelHeight] are its surface's size. */ +internal class XrPanelState(val kind: XrPanelKind, var pose: Pose, var width: Float, var height: Float) { + var pixelWidth = XrUnits.pixels(width) + var pixelHeight = XrUnits.pixels(height) + /** 0 while it opens or closes from [animationFrom], 1 when it is in place and takes input. */ + var scale = 1f + var animationFrom: Vec3? = null + + val shownPose: Pose get() = animationFrom?.let { Pose(pose.orientation, Vec3.lerp(it, pose.position, scale)) } ?: pose + val interactive: Boolean get() = scale >= 1f + + fun hit(ray: Pose): XrHit? = hitPlane(ray, bounded = true) + + /** Where [ray] meets this panel's plane; [bounded] limits it to the panel itself. */ + fun hitPlane(ray: Pose, bounded: Boolean, plane: Pose = pose, w: Float = width, h: Float = height): XrHit? { + val normal = plane.orientation.rotate(Vec3(0f, 0f, 1f)) + val direction = ray.forward + val denominator = direction dot normal + if (denominator > -1e-4f) return null + val distance = ((plane.position - ray.position) dot normal) / denominator + if (distance <= 0f) return null + val local = plane.toLocal(ray.position + direction * distance) + if (bounded && (abs(local.x) > w / 2f || abs(local.y) > h / 2f)) return null + return XrHit(this, local.x, local.y, distance) + } + + fun u(localX: Float) = (localX / width + 0.5f).coerceIn(0f, 1f) + fun v(localY: Float) = (0.5f - localY / height).coerceIn(0f, 1f) + fun pixelX(localX: Float) = u(localX) * pixelWidth + fun pixelY(localY: Float) = v(localY) * pixelHeight + + /** The grab bar runs along the bottom, as under Quest's own windows, with its button at the left end. */ + fun inBar(hit: XrHit) = kind.chrome && hit.y + 0.5f * height <= XrUnits.BAR_METRES + fun inBarButtons(hit: XrHit) = kind.barButton && inBar(hit) && hit.x + 0.5f * width <= XrUnits.BAR_BUTTONS_METRES + fun inResizeGrip(hit: XrHit) = kind.resizable && + 0.5f * width - hit.x <= XrUnits.GRIP_METRES && hit.y + 0.5f * height <= XrUnits.GRIP_METRES +} + +internal class XrHit(val panel: XrPanelState, val x: Float, val y: Float, val distance: Float) + +internal object XrUnits { + const val DP_PER_METRE = 900f + const val DENSITY = 2f + const val DPI = 320 + const val BAR_METRES = 52f / DP_PER_METRE + const val BAR_BUTTONS_DP = 150f + const val BAR_BUTTONS_METRES = BAR_BUTTONS_DP / DP_PER_METRE + const val GRIP_METRES = 0.05f + const val MIN_METRES = 0.3f + const val MAX_METRES = 1.6f + const val MIN_DISTANCE = 0.4f + const val MAX_DISTANCE = 3f + fun pixels(metres: Float) = (metres * DP_PER_METRE * DENSITY).toInt().coerceAtLeast(16) +} + +internal sealed class XrPointerEvent(val panel: XrPanelState) { + class Down(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel) + class Move(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel) + class Up(panel: XrPanelState, val x: Float, val y: Float, val hand: Int = 0) : XrPointerEvent(panel) + class Cancel(panel: XrPanelState, val hand: Int = 0) : XrPointerEvent(panel) + class Scroll(panel: XrPanelState, val x: Float, val y: Float, val amount: Float) : XrPointerEvent(panel) + class Back(panel: XrPanelState) : XrPointerEvent(panel) + class Click(panel: XrPanelState) : XrPointerEvent(panel) + class Resized(panel: XrPanelState) : XrPointerEvent(panel) + class Moved(panel: XrPanelState) : XrPointerEvent(panel) +} + +internal class XrInteractionOut { + val events = mutableListOf() + val masks = BooleanArray(2) + val lasers = FloatArray(2) + val ticks = BooleanArray(2) + /** Where each controller points on each panel, in its pixels, left hand first; panels with no entry show none. */ + val cursors = mutableMapOf>>() + + fun point(panel: XrPanelState, x: Float, y: Float) { + cursors.getOrPut(panel) { mutableListOf() } += x to y + } +} + +/** + * What the two controllers do to the panels each frame. A controller acts on a panel only while it + * points at one, or while it holds one it picked up, pressed or is resizing; only then is its input + * taken from the game. + */ +internal class XrInteraction { + private sealed class Hold { + object None : Hold() + class Press(val panel: XrPanelState, var x: Float, var y: Float) : Hold() + class Move(val panel: XrPanelState, var offset: Vec3, val byGrip: Boolean) : Hold() + class Resize(val panel: XrPanelState, val plane: Pose, val width: Float, val height: Float, val startX: Float, val startY: Float) : Hold() + class HeadPress(val panel: XrPanelState, val startX: Float, val startY: Float, val offset: Vec3) : Hold() + } + + private val holds = arrayOf(Hold.None, Hold.None) + private val trigger = BooleanArray(2) + private val grip = BooleanArray(2) + private val secondary = BooleanArray(2) + + fun holding(panel: XrPanelState) = holds.any { held(it) === panel } + + private fun held(hold: Hold): XrPanelState? = when (hold) { + is Hold.Press -> hold.panel + is Hold.Move -> hold.panel + is Hold.Resize -> hold.panel + is Hold.HeadPress -> hold.panel + Hold.None -> null + } + + /** Lets go of everything, as when the immersive view goes. A button still held counts only once let go and pressed again. */ + fun reset() { + holds.fill(Hold.None) + trigger.fill(true) + grip.fill(true) + secondary.fill(true) + } + + /** Cancels a press and ends a move or resize where it is, as when the headset loses focus; then [reset]. */ + fun cancel(out: XrInteractionOut) { + for ((hand, hold) in holds.withIndex()) when (hold) { + is Hold.Press -> out.events += XrPointerEvent.Cancel(hold.panel, hand) + is Hold.Move -> out.events += XrPointerEvent.Moved(hold.panel) + is Hold.Resize -> out.events += XrPointerEvent.Resized(hold.panel) + else -> Unit + } + reset() + } + + /** Lets go of [panel], as when it closes. */ + fun release(panel: XrPanelState, out: XrInteractionOut) { + for (hand in 0..1) if (held(holds[hand]) === panel) { + if (holds[hand] is Hold.Press) out.events += XrPointerEvent.Cancel(panel, hand) + holds[hand] = Hold.None + } + } + + fun update(head: Pose, hands: List, panels: List, dtSeconds: Float): XrInteractionOut { + val out = XrInteractionOut() + for (hand in 0..1) handFrame(hand, head, hands[hand], panels.filter { it.interactive }, dtSeconds, out) + return out + } + + private fun handFrame(index: Int, head: Pose, hand: XrHand, panels: List, dt: Float, out: XrInteractionOut) { + val wasTrigger = trigger[index] + val wasGrip = grip[index] + val wasSecondary = secondary[index] + trigger[index] = if (wasTrigger) hand.trigger > 0.4f else hand.trigger > 0.6f + grip[index] = if (wasGrip) hand.squeeze > 0.5f else hand.squeeze > 0.7f + secondary[index] = hand.secondary + val triggerDown = trigger[index] && !wasTrigger + val triggerUp = !trigger[index] && wasTrigger + val gripDown = grip[index] && !wasGrip + val secondaryDown = secondary[index] && !wasSecondary + val hold = holds[index] + if (!hand.active) { + if (hold is Hold.Press) out.events += XrPointerEvent.Cancel(hold.panel, index) + if (hold is Hold.Move) out.events += XrPointerEvent.Moved(hold.panel) + if (hold is Hold.Resize) out.events += XrPointerEvent.Resized(hold.panel) + holds[index] = Hold.None + return + } + val ray = hand.aim + when (hold) { + is Hold.Move -> { + val panel = hold.panel + if (abs(hand.stickY) > 0.2f) { + val length = hold.offset.length + val wanted = (length * (1f + hand.stickY * 1.2f * dt)).coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE) + hold.offset = hold.offset.normalized() * wanted + } + val position = ray.toWorld(hold.offset) + panel.pose = Pose(panel.kind.orient(position, head.position), position) + out.masks[index] = true + out.lasers[index] = hold.offset.length + val released = if (hold.byGrip) !grip[index] else !trigger[index] + if (released) { + holds[index] = Hold.None + out.events += XrPointerEvent.Moved(panel) + } + return + } + is Hold.Resize -> { + val panel = hold.panel + out.masks[index] = true + hold.panel.hitPlane(ray, bounded = false, plane = hold.plane, w = hold.width, h = hold.height)?.let { hit -> + val left = -hold.width / 2f + val top = hold.height / 2f + val width = (hold.width + hit.x - hold.startX).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) + val height = (hold.height + hold.startY - hit.y).coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) + panel.width = width + panel.height = height + panel.pose = Pose(hold.plane.orientation, hold.plane.toWorld(Vec3(left + width / 2f, top - height / 2f, 0f))) + out.lasers[index] = hit.distance + } + if (!trigger[index]) { + holds[index] = Hold.None + out.events += XrPointerEvent.Resized(panel) + } + return + } + is Hold.Press -> { + val panel = hold.panel + out.masks[index] = true + val hit = panel.hitPlane(ray, bounded = false) + if (hit != null) { + val x = panel.pixelX(hit.x) + val y = panel.pixelY(hit.y) + if (x != hold.x || y != hold.y) out.events += XrPointerEvent.Move(panel, x, y, index) + hold.x = x; hold.y = y + out.lasers[index] = hit.distance + out.point(panel, x, y) + } + if (secondaryDown) out.events += XrPointerEvent.Back(panel) + if (triggerUp || !trigger[index]) { + out.events += if (hit != null) XrPointerEvent.Up(panel, hold.x, hold.y, index) else XrPointerEvent.Cancel(panel, index) + holds[index] = Hold.None + } + return + } + is Hold.HeadPress -> { + val panel = hold.panel + out.masks[index] = true + val hit = panel.hitPlane(ray, bounded = false) + if (hit != null) { + out.lasers[index] = hit.distance + val moved = Vec3(hit.x - hold.startX, hit.y - hold.startY, 0f).length + if (moved > HEAD_DRAG_METRES) { + holds[index] = Hold.Move(panel, hold.offset, byGrip = false) + val position = ray.toWorld(hold.offset) + panel.pose = Pose(panel.kind.orient(position, head.position), position) + return + } + } + if (!trigger[index]) { + holds[index] = Hold.None + if (panel.hit(ray) != null) out.events += XrPointerEvent.Click(panel) + } + return + } + Hold.None -> Unit + } + val hit = panels.mapNotNull { it.hit(ray) }.minByOrNull { it.distance } ?: return + val panel = hit.panel + out.masks[index] = true + out.lasers[index] = hit.distance + val x = panel.pixelX(hit.x) + val y = panel.pixelY(hit.y) + out.point(panel, x, y) + val other = holds[1 - index] + val heldByOther = held(other) === panel && other !is Hold.Press + when { + heldByOther -> Unit + gripDown -> { + holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = true) + out.ticks[index] = true + } + triggerDown && panel.kind == XrPanelKind.PET_HEAD -> + holds[index] = Hold.HeadPress(panel, hit.x, hit.y, ray.toLocal(panel.pose.position)) + triggerDown && panel.inResizeGrip(hit) -> { + holds[index] = Hold.Resize(panel, panel.pose, panel.width, panel.height, hit.x, hit.y) + out.ticks[index] = true + } + triggerDown && panel.inBar(hit) && !panel.inBarButtons(hit) -> { + holds[index] = Hold.Move(panel, ray.toLocal(panel.pose.position), byGrip = false) + out.ticks[index] = true + } + triggerDown -> { + holds[index] = Hold.Press(panel, x, y) + out.events += XrPointerEvent.Down(panel, x, y, index) + } + } + if (holds[index] === Hold.None) { + if (abs(hand.stickY) > 0.25f) out.events += XrPointerEvent.Scroll(panel, x, y, hand.stickY * SCROLL_PER_SECOND * dt) + if (secondaryDown) out.events += XrPointerEvent.Back(panel) + } + } + + companion object { + const val HEAD_DRAG_METRES = 0.02f + const val SCROLL_PER_SECOND = 12f + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt new file mode 100644 index 0000000000..275322d745 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrKeyboard.kt @@ -0,0 +1,283 @@ +package com.droiddeck.launcher.session.xr + +import android.view.KeyEvent +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.Backspace +import androidx.compose.material.icons.automirrored.outlined.KeyboardReturn +import androidx.compose.material.icons.outlined.KeyboardArrowUp +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.compositeOver +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.EditCommand +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.ImeOptions +import androidx.compose.ui.text.input.PlatformTextInputService +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.input.PC_KEY_ROWS +import kotlinx.coroutines.delay +import com.droiddeck.launcher.ui.TypingRequest + +/** Sends text fields in the floating panels to [XrKeyboard], since the system keyboard cannot show in the immersive view. */ +internal class XrTextInput : PlatformTextInputService { + private var request: TypingRequest? = null + + override fun startInput( + value: TextFieldValue, imeOptions: ImeOptions, + onEditCommand: (List) -> Unit, onImeActionPerformed: (ImeAction) -> Unit, + ) { + val next = TypingRequest(value, imeOptions, { onEditCommand(TypingRequest.editsFor(it)) }, onImeActionPerformed) + request = next + XrPanels.startTyping(next) + } + + override fun stopInput() { + request?.let { XrPanels.stopTyping(it) } + request = null + } + + override fun showSoftwareKeyboard() { + request?.let { XrPanels.startTyping(it) } + } + + override fun hideSoftwareKeyboard() { + request?.let { XrPanels.stopTyping(it) } + } + + override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) { + request?.value = newValue + } +} + +internal object XrKeys { + private val letters = listOf("qwertyuiop", "asdfghjkl", "zxcvbnm") + private val symbols = listOf("1234567890", "@#&*-+=()", "!?:;'\"/,") + + fun rows(numbers: Boolean, shift: Boolean): List = + (if (numbers) symbols else letters).map { if (shift && !numbers) it.uppercase() else it } + + fun insert(value: TextFieldValue, text: String): TextFieldValue { + val start = minOf(value.selection.start, value.selection.end) + val end = maxOf(value.selection.start, value.selection.end) + val next = value.text.substring(0, start) + text + value.text.substring(end) + return TextFieldValue(next, TextRange(start + text.length)) + } + + fun backspace(value: TextFieldValue): TextFieldValue { + val start = minOf(value.selection.start, value.selection.end) + val end = maxOf(value.selection.start, value.selection.end) + if (start != end) return TextFieldValue(value.text.substring(0, start) + value.text.substring(end), TextRange(start)) + if (start == 0) return value + val cut = value.text.offsetByCodePoints(start, -1) + return TextFieldValue(value.text.substring(0, cut) + value.text.substring(start), TextRange(cut)) + } + + const val REPEAT_DELAY_MS = 450L + const val REPEAT_MS = 50L + + /** Return sends when the field asks for an action, and starts a new line otherwise. */ + fun returnSends(options: ImeOptions) = options.imeAction != ImeAction.Default && options.imeAction != ImeAction.None && + options.singleLine +} + +/** Where the laser keyboard's keys go: a text field in a panel, or the game. */ +internal interface XrKeyTarget { + fun type(text: String) + fun backspace() + fun enter() +} + +internal class XrFieldTarget(private val request: TypingRequest) : XrKeyTarget { + override fun type(text: String) = request.send(XrKeys.insert(request.value, text)) + override fun backspace() = request.send(XrKeys.backspace(request.value)) + override fun enter() = if (XrKeys.returnSends(request.imeOptions)) request.action() else type("\n") +} + +internal class XrGameTarget(private val host: XrMenuHost) : XrKeyTarget { + override fun type(text: String) = host.xrTypeText(text) + override fun backspace() = host.xrTapKey(KeyEvent.KEYCODE_DEL) + override fun enter() = host.xrTapKey(KeyEvent.KEYCODE_ENTER) +} + +/** + * DroidDeck's PC keyboard typing into a panel's text field: the keys that make a character type it, + * Backspace, Enter and Space edit, and Shift and Caps Lock pick the case. The rest have nothing to do there. + */ +internal class XrPcText(private val target: XrKeyTarget, private val timer: XrTimer = XrTimer.Main) { + private val keys = PC_KEY_ROWS.flatten() + .filter { it.labelRes == 0 && it.label.length == 1 && it.code !in ARROWS } + .associateBy { it.code } + private val shifts = mutableSetOf() + private var caps = false + private var stopRepeat: (() -> Unit)? = null + + fun key(code: Int, down: Boolean) { + if (code == LEFT_SHIFT || code == RIGHT_SHIFT) { + if (down) shifts += code else shifts -= code + return + } + if (!down && code != BACKSPACE) return + stopRepeat?.invoke() + stopRepeat = null + if (!down) return + val shifted = shifts.isNotEmpty() + when (code) { + BACKSPACE -> { + target.backspace() + stopRepeat = timer.after(XrKeys.REPEAT_DELAY_MS, ::repeatBackspace) + } + ENTER -> target.enter() + SPACE -> target.type(" ") + CAPS -> caps = !caps + else -> keys[code]?.let { key -> + target.type(when { + shifted && key.shifted != null -> key.shifted + key.label[0].isLetter() && (shifted xor caps) -> key.label.uppercase() + else -> key.label + }) + } + } + } + + private fun repeatBackspace() { + target.backspace() + stopRepeat = timer.after(XrKeys.REPEAT_MS, ::repeatBackspace) + } + + private companion object { + const val LEFT_SHIFT = 42 + const val RIGHT_SHIFT = 54 + const val BACKSPACE = 14 + const val ENTER = 28 + const val SPACE = 57 + const val CAPS = 58 + val ARROWS = setOf(103, 105, 106, 108) + } +} + +/** Runs an action later on the main thread; the function it returns cancels it. */ +internal fun interface XrTimer { + fun after(ms: Long, action: () -> Unit): () -> Unit + + companion object { + private val handler by lazy { android.os.Handler(android.os.Looper.getMainLooper()) } + val Main = XrTimer { ms, action -> + val runnable = Runnable(action) + handler.postDelayed(runnable, ms) + ({ handler.removeCallbacks(runnable) }) + } + } +} + +/** The Android-style text keyboard. */ +@Composable +internal fun XrKeyboard(target: XrKeyTarget) { + var shift by remember { mutableStateOf(false) } + var numbers by remember { mutableStateOf(false) } + fun type(text: String) { + target.type(text) + if (shift) shift = false + } + Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + XrKeys.rows(numbers, shift).forEachIndexed { index, row -> + Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (index == 2) KeyIcon(Icons.Outlined.KeyboardArrowUp, stringResource(R.string.pckb_key_shift), active = shift, weight = 1.5f) { shift = !shift } + row.forEach { key -> Key(key.toString()) { type(key.toString()) } } + if (index == 2) KeyIcon(Icons.AutoMirrored.Outlined.Backspace, stringResource(R.string.pckb_key_backspace), weight = 1.5f, repeats = true) { target.backspace() } + } + } + Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Key(if (numbers) "abc" else "?123", weight = 1.5f) { numbers = !numbers } + Key(",") { type(",") } + Key(" ", weight = 5f) { type(" ") } + Key(".") { type(".") } + KeyIcon(Icons.AutoMirrored.Outlined.KeyboardReturn, stringResource(R.string.pckb_key_enter), weight = 1.5f) { target.enter() } + } + } +} + +/** A key that lights while the laser is over it and dips while it is pressed; [repeats] keeps acting while held. */ +@Composable +private fun RowScope.KeyBox( + weight: Float, active: Boolean, onClick: () -> Unit, repeats: Boolean = false, content: @Composable (Color) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val source = remember { MutableInteractionSource() } + val (pointedAt, pointed) = rememberXrPointed() + val hovered = pointed.value + val pressed by source.collectIsPressedAsState() + val action by rememberUpdatedState(onClick) + var repeated by remember { mutableStateOf(false) } + if (repeats) LaunchedEffect(pressed) { + if (!pressed) return@LaunchedEffect + repeated = false + delay(XrKeys.REPEAT_DELAY_MS) + repeated = true + while (true) { + action() + delay(XrKeys.REPEAT_MS) + } + } + val fill by animateColorAsState( + when { + pressed -> colors.primary + active -> colors.primary.copy(alpha = 0.8f) + hovered -> colors.onSurface.copy(alpha = 0.22f).compositeOver(colors.surfaceVariant) + else -> colors.surfaceVariant + }, tween(if (pressed) 40 else 140), label = "keyFill", + ) + val scale by animateFloatAsState(if (pressed) 0.9f else if (hovered) 1.05f else 1f, tween(if (pressed) 40 else 140), label = "keyScale") + Box( + Modifier.weight(weight).fillMaxHeight() + .then(pointedAt) + .graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale } + .clip(RoundedCornerShape(8.dp)).background(fill) + .border(if (hovered) 2.dp else 0.dp, if (hovered) colors.primary else Color.Transparent, RoundedCornerShape(8.dp)) + .clickable(interactionSource = source, indication = null) { if (repeated) repeated = false else onClick() }, + contentAlignment = Alignment.Center, + ) { content(if (pressed || active) colors.onPrimary else colors.onSurface) } +} + +@Composable +private fun RowScope.Key(label: String, weight: Float = 1f, onClick: () -> Unit) = + KeyBox(weight, active = false, onClick) { tint -> Text(label, color = tint, fontSize = 22.sp, maxLines = 1) } + +@Composable +private fun RowScope.KeyIcon(icon: ImageVector, label: String, active: Boolean = false, weight: Float = 1f, repeats: Boolean = false, onClick: () -> Unit) = + KeyBox(weight, active, onClick, repeats) { tint -> Icon(icon, label, tint = tint) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt new file mode 100644 index 0000000000..4f5072f142 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrMath.kt @@ -0,0 +1,61 @@ +package com.droiddeck.launcher.session.xr + +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt + +internal data class Vec3(val x: Float, val y: Float, val z: Float) { + operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z) + operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z) + operator fun times(s: Float) = Vec3(x * s, y * s, z * s) + infix fun dot(o: Vec3) = x * o.x + y * o.y + z * o.z + infix fun cross(o: Vec3) = Vec3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x) + val length: Float get() = sqrt(this dot this) + fun normalized(): Vec3 = length.let { if (it > 1e-6f) this * (1f / it) else ZERO } + + companion object { + val ZERO = Vec3(0f, 0f, 0f) + val FORWARD = Vec3(0f, 0f, -1f) + val UP = Vec3(0f, 1f, 0f) + fun lerp(a: Vec3, b: Vec3, t: Float) = a + (b - a) * t + } +} + +internal data class Quat(val x: Float, val y: Float, val z: Float, val w: Float) { + fun rotate(v: Vec3): Vec3 { + val u = Vec3(x, y, z) + return u * (2f * (u dot v)) + v * (w * w - (u dot u)) + (u cross v) * (2f * w) + } + + fun conjugate() = Quat(-x, -y, -z, w) + + operator fun times(o: Quat) = Quat( + w * o.x + x * o.w + y * o.z - z * o.y, + w * o.y - x * o.z + y * o.w + z * o.x, + w * o.z + x * o.y - y * o.x + z * o.w, + w * o.w - x * o.x - y * o.y - z * o.z, + ) + + companion object { + val IDENTITY = Quat(0f, 0f, 0f, 1f) + fun yaw(radians: Float) = Quat(0f, sin(radians / 2f), 0f, cos(radians / 2f)) + fun pitch(radians: Float) = Quat(sin(radians / 2f), 0f, 0f, cos(radians / 2f)) + } +} + +internal data class Pose(val orientation: Quat = Quat.IDENTITY, val position: Vec3 = Vec3.ZERO) { + val forward: Vec3 get() = orientation.rotate(Vec3.FORWARD) + fun toLocal(world: Vec3): Vec3 = orientation.conjugate().rotate(world - position) + fun toWorld(local: Vec3): Vec3 = position + orientation.rotate(local) +} + +/** Yaw of a direction in the horizontal plane, 0 along -Z, matching [Quat.yaw] applied to -Z. */ +internal fun yawOf(direction: Vec3): Float = atan2(-direction.x, -direction.z) + +/** An orientation that turns +Z, the side of a quad that shows, from [position] towards [target] about the vertical axis only. */ +internal fun facing(position: Vec3, target: Vec3): Quat { + val d = target - position + if (d.x * d.x + d.z * d.z < 1e-8f) return Quat.IDENTITY + return Quat.yaw(atan2(d.x, d.z)) +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt new file mode 100644 index 0000000000..00540563a1 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelChrome.kt @@ -0,0 +1,126 @@ +package com.droiddeck.launcher.session.xr + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Remove +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.ui.geometry.Rect +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** + * The frame of a floating panel: the content, a bar under it to grab it by with up to two buttons at + * its left end, a corner grip to resize it, and the dot where a controller points. Its sizes match [XrUnits]. + */ +@Composable +internal fun XrPanelChrome( + cursor: State>>, + buttons: List, + resizable: Boolean, + content: @Composable () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val shape = RoundedCornerShape(18.dp) + Box(Modifier.fillMaxSize().clip(shape).background(colors.background).border(1.dp, Color(0x33FFFFFF), shape)) { + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f).fillMaxWidth().padding(start = 10.dp, top = 10.dp, end = 10.dp)) { + CompositionLocalProvider(LocalXrPointers provides cursor) { content() } + } + Box( + Modifier.fillMaxWidth().height(52.dp).background(colors.surfaceVariant.copy(alpha = 0.6f)), + contentAlignment = Alignment.Center, + ) { + Box(Modifier.width(72.dp).height(6.dp).clip(CircleShape).background(colors.onSurface.copy(alpha = 0.35f))) + if (buttons.isNotEmpty()) Row( + Modifier.align(Alignment.CenterStart).width(XrUnits.BAR_BUTTONS_DP.dp).padding(start = 8.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + buttons.take(2).forEach { button -> + if (button.icon != null) IconButton(onClick = button.onClick, modifier = Modifier.size(44.dp)) { + Icon(button.icon, button.label, tint = colors.onSurface) + } else TextButton(onClick = button.onClick, modifier = Modifier.height(40.dp), contentPadding = PaddingValues(horizontal = 10.dp)) { + Text(button.label, color = colors.onSurface, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1) + } + } + } + } + } + if (resizable) Canvas(Modifier.align(Alignment.BottomEnd).padding(6.dp).size(28.dp)) { + val stroke = Stroke(width = 3.dp.toPx()) + for (step in 1..3) { + val inset = size.width * step / 4f + drawLine(Color(0x99FFFFFF), Offset(size.width, inset), Offset(inset, size.height), stroke.width) + } + } + val density = LocalDensity.current + Canvas(Modifier.fillMaxSize()) { + val radius = with(density) { 7.dp.toPx() } + for ((x, y) in cursor.value) { + drawCircle(Color(0xCC1E9EFF), radius, Offset(x, y)) + drawCircle(Color.White, radius, Offset(x, y), style = Stroke(with(density) { 2.dp.toPx() })) + } + } + } +} + +/** Where each laser meets the panel, in the panel's pixels; null off a floating panel. */ +internal val LocalXrPointers = staticCompositionLocalOf>>?> { null } + +/** + * Whether a laser rests on the element the returned [Modifier] is put on, for both controllers at + * once, where a mouse hover has room for one. False off a floating panel. + */ +@Composable +internal fun rememberXrPointed(): Pair> { + val pointers = LocalXrPointers.current + var bounds by remember { mutableStateOf(Rect.Zero) } + val pointed = remember(pointers) { + derivedStateOf { pointers != null && pointers.value.any { (x, y) -> bounds.contains(Offset(x, y)) } } + } + return Modifier.onGloballyPositioned { bounds = it.boundsInWindow() } to pointed +} + +/** With no [icon] the button shows [label] itself, for a short word such as a keyboard mode. */ +internal class XrPanelButton(val icon: ImageVector?, val label: String, val onClick: () -> Unit) + +internal val XrCollapseIcon get() = Icons.Outlined.Remove diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt new file mode 100644 index 0000000000..0d54d8cafe --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanelWindow.kt @@ -0,0 +1,271 @@ +package com.droiddeck.launcher.session.xr + +import android.app.Presentation +import android.content.Context +import android.hardware.display.DisplayManager +import android.hardware.display.VirtualDisplay +import android.os.Bundle +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import android.view.Surface +import android.view.View +import android.view.ViewGroup +import android.view.WindowManager +import android.view.inspector.WindowInspector +import android.widget.FrameLayout +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.LocalTextInputService +import androidx.compose.ui.text.input.TextInputService +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.activity.OnBackPressedDispatcher +import androidx.activity.OnBackPressedDispatcherOwner +import androidx.activity.setViewTreeOnBackPressedDispatcherOwner +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.lifecycle.setViewTreeViewModelStoreOwner +import androidx.savedstate.SavedStateRegistry +import androidx.savedstate.SavedStateRegistryController +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.droiddeck.launcher.ui.LocalPresentationWindow + +/** Keeps a panel's Compose content running while the activity that made it is stopped behind the XR view. */ +private class PanelOwner : LifecycleOwner, SavedStateRegistryOwner, ViewModelStoreOwner, OnBackPressedDispatcherOwner { + private val registry = LifecycleRegistry(this) + private val saved = SavedStateRegistryController.create(this) + override val lifecycle: Lifecycle get() = registry + override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry + override val viewModelStore = ViewModelStore() + override val onBackPressedDispatcher = OnBackPressedDispatcher() + + fun own(view: View) { + view.setViewTreeLifecycleOwner(this) + view.setViewTreeSavedStateRegistryOwner(this) + view.setViewTreeViewModelStoreOwner(this) + view.setViewTreeOnBackPressedDispatcherOwner(this) + } + + init { + saved.performRestore(null) + registry.currentState = Lifecycle.State.RESUMED + } + + fun destroy() { + registry.currentState = Lifecycle.State.DESTROYED + viewModelStore.clear() + } +} + +/** + * One floating panel's Android side: a private virtual display drawing into the panel's OpenXR + * surface, and a presentation on it holding the Compose content. Main thread only. + */ +internal class XrPanelWindow( + private val context: Context, + private var surface: Surface, + width: Int, + height: Int, + startPaused: Boolean, + private val content: @Composable () -> Unit, +) { + private var paused = startPaused + private val owner = PanelOwner() + private val textInput = TextInputService(XrTextInput()) + private val display: VirtualDisplay = context.getSystemService(DisplayManager::class.java).createVirtualDisplay( + "DroidDeck XR panel", width, height, XrUnits.DPI, surface.takeUnless { paused }, DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY, + ) + private val presentation = PanelPresentation(context, display.display) + private var downTime = 0L + private var target: View? = null + /** The controllers pressing the panel, by hand, as fingers of one touch. */ + private val touches = linkedMapOf>() + private var hovering: View? = null + private var hoverAt = 0f to 0f + private var cursor: Pair? = null + + init { + try { + presentation.show() + } catch (failure: RuntimeException) { + release() + throw failure + } + } + + val displayId: Int get() = display.display.displayId + + fun resize(surface: Surface, width: Int, height: Int) { + this.surface = surface + if (!paused) display.surface = surface + display.resize(width, height, XrUnits.DPI) + } + + /** Stops drawing into the panel's layer, or starts again. */ + fun pause(pause: Boolean) { + if (pause == paused) return + paused = pause + display.surface = if (pause) null else surface + } + + fun release() { + runCatching { presentation.dismiss() } + owner.destroy() + display.release() + } + + private inner class PanelPresentation(outer: Context, display: android.view.Display) : Presentation(outer, display) { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + window?.setBackgroundDrawableResource(android.R.color.transparent) + window?.addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) + val compose = ComposeView(context).apply { + owner.own(this) + setContent { + CompositionLocalProvider( + LocalPresentationWindow provides true, + LocalTextInputService provides textInput, + ) { content() } + } + } + val frame = FrameLayout(context).apply { + addView(compose, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + } + setContentView(frame) + window?.decorView?.let(owner::own) + } + } + + /** + * The topmost window on this panel's display under the point, so popups and dialogs get the input. + * A focusable popup or dialog on top takes a press outside it too, as on a touchscreen, where it + * dismisses itself rather than letting the press act on what is behind it. + */ + private fun rootAt(x: Float, y: Float): View? { + val roots = WindowInspector.getGlobalWindowViews().filter { it.isAttachedToWindow && it.display?.displayId == displayId && it.isShown } + val location = IntArray(2) + fun contains(root: View): Boolean { + root.getLocationOnScreen(location) + return x >= location[0] && y >= location[1] && x < location[0] + root.width && y < location[1] + root.height + } + val top = roots.lastOrNull() ?: return null + val focusable = (top.layoutParams as? WindowManager.LayoutParams) + ?.let { it.flags and WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE == 0 } ?: false + if (roots.size > 1 && focusable && !contains(top)) return top + return roots.lastOrNull(::contains) ?: top + } + + /** Sends every finger in [touches] to [target]; [action] is already shifted by its pointer index where it needs one. */ + private fun sendTouches(action: Int, time: Long) { + val view = target ?: return + val location = IntArray(2) + view.getLocationOnScreen(location) + val properties = touches.keys.map { hand -> + MotionEvent.PointerProperties().apply { id = hand; toolType = MotionEvent.TOOL_TYPE_FINGER } + }.toTypedArray() + val coords = touches.values.map { (x, y) -> + MotionEvent.PointerCoords().apply { this.x = x - location[0]; this.y = y - location[1]; pressure = 1f; size = 1f } + }.toTypedArray() + val event = MotionEvent.obtain(downTime, time, action, touches.size, properties, coords, 0, 0, 1f, 1f, 0, 0, + InputDevice.SOURCE_TOUCHSCREEN, 0) + try { + view.dispatchTouchEvent(event) + } finally { + event.recycle() + } + } + + private fun indexed(action: Int, hand: Int) = + action or (touches.keys.indexOf(hand) shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) + + private fun send(view: View, action: Int, x: Float, y: Float, time: Long, generic: Boolean, scroll: Float = 0f): Boolean { + val location = IntArray(2) + view.getLocationOnScreen(location) + val properties = arrayOf(MotionEvent.PointerProperties().apply { + id = 0 + toolType = if (generic) MotionEvent.TOOL_TYPE_MOUSE else MotionEvent.TOOL_TYPE_FINGER + }) + val coords = arrayOf(MotionEvent.PointerCoords().apply { + this.x = x - location[0] + this.y = y - location[1] + pressure = 1f + size = 1f + if (scroll != 0f) setAxisValue(MotionEvent.AXIS_VSCROLL, scroll) + }) + val source = if (generic) InputDevice.SOURCE_MOUSE else InputDevice.SOURCE_TOUCHSCREEN + val event = MotionEvent.obtain(if (generic) time else downTime, time, action, 1, properties, coords, 0, 0, 1f, 1f, 0, 0, source, 0) + return try { + if (generic) view.dispatchGenericMotionEvent(event) else view.dispatchTouchEvent(event) + } finally { + event.recycle() + } + } + + /** The laser resting on the panel, as a mouse hovering, so keys and buttons light under it. Null: it left. */ + fun hover(at: Pair?) { + cursor = at + if (target != null) return + val now = SystemClock.uptimeMillis() + val root = at?.let { (x, y) -> rootAt(x, y) } + if (root !== hovering) endHover(now) + if (root == null || at == null) return + if (hovering == null) send(root, MotionEvent.ACTION_HOVER_ENTER, at.first, at.second, now, generic = true) + send(root, MotionEvent.ACTION_HOVER_MOVE, at.first, at.second, now, generic = true) + hovering = root + hoverAt = at + } + + private fun endHover(now: Long) { + hovering?.let { send(it, MotionEvent.ACTION_HOVER_EXIT, hoverAt.first, hoverAt.second, now, generic = true) } + hovering = null + } + + fun pointer(event: XrPointerEvent) { + val now = SystemClock.uptimeMillis() + when (event) { + is XrPointerEvent.Down -> { + if (event.hand in touches) return + touches[event.hand] = event.x to event.y + if (touches.size == 1) { + endHover(now) + downTime = now + target = rootAt(event.x, event.y) + sendTouches(MotionEvent.ACTION_DOWN, now) + } else sendTouches(indexed(MotionEvent.ACTION_POINTER_DOWN, event.hand), now) + } + is XrPointerEvent.Move -> { + if (event.hand !in touches) return + touches[event.hand] = event.x to event.y + sendTouches(MotionEvent.ACTION_MOVE, now) + } + is XrPointerEvent.Up -> { + if (event.hand !in touches) return + touches[event.hand] = event.x to event.y + if (touches.size > 1) { + sendTouches(indexed(MotionEvent.ACTION_POINTER_UP, event.hand), now) + touches -= event.hand + } else { + sendTouches(MotionEvent.ACTION_UP, now) + touches.clear() + target = null + hover(cursor) + } + } + is XrPointerEvent.Cancel -> { + if (event.hand !in touches) return + sendTouches(MotionEvent.ACTION_CANCEL, now) + touches.clear() + target = null + } + is XrPointerEvent.Scroll -> rootAt(event.x, event.y)?.let { + send(it, MotionEvent.ACTION_SCROLL, event.x, event.y, now, generic = true, scroll = event.amount) + } + else -> Unit + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt new file mode 100644 index 0000000000..17431f1458 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrPanels.kt @@ -0,0 +1,611 @@ +package com.droiddeck.launcher.session.xr + +import android.content.Context +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.util.Log +import android.view.Surface +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.KeyboardHide +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.agent.AgentHost +import com.droiddeck.launcher.session.QuestExperimental +import com.droiddeck.launcher.ui.AgentPage +import com.droiddeck.launcher.ui.AgentPet +import com.droiddeck.launcher.ui.DroidDeckTheme +import com.droiddeck.launcher.ui.PcKeyboard +import com.droiddeck.launcher.ui.PetFigure +import com.droiddeck.launcher.ui.TypingRequest +import com.droiddeck.launcher.ui.petStateNow +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import java.lang.ref.WeakReference +import java.nio.ByteBuffer +import java.util.concurrent.ConcurrentLinkedQueue +import kotlin.math.PI + +/** The 2D session window, which hands its menu to the immersive view while that is open. */ +internal interface XrMenuHost { + @Composable + fun XrMenuContent() + fun xrSetMenuOpen(open: Boolean) + fun xrMenuBack() + /** A key of DroidDeck's PC keyboard, by Linux key code, to the game. */ + fun xrSendKey(code: Int, down: Boolean) + /** Text from the laser keyboard to the game, as the Android keyboard sends it. */ + fun xrTypeText(text: String) + fun xrTapKey(keyCode: Int) + /** The immersive view opened or closed; Steam's screen, which SteamVR mirrors as its Steam window, sizes for it. */ + fun xrImmersiveChanged(active: Boolean) +} + +/** What the immersive view's native loop offers: surface-backed layers it composites in front of the game. */ +internal interface XrLayerSource { + val context: Context + fun createLayer(width: Int, height: Int): Int + fun layerSurface(id: Int): Surface? + fun destroyLayer(id: Int) + fun setOrbImage(image: android.graphics.Bitmap) + fun leave() +} + +/** + * DroidDeck's own windows inside the immersive Quest view: the session menu, opened by holding the + * controllers together, and the agent pet with its chat. Quest only. [frame] runs on the XR thread + * each frame; the rest runs on the main thread. + */ +internal object XrPanels { + private const val TAG = "XrPanels" + private const val OPEN_MS = 350f + private const val CLOSE_MS = 250f + private const val BURST_MS = 400f + + /** The immersive view is up, so the menu and pet belong in it. Always false off Quest. */ + @Volatile + var immersiveActive = false + + /** Counts attachments, so work posted from one immersive view is dropped once a later one, or none, is up. */ + @Volatile + private var attachment = 0 + private set + + private val main = Handler(Looper.getMainLooper()) + + /** Whether the headset shows the session; panels draw into their layers only then. */ + @Volatile + private var drawing = false + private val lock = Any() + private val ops = ConcurrentLinkedQueue<() -> Unit>() + private var source: XrLayerSource? = null + private var host: XrHost? = null + private var menuHost: WeakReference? = null + private var scope: CoroutineScope? = null + + private class Panel(val state: XrPanelState, val content: @Composable (State>>) -> Unit) { + val cursorState = mutableStateOf>>(emptyList()) + var layerId = -1 + var window: XrPanelWindow? = null + var openedMs = 0L + var closingMs = 0L + var resizing = false + var cursor: List> = emptyList() + } + + private val panels = mutableListOf() + private val gesture = XrGesture() + private val interaction = XrInteraction() + private var lastFrameMs = 0L + private var orbImageSent = false + private var lastHead = Pose() + private var burstMs = 0L + private var burstAt = Vec3.ZERO + private var lastTick = 0 + private var menuFrom: Vec3? = null + private val typing = mutableStateOf(null) + /** The keyboard was opened for the game, from the session menu; a panel's text field takes it over while it types. */ + private val gameKeyboard = mutableStateOf(false) + private val pcKeyboard = mutableStateOf(false) + + fun gateOpen(model: String, device: String, manufacturer: String, immersive: Boolean) = + immersive && QuestExperimental.supported(model, device, manufacturer) + + fun setMenuHost(menu: XrMenuHost?) { + menuHost = menu?.let { WeakReference(it) } + if (immersiveActive) menu?.xrImmersiveChanged(true) + } + + fun clearMenuHost(menu: XrMenuHost) { + if (menuHost?.get() === menu) menuHost = null + } + + /** Main thread: the immersive view handed over its buffers. */ + fun attach(layers: XrLayerSource, state: ByteBuffer, control: ByteBuffer) { + if (!QuestExperimental.isSupported()) return + synchronized(lock) { + source = layers + host = XrHost(state, control) + orbImageSent = false + } + attachment++ + immersiveActive = true + menuHost?.get()?.xrImmersiveChanged(true) + scope?.cancel() + scope = MainScope().also { scope -> + scope.launch { + snapshotFlow { com.droiddeck.launcher.agent.AgentGuest.focusRevision }.collect { + menuHost?.get()?.xrImmersiveChanged(true) + } + } + scope.launch { + snapshotFlow { AgentPet.enabled && AgentHost.installed }.collect { on -> + if (on) { if (!shown(XrPanelKind.PET_CHAT)) open(XrPanelKind.PET_HEAD) } + else { close(XrPanelKind.PET_HEAD); close(XrPanelKind.PET_CHAT) } + } + } + } + } + + /** + * XR thread, as the session becomes visible or stops being so. OpenXR allows writing into a surface + * swapchain only while the session is visible or focused, and requires the writes to have stopped + * before xrEndSession, so this returns once the panels have stopped or started drawing. + */ + fun setDrawing(visible: Boolean) { + val done = java.util.concurrent.CountDownLatch(1) + val apply = Runnable { + try { + drawing = visible + synchronized(lock) { panels.mapNotNull { it.window } }.forEach { it.pause(!visible) } + } finally { + done.countDown() + } + } + if (Looper.myLooper() == Looper.getMainLooper()) apply.run() + else if (main.post(apply) && !done.await(1, java.util.concurrent.TimeUnit.SECONDS)) + Log.w(TAG, "panels did not ${if (visible) "start" else "stop"} drawing within a second") + } + + /** Main thread: the immersive view is going; every panel goes with it. */ + fun detach() { + if (!immersiveActive) return + immersiveActive = false + scope?.cancel() + scope = null + val windows = synchronized(lock) { + source = null + host = null + ops.clear() + interaction.reset() + panels.mapNotNull { it.window }.also { panels.clear() } + } + windows.forEach { it.release() } + typing.value = null + gameKeyboard.value = false + gesture.reset(release = false) + menuHost?.get()?.xrSetMenuOpen(false) + menuHost?.get()?.xrImmersiveChanged(false) + } + + /** Main thread, from the session window's menu state. */ + fun showMenu(): Boolean { + if (!immersiveActive) return false + open(XrPanelKind.MENU, menuFrom) + menuFrom = null + return true + } + + fun hideMenu() = close(XrPanelKind.MENU) + + /** Main thread: closes the immersive view, as a stop chosen in its menu asks. */ + fun leaveImmersive() { + synchronized(lock) { source }?.leave() + } + + /** Main thread: a text field in a panel wants typing, so the laser keyboard opens. */ + fun startTyping(request: TypingRequest) { + if (!immersiveActive) return + typing.value = request + open(XrPanelKind.KEYBOARD) + } + + fun stopTyping(request: TypingRequest) { + if (typing.value !== request) return + typing.value = null + if (!gameKeyboard.value) close(XrPanelKind.KEYBOARD) + } + + /** + * Main thread: the session menu's keyboards. [pc] picks DroidDeck's PC keyboard over the Android-style one; + * asking again for the one already open closes it. False off the immersive view, where the 2D keyboards stay. + */ + fun toggleGameKeyboard(pc: Boolean): Boolean { + if (!immersiveActive) return false + if (gameKeyboard.value && pcKeyboard.value == pc && shown(XrPanelKind.KEYBOARD)) hideKeyboard() + else showGameKeyboard(pc) + return true + } + + fun showGameKeyboard(pc: Boolean): Boolean { + if (!immersiveActive) return false + gameKeyboard.value = true + pcKeyboard.value = pc + open(XrPanelKind.KEYBOARD) + return true + } + + private fun hideKeyboard() { + typing.value = null + gameKeyboard.value = false + close(XrPanelKind.KEYBOARD) + } + + private fun shown(kind: XrPanelKind) = synchronized(lock) { panels.any { it.state.kind == kind && it.closingMs == 0L } } + + private fun open(kind: XrPanelKind, from: Vec3? = null) { + ops += { create(kind, from) } + } + + private fun close(kind: XrPanelKind) { + ops += { + panels.filter { it.state.kind == kind && it.closingMs == 0L }.forEach { panel -> + panel.closingMs = SystemClock.uptimeMillis() + val out = XrInteractionOut() + interaction.release(panel.state, out) + dispatch(out) + } + } + } + + /** XR thread. */ + private fun create(kind: XrPanelKind, from: Vec3?) { + val layers = source ?: return + panels.firstOrNull { it.state.kind == kind }?.let { existing -> + if (existing.closingMs != 0L) { + existing.closingMs = 0L + val elapsed = 1f - Math.cbrt((1.0 - existing.state.scale).coerceIn(0.0, 1.0)).toFloat() + existing.openedMs = SystemClock.uptimeMillis() - (elapsed * OPEN_MS).toLong() + } + return + } + val placed = XrPlacement.load(layers.context, kind, lastHead) + val state = XrPanelState(kind, placed.pose, placed.width, placed.height) + state.scale = 0f + state.animationFrom = from ?: placed.pose.position + val id = layers.createLayer(state.pixelWidth, state.pixelHeight) + val surface = if (id >= 0) layers.layerSurface(id) else null + if (surface == null) { + Log.w(TAG, "no layer for the ${kind.key} panel") + if (id >= 0) layers.destroyLayer(id) + if (kind == XrPanelKind.MENU) main.post { menuHost?.get()?.xrSetMenuOpen(false) } + return + } + val panel = Panel(state, contentFor(kind)) + panel.layerId = id + panel.openedMs = SystemClock.uptimeMillis() + panels += panel + val context = layers.context + main.post { + synchronized(lock) { + if (panel !in panels) return@post + panel.window = runCatching { + XrPanelWindow(context, surface, state.pixelWidth, state.pixelHeight, startPaused = !drawing) { + panel.content(panel.cursorState) + } + }.onFailure { + Log.w(TAG, "could not show the ${kind.key} panel", it) + panels -= panel + ops += { if (source === layers) layers.destroyLayer(id) } + if (kind == XrPanelKind.MENU) menuHost?.get()?.xrSetMenuOpen(false) + }.getOrNull() + } + } + } + + private fun contentFor(kind: XrPanelKind): @Composable (State>>) -> Unit = when (kind) { + XrPanelKind.MENU -> { cursor -> + DroidDeckTheme { + XrPanelChrome(cursor, buttons = emptyList(), resizable = true) { + menuHost?.get()?.XrMenuContent() + } + } + } + XrPanelKind.PET_HEAD -> { _ -> + DroidDeckTheme { Box(Modifier.fillMaxSize()) { PetFigure(petStateNow(), Modifier.fillMaxSize()) } } + } + XrPanelKind.KEYBOARD -> { cursor -> + DroidDeckTheme { + val buttons = listOf( + XrPanelButton(Icons.Outlined.KeyboardHide, stringResource(R.string.pckb_hide), ::hideKeyboard), + XrPanelButton(null, if (pcKeyboard.value) "Android" else "PC") { pcKeyboard.value = !pcKeyboard.value }, + ) + XrPanelChrome(cursor, buttons, resizable = true) { KeyboardContent() } + } + } + XrPanelKind.PET_CHAT -> { cursor -> + DroidDeckTheme { + XrPanelChrome(cursor, listOf(XrPanelButton(XrCollapseIcon, stringResource(R.string.bottom_chat_close), ::collapseChat)), resizable = true) { + AgentPage(Modifier.fillMaxSize().padding(horizontal = 12.dp), visible = true, startTyping = false, hidesPet = false) + } + } + } + } + + /** A panel's text field takes the keyboard while it types; otherwise its keys go to the game. */ + @Composable + private fun KeyboardContent() { + val request = typing.value + val host = menuHost?.get()?.takeIf { gameKeyboard.value } + val target = request?.let(::XrFieldTarget) ?: host?.let(::XrGameTarget) ?: return + if (pcKeyboard.value) { + val pcText = remember(request) { request?.let { XrPcText(XrFieldTarget(it)) } } + PcKeyboard( + sendKey = { code, down -> pcText?.key(code, down) ?: host?.xrSendKey(code, down) }, + onAndroidKeyboard = { pcKeyboard.value = false }, + onClose = ::hideKeyboard, + heightFraction = 1f, + showButtons = false, + hoverFeedback = true, + ) + } else XrKeyboard(target) + } + + private fun collapseChat() { + close(XrPanelKind.PET_CHAT) + open(XrPanelKind.PET_HEAD) + } + + private fun expandChat(from: Vec3) { + close(XrPanelKind.PET_HEAD) + open(XrPanelKind.PET_CHAT, from) + } + + /** XR thread, once per frame, from QuestXrActivity.onXrHostFrame. */ + fun frame() = synchronized(lock) { + val host = host ?: return + val layers = source ?: return + val frame = host.read() + lastHead = frame.head + while (true) (ops.poll() ?: break).invoke() + if (!orbImageSent) { + orbImageSent = true + runCatching { + android.graphics.BitmapFactory.decodeResource(layers.context.resources, R.drawable.logo) + }.getOrNull()?.let { layers.setOrbImage(it); it.recycle() } + } + val now = SystemClock.uptimeMillis() + val dt = if (lastFrameMs == 0L) 0f else ((now - lastFrameMs) / 1000f).coerceIn(0f, 0.1f) + lastFrameMs = now + val control = XrControlOut() + animate(now, layers) + val active = panels.filter { it.closingMs == 0L && it.window != null } + if (frame.focused) { + if (gesture.update(frame.hands[0], frame.hands[1], now)) { + burstMs = now + burstAt = gesture.midpoint + lastTick = 0 + for (hand in 0..1) control.haptics[hand] = XrHaptic(60, 0.9f) + val from = gesture.midpoint + val posted = attachment + main.post { if (immersiveActive && posted == attachment) toggleMenu(from) } + } else if (gesture.phase == XrGesture.Phase.ARMING) { + val step = (gesture.progress * 4).toInt() + if (step > lastTick) for (hand in 0..1) control.haptics[hand] = XrHaptic(18, 0.2f + 0.15f * step) + lastTick = step + } else lastTick = 0 + val out = interaction.update(frame.head, frame.hands, active.map { it.state }, dt) + for (hand in 0..1) { + control.masks[hand] = out.masks[hand] + control.lasers[hand] = out.lasers[hand] + if (out.ticks[hand] && control.haptics[hand] == null) control.haptics[hand] = XrHaptic(12, 0.35f) + } + dispatch(out) + } else { + gesture.reset(release = false) + val out = XrInteractionOut() + interaction.cancel(out) + dispatch(out) + } + control.orb = orb(now) + panels.forEachIndexed { index, panel -> + if (panel.layerId < 0 || panel.window == null) return@forEachIndexed + val state = panel.state + control.layers += XrLayerOut(panel.layerId, state.shownPose, state.width * state.scale, state.height * state.scale, + order = if (state.kind == XrPanelKind.PET_HEAD) 100 else index) + } + host.write(control) + } + + private fun orb(now: Long): XrControlOut.Orb? { + if (gesture.phase == XrGesture.Phase.ARMING) + return XrControlOut.Orb(gesture.midpoint, 0.02f + 0.01f * gesture.progress, gesture.progress, 0f) + val burst = (now - burstMs) / BURST_MS + if (burstMs != 0L && burst < 1f) return XrControlOut.Orb(burstAt, 0.03f, 1f, burst.coerceAtLeast(0.01f)) + return null + } + + private fun animate(now: Long, layers: XrLayerSource) { + val gone = mutableListOf() + for (panel in panels) { + val state = panel.state + if (panel.closingMs != 0L) { + val t = ((now - panel.closingMs) / CLOSE_MS).coerceIn(0f, 1f) + state.scale = minOf(state.scale, 1f - easeOut(t)) + if (state.animationFrom == null) state.animationFrom = state.pose.position + if (t >= 1f) gone += panel + } else if (state.scale < 1f) { + state.scale = easeOut(((now - panel.openedMs) / OPEN_MS).coerceIn(0f, 1f)) + if (state.scale >= 1f) state.animationFrom = null + } + } + for (panel in gone) { + panels -= panel + if (panel.layerId >= 0) layers.destroyLayer(panel.layerId) + val window = panel.window + val context = layers.context + val state = panel.state + val head = lastHead + main.post { + window?.release() + XrPlacement.save(context, state.kind, head, state.pose, state.width, state.height) + } + } + } + + private fun easeOut(t: Float) = 1f - (1f - t) * (1f - t) * (1f - t) + + /** XR thread: hands each panel its input on the main thread and follows up on moves and resizes. */ + private fun dispatch(out: XrInteractionOut) { + val layers = source ?: return + for (panel in panels) { + val cursor = out.cursors[panel.state]?.toList().orEmpty() + if (cursor != panel.cursor) { + panel.cursor = cursor + val target = panel.cursorState + val window = panel.window + main.post { + target.value = cursor + window?.hover(cursor.firstOrNull()) + } + } + } + for (event in out.events) { + val panel = panels.firstOrNull { it.state === event.panel } ?: continue + when (event) { + is XrPointerEvent.Back -> main.post { back(panel.state.kind) } + is XrPointerEvent.Click -> { + val from = panel.state.pose.position + main.post { expandChat(from) } + } + is XrPointerEvent.Resized -> { + savePlacement(panel, layers) + resize(panel, layers) + } + is XrPointerEvent.Moved -> savePlacement(panel, layers) + else -> { + val window = panel.window + main.post { window?.pointer(event) } + } + } + } + } + + /** XR thread: the place a move or resize ended at, read together now and saved on the main thread. */ + private fun savePlacement(panel: Panel, layers: XrLayerSource) { + val state = panel.state + val kind = state.kind + val head = lastHead + val pose = state.pose + val width = state.width + val height = state.height + val context = layers.context + main.post { XrPlacement.save(context, kind, head, pose, width, height) } + } + + /** XR thread: gives a resized panel a surface of its new size once its content has moved over to it. */ + private fun resize(panel: Panel, layers: XrLayerSource) { + val state = panel.state + val width = XrUnits.pixels(state.width) + val height = XrUnits.pixels(state.height) + if (width == state.pixelWidth && height == state.pixelHeight) return + val id = layers.createLayer(width, height) + val surface = if (id >= 0) layers.layerSurface(id) else null + if (surface == null) { + if (id >= 0) layers.destroyLayer(id) + return + } + val window = panel.window + main.post { + window?.resize(surface, width, height) + ops += { + if (panel in panels) { + val old = panel.layerId + panel.layerId = id + state.pixelWidth = width + state.pixelHeight = height + if (old >= 0) layers.destroyLayer(old) + } else if (source === layers) layers.destroyLayer(id) + } + } + } + + /** Main thread. */ + private fun toggleMenu(from: Vec3) { + val menu = menuHost?.get() ?: return + if (shown(XrPanelKind.MENU)) menu.xrSetMenuOpen(false) + else { + menuFrom = from + menu.xrSetMenuOpen(true) + } + } + + /** Main thread: B on a panel goes back a step, as Back does in the 2D window. */ + private fun back(kind: XrPanelKind) { + when (kind) { + XrPanelKind.MENU -> menuHost?.get()?.xrMenuBack() + XrPanelKind.PET_CHAT -> collapseChat() + XrPanelKind.PET_HEAD -> Unit + XrPanelKind.KEYBOARD -> hideKeyboard() + } + } +} + +/** Where each panel kind was left, relative to where the user faced, so it comes back there. */ +internal object XrPlacement { + class Placed(val pose: Pose, val width: Float, val height: Float) + + private class Default(val yaw: Float, val distance: Float, val dy: Float, val width: Float, val height: Float) + + private val defaults = mapOf( + XrPanelKind.MENU to Default(0f, 0.95f, -0.12f, 0.9f, 0.6f), + XrPanelKind.PET_CHAT to Default(0.6f, 0.95f, -0.12f, 0.6f, 0.7f), + XrPanelKind.PET_HEAD to Default(0.7f, 0.75f, -0.45f, 0.12f, 0.12f), + XrPanelKind.KEYBOARD to Default(0f, 0.5f, -0.5f, 0.8f, 0.36f), + ) + + private fun prefs(context: Context) = context.getSharedPreferences("quest_xr_panels", Context.MODE_PRIVATE) + + fun place(kind: XrPanelKind, head: Pose, yaw: Float, distance: Float, dy: Float): Pose { + val angle = yawOf(head.forward) + yaw + val direction = Quat.yaw(angle).rotate(Vec3.FORWARD) + val position = head.position + direction * distance + Vec3(0f, dy, 0f) + return Pose(kind.orient(position, head.position), position) + } + + fun relative(head: Pose, position: Vec3): Triple { + val offset = position - head.position + val distance = Vec3(offset.x, 0f, offset.z).length + var yaw = yawOf(offset) - yawOf(head.forward) + while (yaw > PI) yaw -= (2 * PI).toFloat() + while (yaw < -PI) yaw += (2 * PI).toFloat() + return Triple(yaw, distance, offset.y) + } + + fun load(context: Context, kind: XrPanelKind, head: Pose): Placed { + val fallback = defaults.getValue(kind) + val saved = prefs(context).getString(kind.key, null)?.split(',')?.mapNotNull { it.toFloatOrNull() } + val values = saved?.takeIf { it.size == 5 } ?: listOf(fallback.yaw, fallback.distance, fallback.dy, fallback.width, fallback.height) + val distance = values[1].coerceIn(XrUnits.MIN_DISTANCE, XrUnits.MAX_DISTANCE) + val width = if (kind.resizable) values[3].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.width + val height = if (kind.resizable) values[4].coerceIn(XrUnits.MIN_METRES, XrUnits.MAX_METRES) else fallback.height + return Placed(place(kind, head, values[0], distance, values[2].coerceIn(-1.5f, 1.5f)), width, height) + } + + fun save(context: Context, kind: XrPanelKind, head: Pose, pose: Pose, width: Float, height: Float) { + val (yaw, distance, dy) = relative(head, pose.position) + prefs(context).edit().putString(kind.key, listOf(yaw, distance, dy, width, height).joinToString(",")).apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt b/app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt new file mode 100644 index 0000000000..d797f5be9b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/xr/XrSteamScreen.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.session.xr + +/** Whether the guest's focus report shows Steam's own screen, with no game holding a window. */ +internal object XrSteamScreen { + /** Steam's own UI and SteamVR, which have windows of their own but are not games. */ + private val STEAM_APPS = setOf(769L, 250820L) + + /** + * Gamescope lists Steam itself while its screen is up, so a report naming no app at all, as the guest + * writes when it could not collect focus or gamescope has not published it, says nothing. + */ + fun shown(focusedApp: Long?, focusableApps: List?): Boolean { + val apps = (listOfNotNull(focusedApp) + focusableApps.orEmpty()).filter { it > 0 } + return apps.isNotEmpty() && apps.all { it in STEAM_APPS } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt index 8adadcab9c..2ded416719 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPet.kt @@ -88,7 +88,14 @@ internal object AgentPet { private set /** The floating windows could not be made, so the pet stays in DroidDeck's own windows instead. */ private var floatFailed by mutableStateOf(false) - val floating get() = enabled && allowed && !floatFailed + val floating get() = enabled && allowed && !floatFailed && usesOverlayWindows(onQuest) + /** Quest's shell turns overlay windows into system panels that take input from the VR view. */ + private val onQuest = com.droiddeck.launcher.session.QuestExperimental.isSupported() + + internal fun usesOverlayWindows(quest: Boolean) = !quest + + /** On Quest the chat opens as its own panel window, which Horizon moves, resizes and closes. */ + internal fun chatInOwnWindow(quest: Boolean = onQuest) = quest /** How to close the chat open inside each DroidDeck window that has one. */ private val closeInWindow = java.util.WeakHashMap Unit>() @@ -118,7 +125,7 @@ internal object AgentPet { AgentHost.prefs(context).edit().putBoolean(KEY, on).apply() if (on) { allowed = PetWindows.allowed(context) - if (!allowed) requestFloating(context) + if (!allowed && usesOverlayWindows(onQuest)) requestFloating(context) } } @@ -251,9 +258,12 @@ private fun PetLayer(host: AgentPetHost) { val density = LocalDensity.current val openLabel = androidx.compose.ui.res.stringResource(com.droiddeck.launcher.R.string.agent_pet_open) val openChat = { - motion.dock() - chatShown = true - chatOpen = true + if (AgentPet.chatInOwnWindow()) com.droiddeck.launcher.agent.AgentChatActivity.open(context) + else { + motion.dock() + chatShown = true + chatOpen = true + } } val closeChat = { chatOpen = false diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt b/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt index 59c87675e9..3810161619 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt @@ -7,13 +7,16 @@ import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.background import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn @@ -35,6 +38,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role @@ -90,6 +94,29 @@ internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Un } } +/** A Quest has no system Back gesture, so a laser drag in from the right edge stands in for it. */ +@Composable +internal fun DrawerEdgeSwipe(onBack: () -> Unit) { + val density = LocalDensity.current + val threshold = with(density) { 48.dp.toPx() } + val strip = with(density) { 12.toDp() } + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) { + Box( + Modifier.fillMaxHeight().width(strip).testTag("drawer-edge") + .pointerInput(Unit) { + var travelled = 0f + detectHorizontalDragGestures( + onDragStart = { travelled = 0f }, + onDragEnd = { if (travelled <= -threshold) onBack() }, + ) { change, amount -> + change.consume() + travelled += amount + } + }, + ) + } +} + @Composable internal fun DrawerCornerTap(onOpen: () -> Unit) { Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) { 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 834de6f4d1..5fe2b12fec 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -711,7 +711,7 @@ internal fun SetupPanel( ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) { AgentPet.set(agentContext, it) } - if (AgentPet.enabled && !AgentPet.allowed) ActionRow( + if (AgentPet.enabled && !AgentPet.allowed && AgentPet.usesOverlayWindows(com.droiddeck.launcher.session.QuestExperimental.isSupported())) ActionRow( stringResource(R.string.setup_agent_pet_float), stringResource(R.string.setup_agent_pet_float_hint), stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt index 5c40727031..bd63dce034 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PcKeyboard.kt @@ -8,6 +8,9 @@ import com.droiddeck.launcher.input.PcKey import androidx.compose.ui.res.stringResource import android.view.KeyEvent import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.collectIsHoveredAsState import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable @@ -69,6 +72,9 @@ fun PcKeyboard( sendKey: (Int, Boolean) -> Unit, onAndroidKeyboard: () -> Unit, onClose: () -> Unit, + heightFraction: Float? = null, + showButtons: Boolean = true, + hoverFeedback: Boolean = false, ) { val pal = LocalPalette.current val colors = MaterialTheme.colorScheme @@ -76,31 +82,40 @@ fun PcKeyboard( var capsOn by remember { mutableStateOf(false) } val firstKey = remember { FocusRequester() } val shifted = (mods[42] ?: MOD_OFF) != MOD_OFF || (mods[54] ?: MOD_OFF) != MOD_OFF + // Keys go to wherever sendKey points now, but a held key is let go where it went down. + val currentSend by androidx.compose.runtime.rememberUpdatedState(sendKey) + val heldAt = remember { mutableMapOf Unit>() } + fun down(code: Int) { + val send = currentSend + heldAt[code] = send + send(code, true) + } + fun up(code: Int) = (heldAt.remove(code) ?: currentSend)(code, false) fun releaseOnceModifiers() { - for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { sendKey(code, false); mods[code] = MOD_OFF } + for ((code, state) in mods.toMap()) if (state == MOD_ONCE) { up(code); mods[code] = MOD_OFF } } fun press(key: PcKey) { if (key.code in PC_MODIFIERS) { when (mods[key.code] ?: MOD_OFF) { - MOD_OFF -> { sendKey(key.code, true); mods[key.code] = MOD_ONCE } + MOD_OFF -> { down(key.code); mods[key.code] = MOD_ONCE } MOD_ONCE -> mods[key.code] = MOD_LOCKED - else -> { sendKey(key.code, false); mods[key.code] = MOD_OFF } + else -> { up(key.code); mods[key.code] = MOD_OFF } } return } - sendKey(key.code, true) + down(key.code) } fun release(key: PcKey) { if (key.code in PC_MODIFIERS) return - sendKey(key.code, false) + up(key.code) if (key.code == 58) capsOn = !capsOn releaseOnceModifiers() } androidx.compose.runtime.DisposableEffect(Unit) { - onDispose { for ((code, state) in mods.toMap()) if (state != MOD_OFF) sendKey(code, false) } + onDispose { for (code in heldAt.keys.toList()) up(code) } } - LaunchedEffect(Unit) { runCatching { firstKey.requestFocus() } } + LaunchedEffect(Unit) { if (!hoverFeedback) runCatching { firstKey.requestFocus() } } val prefsContext = LocalContext.current remember { PcKeyboardPrefs.load(prefsContext) } @@ -108,7 +123,7 @@ fun PcKeyboard( val rows = PC_KEY_ROWS.map { row -> row.filter { it.code !in hiddenCodes } }.filter { it.isNotEmpty() } BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { - val rowHeight = ((maxHeight * (PcKeyboardPrefs.size / 100f) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size) + val rowHeight = ((maxHeight * (heightFraction ?: (PcKeyboardPrefs.size / 100f)) - 24.dp - 3.dp * rows.size - 10.dp) / rows.size) .coerceIn(20.dp, 56.dp) Box( Modifier.fillMaxWidth() @@ -122,9 +137,11 @@ fun PcKeyboard( Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(24.dp)) { Text(stringResource(R.string.drawer_pc_keyboard), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant) Spacer(Modifier.weight(1f)) - HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard) - Spacer(Modifier.width(8.dp)) - HeaderButton(stringResource(R.string.pckb_hide), onClose) + if (showButtons) { + HeaderButton(stringResource(R.string.pckb_android), onAndroidKeyboard) + Spacer(Modifier.width(8.dp)) + HeaderButton(stringResource(R.string.pckb_hide), onClose) + } } rows.forEachIndexed { r, row -> Row(horizontalArrangement = Arrangement.spacedBy(3.dp), modifier = Modifier.fillMaxWidth().height(rowHeight)) { @@ -139,7 +156,7 @@ fun PcKeyboard( } key(key.code) { KeyCap( - label, key.weight, lit, locked = state == MOD_LOCKED, + label, key.weight, lit, locked = state == MOD_LOCKED, hoverFeedback = hoverFeedback, modifier = if (r == 0 && i == 0) Modifier.focusRequester(firstKey) else Modifier, onDown = { press(key) }, onUp = { release(key) }, ) @@ -154,25 +171,35 @@ fun PcKeyboard( @Composable private fun RowScope.KeyCap( - label: String, weight: Float, lit: Boolean, locked: Boolean, + label: String, weight: Float, lit: Boolean, locked: Boolean, hoverFeedback: Boolean, modifier: Modifier, onDown: () -> Unit, onUp: () -> Unit, ) { val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val focused by src.collectIsFocusedAsState() + val hovered by src.collectIsHoveredAsState() + val (pointedAt, laser) = com.droiddeck.launcher.session.xr.rememberXrPointed() + val pointed = hoverFeedback && (hovered || laser.value) var down by remember { mutableStateOf(false) } val fill by animateColorAsState( when { down -> pal.signal.copy(alpha = 0.55f) lit -> pal.signal.copy(alpha = if (locked) 0.45f else 0.28f) + pointed -> Color.White.copy(alpha = 0.2f) else -> Color.White.copy(alpha = 0.07f) - }, Motion.tw(160), label = "keyFill", + }, Motion.tw(if (down) 40 else 160), label = "keyFill", + ) + val scale by animateFloatAsState( + if (!hoverFeedback) 1f else if (down) 0.9f else if (pointed) 1.06f else 1f, Motion.tw(if (down) 40 else 140), label = "keyScale", ) Box( contentAlignment = Alignment.Center, modifier = modifier.weight(weight).fillMaxHeight() + .then(pointedAt) + .graphicsLayer { scaleX = 1f + (scale - 1f) * size.height / size.width; scaleY = scale } .background(fill, RoundedCornerShape(7.dp)) - .glideBorder(focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f)) + .glideBorder(if (hoverFeedback) pointed || down else focused, RoundedCornerShape(7.dp), pal.signal, if (lit) pal.signal.copy(alpha = 0.7f) else Color.White.copy(alpha = 0.12f)) + .then(if (hoverFeedback) Modifier.hoverable(src) else Modifier) .pointerInput(Unit) { awaitEachGesture { awaitFirstDown().consume() diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt new file mode 100644 index 0000000000..525de1aefb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrGestureTest.kt @@ -0,0 +1,53 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class XrGestureTest { + private fun hand(x: Float, active: Boolean = true) = + XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.2f, -0.3f)), 0f, 0f, 0f, 0f, 0, active) + + @Test + fun holdingTheControllersTogetherFiresAfterTheHold() { + val gesture = XrGesture() + assertFalse(gesture.update(hand(-0.03f), hand(0.03f), 0)) + assertEquals(XrGesture.Phase.ARMING, gesture.phase) + assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS / 2)) + assertEquals(0.5f, gesture.progress, 0.01f) + assertEquals(0f, gesture.midpoint.x, 1e-6f) + assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS)) + } + + @Test + fun pullingApartCancels() { + val gesture = XrGesture() + gesture.update(hand(-0.03f), hand(0.03f), 0) + gesture.update(hand(-0.06f), hand(0.06f), 500) + assertEquals(XrGesture.Phase.ARMING, gesture.phase) + gesture.update(hand(-0.08f), hand(0.08f), 600) + assertEquals(XrGesture.Phase.IDLE, gesture.phase) + assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS + 600)) + assertEquals(0f, gesture.progress, 0f) + } + + @Test + fun itDoesNotFireAgainUntilTheControllersPart() { + val gesture = XrGesture() + gesture.update(hand(-0.03f), hand(0.03f), 0) + assertTrue(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS)) + for (t in 1..5) assertFalse(gesture.update(hand(-0.03f), hand(0.03f), XrGesture.HOLD_MS * (t + 1))) + gesture.update(hand(-0.2f), hand(0.2f), 20_000) + gesture.update(hand(-0.03f), hand(0.03f), 21_000) + assertTrue(gesture.update(hand(-0.03f), hand(0.03f), 21_000 + XrGesture.HOLD_MS)) + } + + @Test + fun aLostControllerStopsIt() { + val gesture = XrGesture() + gesture.update(hand(-0.03f), hand(0.03f), 0) + assertFalse(gesture.update(hand(-0.03f), hand(0.03f, active = false), XrGesture.HOLD_MS)) + assertEquals(XrGesture.Phase.IDLE, gesture.phase) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt new file mode 100644 index 0000000000..8a8c50c02c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrHostTest.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class XrHostTest { + private fun buffer(size: Int) = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()) + + @Test + fun readsHandsAtTheNativeOffsets() { + val state = buffer(XrHostLayout.STATE_SIZE) + state.putInt(8, XrHostLayout.FLAG_FOCUSED or XrHostLayout.FLAG_SURFACE_SWAPCHAIN) + state.putLong(16, 42L) + XrHost.writePose(state, XrHostLayout.STATE_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f))) + val right = XrHostLayout.STATE_HANDS + XrHostLayout.HAND_SIZE + XrHost.writePose(state, right + XrHostLayout.HAND_AIM, Pose(Quat.IDENTITY, Vec3(0.2f, 1.2f, -0.3f))) + state.putFloat(right + XrHostLayout.HAND_TRIGGER, 0.75f) + state.putFloat(right + XrHostLayout.HAND_STICK + 4, -0.5f) + state.putInt(right + XrHostLayout.HAND_BUTTONS, XrHostLayout.SECONDARY_CLICK) + state.putInt(right + XrHostLayout.HAND_ACTIVE, 1) + + val frame = XrHost(state, buffer(XrHostLayout.CONTROL_SIZE)).read() + + assertTrue(frame.focused) + assertTrue(frame.surfaces) + assertEquals(42L, frame.frame) + assertEquals(1.6f, frame.head.position.y, 0f) + assertFalse(frame.hands[0].active) + val hand = frame.hands[1] + assertTrue(hand.active) + assertTrue(hand.secondary) + assertEquals(0.75f, hand.trigger, 0f) + assertEquals(-0.5f, hand.stickY, 0f) + assertEquals(Vec3(0.2f, 1.2f, -0.3f), hand.aim.position) + } + + @Test + fun writesControlAtTheNativeOffsets() { + val control = buffer(XrHostLayout.CONTROL_SIZE) + val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control) + val out = XrControlOut().apply { + masks[1] = true + lasers[1] = 0.8f + haptics[0] = XrHaptic(20, 0.5f) + orb = XrControlOut.Orb(Vec3(0f, 1f, -0.5f), 0.04f, 0.25f, 0f) + layers += XrLayerOut(3, Pose(Quat.IDENTITY, Vec3(0f, 1.5f, -1f)), 0.9f, 0.6f, order = 2) + } + host.write(out) + + assertEquals(XrHostLayout.VERSION, control.getInt(0)) + val right = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_SIZE + assertEquals(XrHostLayout.MASK_INPUT, control.getInt(right)) + assertEquals(0.8f, control.getFloat(right + XrHostLayout.HAND_CONTROL_LASER), 0f) + assertEquals(0, control.getInt(XrHostLayout.CONTROL_HANDS)) + val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC + assertEquals(1L, control.getLong(haptic)) + assertEquals(20_000_000L, control.getLong(haptic + 8)) + assertEquals(1, control.getInt(XrHostLayout.CONTROL_ORB)) + assertEquals(0.25f, control.getFloat(XrHostLayout.CONTROL_ORB + 4), 0f) + val layer = XrHostLayout.CONTROL_LAYERS + assertEquals(3, control.getInt(layer)) + assertEquals(1, control.getInt(layer + 4)) + assertEquals(2, control.getInt(layer + 12)) + assertEquals(-1f, control.getFloat(layer + 16 + 24), 0f) + assertEquals(0.9f, control.getFloat(layer + 48), 0f) + assertEquals(-1, control.getInt(layer + XrHostLayout.LAYER_SIZE)) + } + + @Test + fun aHapticIsSentOnceAndTheNextGetsANewId() { + val control = buffer(XrHostLayout.CONTROL_SIZE) + val host = XrHost(buffer(XrHostLayout.STATE_SIZE), control) + val haptic = XrHostLayout.CONTROL_HANDS + XrHostLayout.HAND_CONTROL_HAPTIC + host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) }) + host.write(XrControlOut()) + assertEquals(1L, control.getLong(haptic)) + host.write(XrControlOut().apply { haptics[0] = XrHaptic(10, 0.3f) }) + assertEquals(2L, control.getLong(haptic)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt new file mode 100644 index 0000000000..92ee0cdfb3 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrInteractionTest.kt @@ -0,0 +1,246 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class XrInteractionTest { + private val head = Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)) + + /** A panel 1 m ahead facing the user, 1 m wide and 0.6 m high. */ + private fun panel(kind: XrPanelKind = XrPanelKind.MENU, z: Float = -1f) = + XrPanelState(kind, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, z)), 1f, 0.6f) + + /** A controller at the head's height pointing straight ahead at ([x], [y]) on the panel's plane. */ + private fun aim(x: Float = 0f, y: Float = 0f, trigger: Float = 0f, squeeze: Float = 0f, stickY: Float = 0f, + buttons: Int = 0, active: Boolean = true) = + XrHand(Pose(), Pose(Quat.IDENTITY, Vec3(x, 1.6f + y, 0f)), trigger, squeeze, 0f, stickY, buttons, active) + + private val idle = XrHand.IDLE + + @Test + fun aRayHitsThePanelInItsPixels() { + val panel = panel() + val hit = panel.hit(aim(0.25f, 0.15f).aim) + assertNotNull(hit) + assertEquals(1f, hit!!.distance, 1e-4f) + assertEquals(panel.pixelWidth * 0.75f, panel.pixelX(hit.x), 0.5f) + assertEquals(panel.pixelHeight * 0.25f, panel.pixelY(hit.y), 0.5f) + assertNull(panel.hit(aim(0.7f).aim)) + } + + @Test + fun aPanelBehindTheControllerOrSeenFromBehindIsMissed() { + assertNull(panel(z = 1f).hit(aim().aim)) + val turned = XrPanelState(XrPanelKind.MENU, Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, -1f)), 1f, 0.6f) + assertNull(turned.hit(aim().aim)) + } + + @Test + fun theNearestPanelTakesTheRay() { + val far = panel(z = -2f) + val near = panel(z = -1f) + val out = XrInteraction().update(head, listOf(aim(trigger = 0f), idle), listOf(far, near), 0.014f) + assertTrue(out.cursors.containsKey(near)) + assertFalse(out.cursors.containsKey(far)) + } + + @Test + fun onlyTheControllerPointingAtAPanelIsTakenFromTheGame() { + val panel = panel() + val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true) + val out = XrInteraction().update(head, listOf(away, aim()), listOf(panel), 0.014f) + assertFalse(out.masks[0]) + assertEquals(0f, out.lasers[0], 0f) + assertTrue(out.masks[1]) + assertEquals(1f, out.lasers[1], 1e-4f) + } + + @Test + fun theTriggerPressesMovesAndReleases() { + val panel = panel() + val interaction = XrInteraction() + val down = interaction.update(head, listOf(aim(0f, 0f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(down.events.single() is XrPointerEvent.Down) + val moved = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.5f), idle), listOf(panel), 0.014f) + assertTrue(moved.events.single() is XrPointerEvent.Move) + assertTrue(moved.masks[0]) + val up = interaction.update(head, listOf(aim(0.1f, 0f, trigger = 0.1f), idle), listOf(panel), 0.014f) + val release = up.events.single() as XrPointerEvent.Up + assertEquals(panel.pixelWidth * 0.6f, release.x, 0.5f) + } + + @Test + fun aHeldPressFollowsTheRayOffThePanelAndAlostControllerCancels() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val off = interaction.update(head, listOf(aim(0.9f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue((off.events.single() as XrPointerEvent.Move).x >= panel.pixelWidth - 0.5f) + assertTrue(off.masks[0]) + val lost = interaction.update(head, listOf(aim(active = false), idle), listOf(panel), 0.014f) + assertTrue(lost.events.single() is XrPointerEvent.Cancel) + } + + @Test + fun theStickScrollsAndBGoesBack() { + val panel = panel() + val interaction = XrInteraction() + val scroll = interaction.update(head, listOf(aim(stickY = 1f), idle), listOf(panel), 0.1f) + assertTrue((scroll.events.single() as XrPointerEvent.Scroll).amount > 0f) + val back = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f) + assertTrue(back.events.single() is XrPointerEvent.Back) + val held = interaction.update(head, listOf(aim(buttons = XrHostLayout.SECONDARY_CLICK), idle), listOf(panel), 0.014f) + assertTrue(held.events.isEmpty()) + } + + @Test + fun gripCarriesThePanelAndTheStickPushesItAway() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(squeeze = 0.9f), idle), listOf(panel), 0.014f) + interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(0.3f, panel.pose.position.x, 1e-4f) + assertEquals(1.7f, panel.pose.position.y, 1e-4f) + val before = panel.pose.position.z + repeat(10) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) } + assertTrue(panel.pose.position.z < before) + repeat(200) { interaction.update(head, listOf(aim(0.3f, 0.1f, squeeze = 0.9f, stickY = 1f), idle), listOf(panel), 0.1f) } + assertTrue((panel.pose.position - Vec3(0.3f, 1.7f, 0f)).length <= XrUnits.MAX_DISTANCE + 1e-3f) + val dropped = interaction.update(head, listOf(aim(0.3f, 0.1f), idle), listOf(panel), 0.014f) + assertTrue(dropped.events.single() is XrPointerEvent.Moved) + val facingHead = panel.pose.orientation.rotate(Vec3(0f, 0f, 1f)) + val toHead = (head.position - panel.pose.position).let { Vec3(it.x, 0f, it.z).normalized() } + assertEquals(1f, facingHead dot toHead, 1e-3f) + } + + @Test + fun theBottomBarCarriesThePanelButItsButtonIsClicked() { + val panel = panel() + val interaction = XrInteraction() + val barY = -0.3f + XrUnits.BAR_METRES / 2f + val bar = interaction.update(head, listOf(aim(0.1f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(bar.events.isEmpty()) + interaction.update(head, listOf(aim(0.2f, barY, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(0.1f, panel.pose.position.x, 1e-4f) + interaction.update(head, listOf(aim(0.2f, barY), idle), listOf(panel), 0.014f) + + val chat = panel(XrPanelKind.PET_CHAT) + val button = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(chat), 0.014f) + assertTrue(button.events.single() is XrPointerEvent.Down) + + val menu = panel() + val noButton = XrInteraction().update(head, listOf(aim(-0.48f, barY, trigger = 0.9f), idle), listOf(menu), 0.014f) + assertTrue(noButton.events.isEmpty()) + } + + @Test + fun theCornerResizesWithTheTopLeftCornerFixed() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(1f, panel.width, 1e-4f) + assertEquals(0.6f, panel.height, 1e-4f) + interaction.update(head, listOf(aim(0.78f, -0.48f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(1.3f, panel.width, 1e-3f) + assertEquals(0.8f, panel.height, 1e-3f) + assertEquals(-0.5f, panel.pose.position.x - panel.width / 2f, 1e-3f) + assertEquals(1.9f, panel.pose.position.y + panel.height / 2f, 1e-3f) + interaction.update(head, listOf(aim(-2f, 2f, trigger = 0.9f), idle), listOf(panel), 0.014f) + assertEquals(XrUnits.MIN_METRES, panel.width, 1e-4f) + assertEquals(XrUnits.MIN_METRES, panel.height, 1e-4f) + val done = interaction.update(head, listOf(aim(-2f, 2f), idle), listOf(panel), 0.014f) + assertTrue(done.events.single() is XrPointerEvent.Resized) + } + + @Test + fun thePetHeadClicksOrIsDragged() { + val head0 = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f) + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f) + val click = interaction.update(head, listOf(aim(), idle), listOf(head0), 0.014f) + assertTrue(click.events.single() is XrPointerEvent.Click) + + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(head0), 0.014f) + interaction.update(head, listOf(aim(0.05f, trigger = 0.9f), idle), listOf(head0), 0.014f) + interaction.update(head, listOf(aim(0.2f, trigger = 0.9f), idle), listOf(head0), 0.014f) + assertEquals(0.2f, head0.pose.position.x, 1e-3f) + val dropped = interaction.update(head, listOf(aim(0.2f), idle), listOf(head0), 0.014f) + assertTrue(dropped.events.single() is XrPointerEvent.Moved) + } + + @Test + fun aClosingPanelLetsGo() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val out = XrInteractionOut() + interaction.release(panel, out) + assertTrue(out.events.single() is XrPointerEvent.Cancel) + assertFalse(interaction.holding(panel)) + } + + @Test + fun aReleaseAimedAwayFromThePanelCancels() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true) + val out = interaction.update(head, listOf(away, idle), listOf(panel), 0.014f) + assertTrue(out.events.single() is XrPointerEvent.Cancel) + } + + @Test + fun aPanelOneControllerHoldsCannotBeTakenByTheOther() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), idle), listOf(panel), 0.014f) + interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(squeeze = 0.9f)), listOf(panel), 0.014f) + val out = interaction.update(head, listOf(aim(0.48f, -0.28f, trigger = 0.9f), aim(0.3f, squeeze = 0.9f)), listOf(panel), 0.014f) + assertEquals(0f, panel.pose.position.x, 1e-3f) + assertTrue(out.events.isEmpty()) + } + + @Test + fun losingFocusCancelsAndAButtonStillHeldNeedsANewPress() { + val panel = panel() + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + val out = XrInteractionOut() + interaction.cancel(out) + assertTrue(out.events.single() is XrPointerEvent.Cancel) + assertFalse(interaction.holding(panel)) + val stillHeld = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(stillHeld.events.isEmpty()) + interaction.update(head, listOf(aim(), idle), listOf(panel), 0.014f) + val pressed = interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(panel), 0.014f) + assertTrue(pressed.events.single() is XrPointerEvent.Down) + } + + @Test + fun bothControllersPressOnePanelAtOnce() { + val panel = panel() + val interaction = XrInteraction() + val first = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f) + assertEquals(2, first.cursors.getValue(panel).size) + assertEquals(0, (first.events.single() as XrPointerEvent.Down).hand) + val second = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f, trigger = 0.9f)), listOf(panel), 0.014f) + assertEquals(1, (second.events.single() as XrPointerEvent.Down).hand) + val up = interaction.update(head, listOf(aim(-0.2f, trigger = 0.9f), aim(0.2f)), listOf(panel), 0.014f) + assertEquals(1, (up.events.single() as XrPointerEvent.Up).hand) + } + + @Test + fun lettingGoOfThePetHeadOffItIsNoClick() { + val pet = XrPanelState(XrPanelKind.PET_HEAD, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, -1f)), 0.12f, 0.12f) + val interaction = XrInteraction() + interaction.update(head, listOf(aim(trigger = 0.9f), idle), listOf(pet), 0.014f) + val away = XrHand(Pose(), Pose(Quat.yaw(Math.PI.toFloat()), Vec3(0f, 1.6f, 0f)), 0f, 0f, 0f, 0f, 0, true) + val out = interaction.update(head, listOf(away, idle), listOf(pet), 0.014f) + assertTrue(out.events.isEmpty()) + assertFalse(interaction.holding(pet)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt new file mode 100644 index 0000000000..0ddd9b33ab --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPanelsGateTest.kt @@ -0,0 +1,113 @@ +package com.droiddeck.launcher.session.xr + +import android.content.Context +import android.view.Surface +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowBuild +import java.nio.ByteBuffer + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE) +class XrPanelsGateTest { + private val layers = object : XrLayerSource { + override val context: Context get() = RuntimeEnvironment.getApplication() + override fun createLayer(width: Int, height: Int) = -1 + override fun layerSurface(id: Int): Surface? = null + override fun destroyLayer(id: Int) = Unit + override fun setOrbImage(image: android.graphics.Bitmap) = Unit + override fun leave() = Unit + } + + private fun attach() = XrPanels.attach( + layers, ByteBuffer.allocateDirect(XrHostLayout.STATE_SIZE), ByteBuffer.allocateDirect(XrHostLayout.CONTROL_SIZE), + ) + + @After + fun detach() = XrPanels.detach() + + @Test + fun onlyAQuestInTheImmersiveViewOpensTheGate() { + assertTrue(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = true)) + assertTrue(XrPanels.gateOpen("Quest 3S", "panther", "Oculus", immersive = true)) + assertFalse(XrPanels.gateOpen("Quest 3", "eureka", "Oculus", immersive = false)) + assertFalse(XrPanels.gateOpen("BKQ_N49", "BKQ", "HONOR", immersive = true)) + assertFalse(XrPanels.gateOpen("Pixel 9", "tokay", "Google", immersive = true)) + assertFalse(XrPanels.gateOpen("Rift", "rift", "Oculus", immersive = true)) + } + + @Test + fun offQuestTheMenuStaysInTheSessionWindow() { + ShadowBuild.setModel("BKQ_N49") + ShadowBuild.setDevice("BKQ") + ShadowBuild.setManufacturer("HONOR") + attach() + assertFalse(XrPanels.immersiveActive) + assertFalse(XrPanels.showMenu()) + } + + @Test + fun onQuestTheImmersiveViewTakesTheMenu() { + ShadowBuild.setModel("Quest 3") + ShadowBuild.setDevice("eureka") + ShadowBuild.setManufacturer("Oculus") + assertFalse(XrPanels.showMenu()) + attach() + assertTrue(XrPanels.immersiveActive) + assertTrue(XrPanels.showMenu()) + XrPanels.detach() + assertFalse(XrPanels.immersiveActive) + assertFalse(XrPanels.showMenu()) + } + + private class Host : XrMenuHost { + val immersive = mutableListOf() + @androidx.compose.runtime.Composable + override fun XrMenuContent() = Unit + override fun xrSetMenuOpen(open: Boolean) = Unit + override fun xrMenuBack() = Unit + override fun xrSendKey(code: Int, down: Boolean) = Unit + override fun xrTypeText(text: String) = Unit + override fun xrTapKey(keyCode: Int) = Unit + override fun xrImmersiveChanged(active: Boolean) { immersive += active } + } + + @Test + fun aFocusChangeInTheImmersiveViewSizesSteamsScreenAgain() { + ShadowBuild.setModel("Quest 3") + ShadowBuild.setDevice("eureka") + ShadowBuild.setManufacturer("Oculus") + val host = Host() + XrPanels.setMenuHost(host) + try { + attach() + settle() + val opened = host.immersive.size + assertTrue(opened >= 1 && host.immersive.all { it }) + com.droiddeck.launcher.agent.AgentGuest.focusRevision++ + settle() + assertTrue(host.immersive.size > opened) + assertTrue(host.immersive.all { it }) + XrPanels.detach() + val left = host.immersive.size + com.droiddeck.launcher.agent.AgentGuest.focusRevision++ + settle() + assertEquals(false, host.immersive.last()) + assertEquals(left, host.immersive.size) + } finally { + XrPanels.clearMenuHost(host) + } + } + + private fun settle() { + androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications() + org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt new file mode 100644 index 0000000000..89b35ee470 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPcTextTest.kt @@ -0,0 +1,72 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Test + +class XrPcTextTest { + private class Field : XrKeyTarget { + val text = StringBuilder() + var entered = 0 + override fun type(text: String) { this.text.append(text) } + override fun backspace() { if (text.isNotEmpty()) text.setLength(text.length - 1) } + override fun enter() { entered++ } + } + + private fun XrPcText.tap(code: Int) { key(code, true); key(code, false) } + + @Test + fun pcKeysTypeIntoAPanelField() { + val field = Field() + val keys = XrPcText(field) + keys.key(42, true); keys.tap(35); keys.key(42, false) + keys.tap(18); keys.tap(57); keys.key(54, true); keys.tap(2); keys.key(54, false) + assertEquals("He !", field.text.toString()) + keys.tap(58); keys.tap(30); keys.tap(58); keys.tap(30) + assertEquals("He !Aa", field.text.toString()) + keys.tap(14); keys.tap(28) + assertEquals("He !A", field.text.toString()) + assertEquals(1, field.entered) + } + + private class FakeTimer : XrTimer { + var pending: (() -> Unit)? = null + override fun after(ms: Long, action: () -> Unit): () -> Unit { + pending = action + return { if (pending === action) pending = null } + } + fun fire() = pending!!.invoke() + } + + @Test + fun holdingBackspaceKeepsDeletingUntilItIsLetGo() { + val field = Field().apply { text.append("hello") } + val timer = FakeTimer() + val keys = XrPcText(field, timer) + keys.key(14, true) + assertEquals("hell", field.text.toString()) + timer.fire(); timer.fire() + assertEquals("he", field.text.toString()) + keys.key(14, false) + assertEquals(null, timer.pending) + assertEquals("he", field.text.toString()) + } + + @Test + fun anotherKeyLetGoLeavesBackspaceRepeating() { + val field = Field().apply { text.append("hello") } + val timer = FakeTimer() + val keys = XrPcText(field, timer) + keys.key(14, true) + keys.key(30, false) + timer.fire() + assertEquals("hel", field.text.toString()) + } + + @Test + fun keysWithNoCharacterTypeNothing() { + val field = Field() + val keys = XrPcText(field) + for (code in listOf(1, 59, 29, 56, 103, 105, 15, 111)) keys.tap(code) + assertEquals("", field.text.toString()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt new file mode 100644 index 0000000000..6892d056e1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrPlacementTest.kt @@ -0,0 +1,67 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Test + +class XrPlacementTest { + @Test + fun aPanelComesBackAtTheSamePlaceRelativeToWhereTheUserFaces() { + val head = Pose(Quat.yaw(0.4f), Vec3(0.5f, 1.6f, 0.2f)) + val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.3f, distance = 1.1f, dy = -0.2f) + val (yaw, distance, dy) = XrPlacement.relative(head, placed.position) + assertEquals(0.3f, yaw, 1e-4f) + assertEquals(1.1f, distance, 1e-4f) + assertEquals(-0.2f, dy, 1e-4f) + + val turned = Pose(Quat.yaw(1.4f), Vec3(-1f, 1.5f, 3f)) + val again = XrPlacement.place(XrPanelKind.MENU, turned, yaw, distance, dy) + val (yaw2, distance2, dy2) = XrPlacement.relative(turned, again.position) + assertEquals(yaw, yaw2, 1e-4f) + assertEquals(distance, distance2, 1e-4f) + assertEquals(dy, dy2, 1e-4f) + } + + @Test + fun aPlacedPanelFacesTheHead() { + val head = Pose(Quat.yaw(-0.8f), Vec3(0f, 1.6f, 0f)) + val placed = XrPlacement.place(XrPanelKind.MENU, head, yaw = 0.5f, distance = 0.9f, dy = 0f) + val front = placed.orientation.rotate(Vec3(0f, 0f, 1f)) + val toHead = (head.position - placed.position).normalized() + assertEquals(1f, front dot toHead, 1e-4f) + } + + @Test + fun straightAheadIsStraightAhead() { + val placed = XrPlacement.place(XrPanelKind.MENU, Pose(Quat.IDENTITY, Vec3(0f, 1.6f, 0f)), 0f, 1f, 0f) + assertEquals(0f, placed.position.x, 1e-5f) + assertEquals(-1f, placed.position.z, 1e-5f) + } + + @Test + fun theKeyboardLeansBackLikeOneOnADeskAndStillTakesTheLaser() { + val head = Pose(Quat.yaw(0.6f), Vec3(0f, 1.6f, 0f)) + val placed = XrPlacement.place(XrPanelKind.KEYBOARD, head, yaw = 0f, distance = 0.5f, dy = -0.5f) + val front = placed.orientation.rotate(Vec3(0f, 0f, 1f)) + val level = (head.position - placed.position).let { Vec3(it.x, 0f, it.z).normalized() } + assertEquals(0.7071f, front.y, 1e-3f) + assertEquals(0.7071f, front dot level, 1e-3f) + + val keyboard = XrPanelState(XrPanelKind.KEYBOARD, placed, 0.8f, 0.36f) + val hand = placed.position + Vec3(0f, 0.25f, 0f) + level * 0.15f + val down = (placed.position - hand).normalized() + val aim = Pose(rotationFromForward(down), hand) + val hit = keyboard.hit(aim) + assertNotNull(hit) + assertEquals(0f, hit!!.x, 1e-3f) + assertEquals(0f, hit.y, 1e-3f) + } + + private fun rotationFromForward(direction: Vec3): Quat { + val axis = Vec3.FORWARD cross direction + val angle = kotlin.math.acos((Vec3.FORWARD dot direction).coerceIn(-1f, 1f)) + val unit = axis.normalized() + val s = kotlin.math.sin(angle / 2f) + return Quat(unit.x * s, unit.y * s, unit.z * s, kotlin.math.cos(angle / 2f)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt new file mode 100644 index 0000000000..2829772d20 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/xr/XrSteamScreenTest.kt @@ -0,0 +1,23 @@ +package com.droiddeck.launcher.session.xr + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class XrSteamScreenTest { + @Test fun steamAndSteamVrAloneAreSteamsScreen() { + assertTrue(XrSteamScreen.shown(250820L, listOf(769L, 250820L))) + assertTrue(XrSteamScreen.shown(0L, listOf(769L))) + } + + @Test fun aRunningGameKeepsItFlatEvenWithSteamVrFocused() { + assertFalse(XrSteamScreen.shown(250820L, listOf(769L, 250820L, 1245620L))) + assertFalse(XrSteamScreen.shown(1245620L, null)) + } + + @Test fun aReportWithNoFocusIsUnknown() { + assertFalse(XrSteamScreen.shown(null, null)) + assertFalse(XrSteamScreen.shown(null, emptyList())) + assertFalse(XrSteamScreen.shown(0L, emptyList())) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt new file mode 100644 index 0000000000..c838ed1bf5 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetQuestTest.kt @@ -0,0 +1,24 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], manifest = Config.NONE) +class AgentPetQuestTest { + @Test + fun phonesKeepTheFloatingPetAndItsChat() { + assertTrue(AgentPet.usesOverlayWindows(quest = false)) + assertFalse(AgentPet.chatInOwnWindow(quest = false)) + } + + @Test + fun questUsesNoOverlayWindowsAndOpensTheChatAsItsOwnPanel() { + assertFalse(AgentPet.usesOverlayWindows(quest = true)) + assertTrue(AgentPet.chatInOwnWindow(quest = true)) + } +} diff --git a/tools/release/sign-apk.sh b/tools/release/sign-apk.sh index 0373e80ee5..a5c18a91dc 100755 --- a/tools/release/sign-apk.sh +++ b/tools/release/sign-apk.sh @@ -28,7 +28,7 @@ else python3 "$here/axml_rename.py" "$in" "$work/renamed.apk" \ "$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \ "$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \ - "$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \ + "$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" "$P.agentchat=$pkg.agentchat" \ "$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \ "$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" fi From e935263ccbefbe6a06324091425c471c1c633ecf Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:36:49 -0500 Subject: [PATCH 17/80] Include IBus in the Ubuntu runtime (#3624) Ship the IBus daemon, client, and Python bindings required for Steam pinyin. Verify these dependencies during runtime assembly. --- tools/ubuntu/packages-runtime.txt | 3 +++ tools/ubuntu/protected-runtime.txt | 3 +++ tools/ubuntu/setup.sh | 10 ++++++++++ 3 files changed, 16 insertions(+) diff --git a/tools/ubuntu/packages-runtime.txt b/tools/ubuntu/packages-runtime.txt index c6bcd3618e..95269a035b 100644 --- a/tools/ubuntu/packages-runtime.txt +++ b/tools/ubuntu/packages-runtime.txt @@ -28,12 +28,14 @@ gamescope gir1.2-flatpak-1.0 gir1.2-glib-2.0 gir1.2-gtk-3.0 +gir1.2-ibus-1.0 gnu-coreutils gnupg-agent gpgv grep gzip hostname +ibus iproute2 iputils-ping less @@ -218,6 +220,7 @@ psmisc pulseaudio-utils python3 python3-gi +python3-ibus-1.0 python3-zstandard sed sensible-utils diff --git a/tools/ubuntu/protected-runtime.txt b/tools/ubuntu/protected-runtime.txt index 6462252206..fabadc3d0a 100644 --- a/tools/ubuntu/protected-runtime.txt +++ b/tools/ubuntu/protected-runtime.txt @@ -6,6 +6,8 @@ dpkg flatpak fontconfig gamescope +gir1.2-ibus-1.0 +ibus libegl-mesa0 libgl1-mesa-dri libluajit-5.1-2 @@ -16,4 +18,5 @@ mesa-libgallium mesa-vulkan-drivers python3 python3-gi +python3-ibus-1.0 xwayland diff --git a/tools/ubuntu/setup.sh b/tools/ubuntu/setup.sh index a2b0d63e66..0a673b3101 100755 --- a/tools/ubuntu/setup.sh +++ b/tools/ubuntu/setup.sh @@ -103,6 +103,15 @@ record_apt_state() { done > /usr/share/droiddeck/apt/system-sources.txt } +verify_ibus_runtime() { + local path + for path in /usr/bin/ibus /usr/bin/ibus-daemon /usr/libexec/ibus-dconf; do + [ -x "$path" ] || { printf 'Missing executable required for Steam IBus: %s\n' "$path" >&2; return 1; } + done + /usr/bin/ibus-daemon --version + /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0"); from gi.repository import IBus; assert IBus.Bus' +} + finish() { sed -i 's/^Types: deb deb-src$/Types: deb/' /etc/apt/sources.list.d/ubuntu.sources record_apt_state @@ -133,6 +142,7 @@ if [ "$stage" = runtime ]; then grep -v '^$' "$here/packages-runtime.txt" | xargs apt-get install -y --no-install-recommends install_held + verify_ibus_runtime build_package droiddeck-runtime "$here/overlay-runtime" "$here/protected-runtime.txt" "DroidDeck's Ubuntu runtime" update-alternatives --install /usr/bin/sudo sudo /usr/local/bin/sudo 1000 From eeb10e02fde9382b3299ed79bad11d10d7758863 Mon Sep 17 00:00:00 2001 From: danyi Date: Thu, 3 Dec 2026 12:36:55 +0000 Subject: [PATCH 18/80] Restore Chinese input for Android and Steam keyboards (#1529) Commit Android IME text through the focused renderer and submit only after delivery is confirmed. Restore Steam pinyin on Ubuntu rc7 and allow older runtimes to start normally without IBus. --- app/src/main/cpp/waylandcomp/src/compositor.c | 32 +- .../main/cpp/waylandcomp/src/droiddeck_ext.c | 200 +++- .../main/cpp/waylandcomp/src/droiddeck_ext.h | 14 +- .../cpp/waylandcomp/src/waylandcomp_jni.c | 44 + .../main/cpp/waylandcomp/src/wl_text_input.c | 39 +- .../com/droiddeck/launcher/SessionActivity.kt | 60 +- .../com/droiddeck/launcher/input/HeldInput.kt | 18 +- .../droiddeck/launcher/input/KeyboardHost.kt | 178 +++- .../launcher/input/SessionTextInput.kt | 327 +++++++ .../launcher/session/BottomDesktop.kt | 13 + .../launcher/session/SessionFiles.kt | 42 + .../launcher/ui/BottomDesktopPanel.kt | 6 +- .../launcher/ui/SecondScreenPresentation.kt | 20 +- .../wayland/BottomDesktopCompositorService.kt | 2 +- .../launcher/wayland/WaylandCompositor.java | 39 + .../droiddeck/launcher/input/HeldInputTest.kt | 57 ++ .../launcher/input/KeyboardHostTest.kt | 471 ++++++++- .../launcher/input/SessionInputPointerTest.kt | 31 +- .../launcher/input/SessionTextInputTest.kt | 314 ++++++ .../session/BottomDesktopInputTest.kt | 94 ++ .../launcher/ui/SecondScreenImeTest.kt | 177 ++++ .../BottomDesktopCompositorInputTest.kt | 122 +++ docs/testing/chinese-input.md | 23 + tools/build_local.sh | 4 +- tools/components/recipes.json | 9 +- tools/components/recipes/runtime.sh | 2 + tools/docker_platform.sh | 2 +- tools/ime/packages.json | 27 + tools/ime/prepare.py | 230 +++++ tools/ime/smoke.py | 152 +++ .../usr/local/bin/droiddeck-desktop-clipboard | 18 +- .../overlay/usr/local/bin/droiddeck-session | 59 ++ .../overlay/usr/local/bin/droiddeck-steam-ime | 7 + .../usr/local/bin/droiddeck-text-input | 510 ++++++++++ tools/local-cross.Dockerfile | 2 +- tools/prepare_windows_runtime.py | 116 ++- tools/release/runtime_inputs.py | 6 +- tools/tests/test_ime_prepare.py | 134 +++ tools/tests/test_output_refresh.py | 7 +- tools/tests/test_prepare_windows_runtime.py | 346 ++++++- tools/tests/test_session_dbus.py | 199 ++++ tools/tests/test_steam_ime_runtime.py | 65 ++ tools/tests/test_text_input.py | 907 ++++++++++++++++++ tools/tests/test_wayland_host_order.py | 487 ++++++++++ tools/tests/test_windows_vr_build.py | 54 ++ tools/vr/build_windows.py | 20 +- 46 files changed, 5582 insertions(+), 104 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt create mode 100644 docs/testing/chinese-input.md create mode 100644 tools/ime/packages.json create mode 100644 tools/ime/prepare.py create mode 100644 tools/ime/smoke.py create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input create mode 100644 tools/tests/test_ime_prepare.py create mode 100644 tools/tests/test_session_dbus.py create mode 100644 tools/tests/test_steam_ime_runtime.py create mode 100644 tools/tests/test_text_input.py create mode 100644 tools/tests/test_wayland_host_order.py diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index cc01c63053..9339617e27 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -4582,11 +4583,15 @@ static void output_resized(void) { wl_display_flush_clients(g_display); } -static int on_input_readable(int fd, uint32_t mask, void *data) { +static void dispatch_input(int fd, int remaining) { struct input_msg m; int vsync = 0; int64_t vsync_ns = 0; - while (read(fd, &m, sizeof(m)) == (ssize_t)sizeof(m)) { + while (remaining != 0) { + ssize_t n = read(fd, &m, sizeof(m)); + if (n < 0 && errno == EINTR) continue; + if (n != (ssize_t)sizeof(m)) break; + if (remaining > 0) --remaining; switch (m.type) { case 1: deliver_key(&m); break; case 2: pointer_event(m.p1, m.p2, 0, 0); break; @@ -4628,9 +4633,27 @@ static int on_input_readable(int fd, uint32_t mask, void *data) { wl_display_flush_clients(g_display); } if (vsync) on_vsync(vsync_ns); +} + +static int on_input_readable(int fd, uint32_t mask, void *data) { + dispatch_input(fd, -1); return 0; } +void droiddeck_dispatch_pending_input(void) { + int fd = g_input_pipe[0]; + if (fd < 0) return; + + int bytes; + int result; + do { + result = ioctl(fd, FIONREAD, &bytes); + } while (result < 0 && errno == EINTR); + if (result == 0 && bytes >= (int)sizeof(struct input_msg)) { + dispatch_input(fd, bytes / (int)sizeof(struct input_msg)); + } +} + void droiddeck_wayland_set_scale_mode(int mode, int alignment) { if (g_input_pipe[1] < 0) { vk_present_set_scale_mode(mode, alignment); @@ -4767,6 +4790,11 @@ void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y) void droiddeck_inject_key(uint32_t evdev, int pressed) { key_event(evdev, pressed); } +int droiddeck_key_is_down(uint32_t evdev) { + return evdev < sizeof(g_keys_down) * 8 && + (g_keys_down[evdev >> 3] & (1u << (evdev & 7))) != 0; +} + static struct wl_event_source *g_stats_timer; volatile unsigned g_zero_copy_last; diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c index 1172c095b0..041f9c6c2b 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c @@ -4,12 +4,14 @@ #include #include #include +#include +#include #include #include "droiddeck_ext.h" #include "ahb_swapchain.h" #include "droiddeck_color.h" -enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT }; +enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD }; struct host_msg { enum host_kind kind; @@ -23,6 +25,32 @@ static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; static struct host_msg *g_head, *g_tail; static int g_wake[2] = {-1, -1}; +/* Compositor-thread-only fallback ordering state. */ +static int g_pending_token, g_pending_submit; +static int g_fallback_failed; +static int g_next_token = 1; +static struct host_msg *g_deferred_head, *g_deferred_tail; +static size_t g_deferred_count, g_deferred_bytes; +static int g_deferred_overflow; +static int g_completed_token, g_completed_result; + +#define DROIDDECK_EVDEV_KEY_MAX 768 +#define DROIDDECK_TEXT_DEFERRED_LIMIT 256 +#define DROIDDECK_TEXT_DEFERRED_BYTES (256 * 1024) +static unsigned char g_ordered_key_down[DROIDDECK_EVDEV_KEY_MAX]; + +void droiddeck_host_text_input_fallback_complete(int token, int result) { + pthread_mutex_lock(&g_mu); + g_completed_token = token; + g_completed_result = result; + pthread_mutex_unlock(&g_mu); + if (g_wake[1] >= 0) { + char c = 1; + ssize_t n = write(g_wake[1], &c, 1); + (void)n; + } +} + static void host_post(enum host_kind kind, const char *text, size_t len, int a, int b) { struct host_msg *m = calloc(1, sizeof(*m)); if (!m) return; @@ -51,6 +79,9 @@ void droiddeck_host_clipboard_text(const char *utf8, int len) { void droiddeck_host_text_commit(const char *utf8, int len) { host_post(HOST_TEXT_COMMIT, utf8, len > 0 ? (size_t)len : 0, 0, 0); } +void droiddeck_host_text_commit_and_submit(const char *utf8, int len) { + if (len > 0) host_post(HOST_TEXT_COMMIT, utf8, (size_t)len, 1, 0); +} void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) { host_post(HOST_TEXT_PREEDIT, utf8, len > 0 ? (size_t)len : 0, cursor_begin, cursor_end); } @@ -63,23 +94,173 @@ void droiddeck_host_zero_copy(int on, int live) { void droiddeck_host_hdr_output(int on) { host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0); } +void droiddeck_host_key(int evdev, int state) { + host_post(HOST_KEY, NULL, 0, evdev, state); +} + +void droiddeck_host_select_game_field(int copy) { + host_post(HOST_SELECT_GAME_FIELD, NULL, 0, copy, 0); +} + +static void tap_unheld_key(uint32_t key) { + if (droiddeck_key_is_down(key)) return; + droiddeck_inject_key(key, 1); + droiddeck_inject_key(key, 0); +} + +static void select_game_field(int copy) { + /* Apply pending raw releases before using the compositor's held-key state. */ + droiddeck_dispatch_pending_input(); + int temporary_ctrl = !droiddeck_key_is_down(KEY_LEFTCTRL) && !droiddeck_key_is_down(KEY_RIGHTCTRL); + if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 1); + tap_unheld_key(KEY_A); + if (copy) tap_unheld_key(KEY_C); + if (temporary_ctrl) droiddeck_inject_key(KEY_LEFTCTRL, 0); +} + +static void restore_deferred_to_front(void) { + if (g_deferred_head) { + g_deferred_tail->next = g_head; + if (!g_head) g_tail = g_deferred_tail; + g_head = g_deferred_head; + g_deferred_head = g_deferred_tail = NULL; + g_deferred_count = g_deferred_bytes = 0; + } +} + +/* Only suppress the queued submit for this commit, not a later commit or a held-key release. */ +static void discard_queued_submit(void) { + struct host_msg *prev = NULL; + struct host_msg *m = g_head; + int enter_held = g_ordered_key_down[KEY_ENTER]; + int key_pad_enter_held = g_ordered_key_down[KEY_KPENTER]; + while (m) { + int soft_submit = 0; + if (m->kind == HOST_TEXT_COMMIT) { + if (m->a || m->len == 0) break; + soft_submit = 1; + size_t i = 0; + for (; i < m->len; i++) { + char c = m->text[i]; + if (c != '\r' && c != '\n') soft_submit = 0; + if (c != '\r' && c != '\n' && c != '\b' && c != '\t' && c != 0x7f) break; + } + if (i != m->len) break; + } + struct host_msg *next = m->next; + int *held = m->a == KEY_ENTER ? &enter_held : m->a == KEY_KPENTER ? &key_pad_enter_held : NULL; + if (soft_submit || (m->kind == HOST_KEY && held && (m->b != 0 || !*held))) { + if (prev) prev->next = next; else g_head = next; + if (g_tail == m) g_tail = prev; + free(m->text); + free(m); + } else { + if (m->kind == HOST_KEY && held) *held = 0; + prev = m; + } + m = next; + } +} + +static int release_held_key(const struct host_msg *m) { + int k = m->a; + if (m->kind != HOST_KEY || m->b != 0 || k < 0 || k >= DROIDDECK_EVDEV_KEY_MAX || + !g_ordered_key_down[k]) return 0; + g_ordered_key_down[k] = 0; + droiddeck_inject_key((uint32_t)k, 0); + return 1; +} + +static void discard_deferred_input(void) { + struct host_msg *m = g_deferred_head; + while (m) { + struct host_msg *next = m->next; + release_held_key(m); + free(m->text); + free(m); + m = next; + } + g_deferred_head = g_deferred_tail = NULL; + g_deferred_count = g_deferred_bytes = 0; +} static int on_wake(int fd, uint32_t mask, void *data) { char buf[64]; while (read(fd, buf, sizeof(buf)) > 0) {} for (;;) { + int deferred = 0, submit = 0; pthread_mutex_lock(&g_mu); + if (g_pending_token != 0 && g_completed_token == g_pending_token) { + int result = g_completed_result; + g_completed_token = 0; + restore_deferred_to_front(); + if (result != DROIDDECK_TEXT_DELIVERED) discard_queued_submit(); + if (result == DROIDDECK_TEXT_UNRESOLVED) { + g_fallback_failed = 1; + } else { + if (result == DROIDDECK_TEXT_DELIVERED) submit = g_pending_submit; + g_pending_submit = 0; + g_pending_token = 0; + g_fallback_failed = 0; + g_deferred_overflow = 0; + } + } struct host_msg *m = g_head; - if (m) { g_head = m->next; if (!g_head) g_tail = NULL; } + if (m) { g_head = m->next; if (!g_head) g_tail = NULL; m->next = NULL; } pthread_mutex_unlock(&g_mu); + if (submit) tap_unheld_key(KEY_ENTER); if (!m) break; + if (g_pending_token != 0 && + (m->kind == HOST_TEXT_COMMIT || m->kind == HOST_TEXT_PREEDIT || + m->kind == HOST_TEXT_DELETE || m->kind == HOST_KEY || + m->kind == HOST_SELECT_GAME_FIELD)) { + int released_during_recovery = g_fallback_failed && release_held_key(m); + if (released_during_recovery || g_deferred_overflow || + g_deferred_count == DROIDDECK_TEXT_DEFERRED_LIMIT || + m->len > DROIDDECK_TEXT_DEFERRED_BYTES - g_deferred_bytes) { + if (!released_during_recovery) { + /* An incomplete queue could replay a submit or lose a paired release. */ + if (!g_deferred_overflow) + droiddeck_log("text-input", "deferred input exceeded the recovery queue limit"); + discard_deferred_input(); + release_held_key(m); + g_deferred_overflow = 1; + } + free(m->text); + free(m); + continue; + } + if (g_deferred_tail) g_deferred_tail->next = m; else g_deferred_head = m; + g_deferred_tail = m; + g_deferred_count++; + g_deferred_bytes += m->len; + deferred = 1; + } + if (deferred) continue; switch (m->kind) { case HOST_CLIPBOARD: clipboard_host_text(m->text, m->len); m->text = NULL; break; case HOST_TEXT_COMMIT: - text_input_host_commit(m->text ? m->text : "", m->len); + if (!text_input_host_commit(m->text ? m->text : "", m->len)) { + int token = 0; + if (g_next_token == INT_MAX) g_next_token = 1; + else g_next_token++; + token = g_next_token; + g_pending_token = 0; + if (droiddeck_on_text_input_fallback(m->text ? m->text : "", (int)m->len, token)) { + g_pending_token = token; + g_pending_submit = m->a; + } else { + droiddeck_log("text-input", "fallback had no accepting Android listener"); + pthread_mutex_lock(&g_mu); + discard_queued_submit(); + pthread_mutex_unlock(&g_mu); + } + } else if (m->a) { + tap_unheld_key(KEY_ENTER); + } break; case HOST_TEXT_PREEDIT: text_input_host_preedit(m->text ? m->text : "", m->len, m->a, m->b); @@ -93,6 +274,19 @@ static int on_wake(int fd, uint32_t mask, void *data) { case HOST_HDR_OUTPUT: droiddeck_color_set_output(m->a); break; + case HOST_SELECT_GAME_FIELD: + select_game_field(m->a); + break; + case HOST_KEY: + if (m->b == 1) { + int k = m->a; + if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 1; + } else if (m->b == 0) { + int k = m->a; + if (k >= 0 && k < DROIDDECK_EVDEV_KEY_MAX) g_ordered_key_down[k] = 0; + } + droiddeck_inject_key((uint32_t)m->a, m->b); + break; } free(m->text); free(m); diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h index ca359557e4..d7813eb7eb 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h @@ -15,22 +15,34 @@ struct wl_display *droiddeck_get_display(void); struct wl_resource *droiddeck_ime_target(void); void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y); void droiddeck_inject_key(uint32_t evdev, int pressed); +int droiddeck_key_is_down(uint32_t evdev); +void droiddeck_dispatch_pending_input(void); void droiddeck_on_clipboard_text(const char *utf8, int len); +int droiddeck_on_text_input_fallback(const char *utf8, int len, int token); void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h); void droiddeck_host_clipboard_text(const char *utf8, int len); void droiddeck_host_text_commit(const char *utf8, int len); +void droiddeck_host_text_commit_and_submit(const char *utf8, int len); void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end); void droiddeck_host_text_delete(int before, int after); void droiddeck_host_zero_copy(int on, int live); void droiddeck_host_hdr_output(int on); +void droiddeck_host_key(int evdev, int state); +void droiddeck_host_select_game_field(int copy); +enum droiddeck_text_input_result { + DROIDDECK_TEXT_NOT_DELIVERED = 0, + DROIDDECK_TEXT_DELIVERED = 1, + DROIDDECK_TEXT_UNRESOLVED = 2, +}; +void droiddeck_host_text_input_fallback_complete(int token, int result); void clipboard_init(struct wl_display *display); void clipboard_host_text(char *utf8, size_t len); void text_input_init(struct wl_display *display); -void text_input_host_commit(const char *utf8, size_t len); +int text_input_host_commit(const char *utf8, size_t len); void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end); void text_input_host_delete(int before, int after); void toplevel_icon_init(struct wl_display *display); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index d070b8fd6f..f1a8243d06 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -68,6 +68,7 @@ static jmethodID g_on_compositor_frame; static jmethodID g_on_game_program; static jmethodID g_on_pointer_lock; static jmethodID g_on_clipboard; +static jmethodID g_on_text_input_fallback; static jmethodID g_on_text_input; static jmethodID g_on_overlay_planes; static jmethodID g_on_refresh_target; @@ -92,6 +93,8 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; } g_on_pointer_lock = (*env)->GetStaticMethodID(env, g_compositor_cls, "onPointerLock", "(ZII)V"); g_on_clipboard = (*env)->GetStaticMethodID(env, g_compositor_cls, "onClipboardText", "([B)V"); + g_on_text_input_fallback = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInputFallback", + "([BI)Z"); g_on_text_input = (*env)->GetStaticMethodID(env, g_compositor_cls, "onTextInput", "(ZLjava/lang/String;IIII)V"); g_on_overlay_planes = (*env)->GetStaticMethodID(env, g_compositor_cls, "onOverlayPlanes", "(I)V"); @@ -203,6 +206,20 @@ void droiddeck_on_clipboard_text(const char *utf8, int len) { (*env)->DeleteLocalRef(env, arr); } +int droiddeck_on_text_input_fallback(const char *utf8, int len, int token) { + JNIEnv *env; + if (len <= 0 || token <= 0 || !utf8 || !g_compositor_cls || !g_on_text_input_fallback || !(env = thread_env())) + return 0; + jbyteArray arr = (*env)->NewByteArray(env, len); + if (!arr) { (*env)->ExceptionClear(env); return 0; } + (*env)->SetByteArrayRegion(env, arr, 0, len, (const jbyte *)utf8); + jboolean accepted = (*env)->CallStaticBooleanMethod(env, g_compositor_cls, g_on_text_input_fallback, arr, + (jint)token); + if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); accepted = JNI_FALSE; } + (*env)->DeleteLocalRef(env, arr); + return accepted == JNI_TRUE ? 1 : 0; +} + void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h) { JNIEnv *env; if (!g_compositor_cls || !g_on_text_input || !(env = thread_env())) return; @@ -376,6 +393,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey( droiddeck_wayland_send_key(evdev, state); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKeyOrdered( + JNIEnv *env, jclass clazz, jint evdev, jint state) { + droiddeck_host_key(evdev, state); +} + +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSelectGameField( + JNIEnv *env, jclass clazz, jboolean copy) { + droiddeck_host_select_game_field(copy); +} + JNIEXPORT jboolean JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeFocusTakesTouch( JNIEnv *env, jclass clazz) { @@ -807,6 +836,15 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommit(JNIE free(buf); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommitAndSubmit( + JNIEnv *env, jclass clazz, jbyteArray utf8) { + int len; + char *buf = dup_bytes(env, utf8, &len); + if (buf && len) droiddeck_host_text_commit_and_submit(buf, len); + free(buf); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputPreedit(JNIEnv *env, jclass clazz, jbyteArray utf8, jint cursorBegin, jint cursorEnd) { @@ -821,6 +859,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIE droiddeck_host_text_delete(before, after); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCompleteTextInputFallback( + JNIEnv *env, jclass clazz, jint token, jint result) { + droiddeck_host_text_input_fallback_complete(token, result); +} + extern void adrenotools_set_turbo(bool turbo); JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) { diff --git a/app/src/main/cpp/waylandcomp/src/wl_text_input.c b/app/src/main/cpp/waylandcomp/src/wl_text_input.c index 8b0ade227d..aaeff2de99 100644 --- a/app/src/main/cpp/waylandcomp/src/wl_text_input.c +++ b/app/src/main/cpp/waylandcomp/src/wl_text_input.c @@ -10,6 +10,12 @@ #ifndef KEY_DELETE #define KEY_DELETE 111 #endif +#ifndef KEY_ENTER +#define KEY_ENTER 28 +#endif +#ifndef KEY_TAB +#define KEY_TAB 15 +#endif static struct wl_display *g_disp; @@ -203,16 +209,43 @@ static int32_t utf8_offset(const char *s, size_t len, int chars) { return (int32_t)i; } -void text_input_host_commit(const char *utf8, size_t len) { +static int control_evdev(unsigned char c) { + switch (c) { + case '\r': case '\n': return KEY_ENTER; + case '\b': return KEY_BACKSPACE; + case 0x7f: return KEY_DELETE; + case '\t': return KEY_TAB; + default: return -1; + } +} + +static int all_controls(const char *utf8, size_t len) { + for (size_t i = 0; i < len; i++) + if (control_evdev((unsigned char)utf8[i]) < 0) return 0; + return 1; +} + +int text_input_host_commit(const char *utf8, size_t len) { struct text_input *ti = active_input(); if (!ti) { - droiddeck_log("text-input", "typed text (%zu chars) dropped: no program accepts text input", utf8_chars(utf8, len)); - return; + droiddeck_log("text-input", "typed text (%zu chars): no program accepts Wayland text input", utf8_chars(utf8, len)); + return 0; + } + if (len > 0 && all_controls(utf8, len)) { + /* Keep editing keys on the compositor queue so they cannot overtake text commits. */ + for (size_t i = 0; i < len; i++) { + int code = control_evdev((unsigned char)utf8[i]); + droiddeck_inject_key(code, 1); + droiddeck_inject_key(code, 0); + } + droiddeck_log("text-input", "injected %zu soft control(s) to %s", len, ti_program(ti)); + return 1; } if (ti->has_preedit) { zwp_text_input_v3_send_preedit_string(ti->res, "", 0, 0); ti->has_preedit = 0; } zwp_text_input_v3_send_commit_string(ti->res, utf8); zwp_text_input_v3_send_done(ti->res, ti->serial); droiddeck_log("text-input", "committed %zu chars to %s", utf8_chars(utf8, len), ti_program(ti)); + return 1; } void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end) { diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index d94320a5e2..cd96432a0c 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -76,6 +76,7 @@ import com.droiddeck.launcher.input.InputSpace import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SessionClipboard +import com.droiddeck.launcher.input.SessionTextInput import com.droiddeck.launcher.input.OnScreenControls import com.droiddeck.launcher.input.OnScreenLayout import com.droiddeck.launcher.input.InputRouter @@ -349,6 +350,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true } } + private val sessionTextInput by lazy { + SessionTextInput(this) { + window.decorView.hasWindowFocus() || secondScreenPresentation?.window?.decorView?.hasWindowFocus() == true + } + } private var watching = true private lateinit var touchpad: TouchpadGestures private lateinit var directTouchHold: DirectTouchHold @@ -997,7 +1003,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } root.addView(controls) } - keyboard = KeyboardHost(this).also { host -> + keyboard = KeyboardHost(this, sendKeyEvent = ::dispatchImeKeyEvent, sendText = WaylandCompositor::textInputCommit).also { host -> host.onImeChanged = ::onPrimaryImeChanged root.addView(host) } @@ -3801,16 +3807,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } - override fun dispatchKeyEvent(event: KeyEvent): Boolean { + internal fun dispatchImeKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = true) + + override fun dispatchKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event, orderedImeKey = false) + + private fun dispatchKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean { val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event) - if (normalized === event) return dispatchSessionKeyEvent(event) + if (normalized === event) return dispatchSessionKeyEvent(event, orderedImeKey) if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}") } - return dispatchSessionKeyEvent(normalized) + return dispatchSessionKeyEvent(normalized, orderedImeKey) } - private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean { + private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean { if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { @@ -3893,7 +3903,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return true } val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) - if (pad !== event) return dispatchKeyEvent(pad) + if (pad !== event) return dispatchKeyEvent(pad, orderedImeKey) val fromController = PadBridge.isControllerKeyEvent(event) if (fromController && (menuOwnsController || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) { padBridge?.setInputEnabled(false) @@ -3976,7 +3986,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val down = event.action == KeyEvent.ACTION_DOWN if (down && event.repeatCount > 0) return true val owner = if (event.deviceId <= 0) 16 else 8 - if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true + if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner, orderedImeKey) }) return true } return super.dispatchKeyEvent(event) } @@ -5270,27 +5280,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else { endGameField() } - host.type(text) - host.tap(KeyEvent.KEYCODE_ENTER) + if (text.isEmpty()) host.tap(KeyEvent.KEYCODE_ENTER) + else WaylandCompositor.textInputCommitAndSubmit(text) uiHandler.postDelayed({ if (AgentGuest.gameTextField && com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) endGameField() }, FIELD_SETTLE_MS) } private fun endGameField() { - WaylandCompositor.nativeSendKey(KEY_END, 1) - WaylandCompositor.nativeSendKey(KEY_END, 0) + orderedImeKeySender(KEY_END, true) + orderedImeKeySender(KEY_END, false) } - private fun selectGameField(vararg then: Int) { - heldKeys.set(256, KEY_LEFTCTRL, true) - try { - for (key in intArrayOf(KEY_A) + then) { - heldKeys.set(256, key, true) - heldKeys.set(256, key, false) - } - } finally { heldKeys.release(256) } - } + private fun selectGameField(copy: Boolean = false) { WaylandCompositor.nativeSelectGameField(copy) } private fun readGameField(done: (String?) -> Unit) { val opened = wowChat.request @@ -5299,7 +5301,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (text != null && stillOpen()) endGameField() done(text) } - selectGameField(KEY_C) + selectGameField(copy = true) } private fun cancelWowChat() { @@ -6202,11 +6204,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde releaseHeldKeys() } - private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) { + private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1, orderedImeKey: Boolean = false) { if (down && pipUi) return val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) } - heldKeys.set(owner, code, down) + val orderedSender = if (orderedImeKey) orderedImeKeySender else null + heldKeys.set(owner, code, down, orderedSender) + } + + private val orderedImeKeySender: (Int, Boolean) -> Unit = { code, down -> + WaylandCompositor.nativeSendKeyOrdered(code, if (down) 1 else 0) } private fun capturePausedFrame(manual: Boolean = false, onDone: () -> Unit = {}) { @@ -6389,6 +6396,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldButtons.clear() hidePrimaryKeyboard() sessionClipboard.stop() + sessionTextInput.stop() padMotion?.stop() cursorVisible = false closeSecondScreen(reset = false) @@ -6404,7 +6412,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else if (!isFinishing && !isDestroyed) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) updateOnScreenControls() - if (resumed) { sessionClipboard.start(); updatePadMotion() } + if (resumed) { sessionClipboard.start(); sessionTextInput.start(); updatePadMotion() } if (started) { settleDualScreenControls() refreshSecondScreenDisplays() @@ -6475,6 +6483,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) contentResolver.unregisterContentObserver(refreshSettingObserver) if (!screenIsOff()) closeSecondScreen(reset = false) + sessionTextInput.stop() startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() updateBottomGame() @@ -6554,7 +6563,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onCancel = { padBridge?.cancelHomeGuide() }, ) updatePointerCapture() - if (!pipUi) sessionClipboard.start() + if (!pipUi) { sessionClipboard.start(); sessionTextInput.start() } updatePadMotion() ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener) SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) @@ -7285,6 +7294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde gamescopeConvarRequests.shutdownNow() backQamInput.cancel() steamVrRecovery.close() + sessionTextInput.stop() uiHandler.removeCallbacks(steamTouchRetry) uiHandler.removeCallbacks(cursorResync) uiHandler.removeCallbacks(usbMouseFallback) diff --git a/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt index 1fdb6121fc..41cf641275 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt @@ -2,14 +2,24 @@ package com.droiddeck.launcher.input class HeldInput(private val emit: (Int, Boolean) -> Unit) { private val owners = IntArray(768) + private val ordered = arrayOfNulls<(Int, Boolean) -> Unit>(768) @Synchronized - fun set(source: Int, code: Int, down: Boolean) { + fun set(source: Int, code: Int, down: Boolean, orderedEmit: ((Int, Boolean) -> Unit)? = null) { if (code !in owners.indices) return val before = owners[code] val after = if (down) before or source else before and source.inv() owners[code] = after - if ((before == 0) != (after == 0)) emit(code, after != 0) + if ((before == 0) != (after == 0)) { + if (after != 0) { + ordered[code] = orderedEmit + orderedEmit?.invoke(code, true) ?: emit(code, true) + } else { + val fn = ordered[code] + ordered[code] = null + fn?.invoke(code, false) ?: emit(code, false) + } + } } @Synchronized @@ -21,7 +31,9 @@ class HeldInput(private val emit: (Int, Boolean) -> Unit) { fun clear() { for (code in owners.indices) if (owners[code] != 0) { owners[code] = 0 - emit(code, false) + val fn = ordered[code] + ordered[code] = null + fn?.invoke(code, false) ?: emit(code, false) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt index 5372be6db5..a9549c9918 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt @@ -4,7 +4,6 @@ import android.app.Activity import android.content.Context import android.os.Build import android.text.InputType -import android.view.KeyCharacterMap import android.view.KeyEvent import android.view.View import android.view.WindowInsets @@ -12,15 +11,17 @@ import android.view.inputmethod.BaseInputConnection import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import android.view.inputmethod.InputMethodManager +import com.droiddeck.launcher.wayland.WaylandCompositor class KeyboardHost( context: Context, private val sendKeyEvent: (KeyEvent) -> Boolean, + private val sendText: (String) -> Unit, ) : View(context) { - constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(it) }) + constructor(activity: Activity) : + this(activity, { activity.dispatchKeyEvent(it) }, { WaylandCompositor.textInputCommit(it) }) private val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - private val map: KeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD) var shown = false private set var imeShowing = false @@ -40,8 +41,7 @@ class KeyboardHost( override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { if (!shown) return null - outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or - InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD + outAttrs.inputType = InputType.TYPE_CLASS_TEXT outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI return KeyConnection() @@ -93,45 +93,153 @@ class KeyboardHost( fun type(text: CharSequence?) { if (text.isNullOrEmpty()) return - val events = map.getEvents(text.toString().toCharArray()) - if (events != null) { - for (event in events) sendKeyEvent(event) - } else { - for (ch in text) { - val t = System.currentTimeMillis() - val down = KeyEvent(t, t, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_UNKNOWN, 0, 0, - KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, 0) - sendKeyEvent(CharKeyEvent(down, ch)) - sendKeyEvent(CharKeyEvent(KeyEvent.changeAction(down, KeyEvent.ACTION_UP), ch)) - } - } + // Text and soft editing actions share this queue to preserve IME ordering. + sendText(text.toString()) } fun tap(keyCode: Int) { + val control = softControl(keyCode) + if (control != null) { + sendText(control.toString()) + return + } val t = System.currentTimeMillis() sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0)) sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0)) } private inner class KeyConnection : BaseInputConnection(this, false) { + // A press keeps the route chosen on its first down across repeats and the matching up. + private val controlRoutes = HashMap() + + private var composingText = "" + private var composingCursor = 0 + override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean { + composingText = "" + composingCursor = 0 type(text) return true } - override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = true - override fun finishComposingText(): Boolean = true - - override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { - repeat(beforeLength) { tap(KeyEvent.KEYCODE_DEL) } - repeat(afterLength) { tap(KeyEvent.KEYCODE_FORWARD_DEL) } + override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean { + composingText = text?.toString().orEmpty() + val rawCursor = if (newCursorPosition > 0) { + composingText.length.toLong() + newCursorPosition - 1L + } else { + newCursorPosition.toLong() + } + composingCursor = rawCursor.coerceIn(0L, composingText.length.toLong()).toInt() return true } - override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event) + override fun finishComposingText(): Boolean { + val text = composingText + composingText = "" + composingCursor = 0 + type(text) + return true + } + + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { + val before = beforeLength.coerceAtLeast(0) + val after = afterLength.coerceAtLeast(0) + if (before == 0 && after == 0) return true + val consumedBefore = minOf(before, composingCursor) + val consumedAfter = minOf(after, composingText.length - composingCursor) + val guestBefore = before - consumedBefore + val guestAfter = after - consumedAfter + if (guestBefore > 1 || guestAfter > 1) return false + return applyDeletion( + composingCursor - consumedBefore, + composingCursor + consumedAfter, + guestBefore, + guestAfter, + ) + } + + override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean { + val before = beforeLength.coerceAtLeast(0) + val after = afterLength.coerceAtLeast(0) + if (before == 0 && after == 0) return true + if (splitsPair(composingCursor)) return false + val text = composingText + val beforePoints = Character.codePointCount(text, 0, composingCursor) + val afterPoints = Character.codePointCount(text, composingCursor, text.length) + val consumedBefore = minOf(before, beforePoints) + val consumedAfter = minOf(after, afterPoints) + val start = Character.offsetByCodePoints(text, composingCursor, -consumedBefore) + val end = Character.offsetByCodePoints(text, composingCursor, consumedAfter) + if (hasUnpairedSurrogate(text, start, end)) return false + return applyDeletion( + start, + end, + before - consumedBefore, + after - consumedAfter, + ) + } + + private fun applyDeletion(start: Int, end: Int, guestBefore: Int, guestAfter: Int): Boolean { + if (guestBefore > 64 || guestAfter > 64) return false + if (splitsPair(start) || splitsPair(end)) return false + if (start < end) { + composingText = composingText.removeRange(start, end) + composingCursor = start + } + val controls = StringBuilder() + repeat(guestBefore) { controls.append(BACKSPACE) } + repeat(guestAfter) { controls.append(FORWARD_DELETE) } + if (controls.isNotEmpty()) sendText(controls.toString()) + return true + } + + private fun splitsPair(index: Int): Boolean = + index > 0 && index < composingText.length && + composingText[index - 1].isHighSurrogate() && composingText[index].isLowSurrogate() + + private fun hasUnpairedSurrogate(text: CharSequence, start: Int, end: Int): Boolean { + var i = start + while (i < end) { + val c = text[i] + if (c.isHighSurrogate()) { + if (i + 1 >= end || !text[i + 1].isLowSurrogate()) return true + i += 2 + } else if (c.isLowSurrogate()) { + return true + } else { + i++ + } + } + return false + } + + override fun sendKeyEvent(event: KeyEvent): Boolean { + val control = softControl(event.keyCode) + if (control == null) return this@KeyboardHost.sendKeyEvent(event) + if (event.action == KeyEvent.ACTION_DOWN) { + val soft = if (event.repeatCount == 0) { + val route = !event.isModified() + controlRoutes[event.keyCode] = route + route + } else { + controlRoutes[event.keyCode] ?: !event.isModified() + } + if (!soft) return this@KeyboardHost.sendKeyEvent(event) + if (control == ENTER) finishComposingText() + sendText(control.toString()) + return true + } + if (event.action == KeyEvent.ACTION_UP) { + val soft = controlRoutes.remove(event.keyCode) ?: !event.isModified() + if (soft) return true + return this@KeyboardHost.sendKeyEvent(event) + } + return this@KeyboardHost.sendKeyEvent(event) + } override fun performEditorAction(actionCode: Int): Boolean { - tap(KeyEvent.KEYCODE_ENTER) + finishComposingText() + sendText(ENTER.toString()) return true } @@ -140,8 +248,22 @@ class KeyboardHost( override fun getSelectedText(flags: Int): CharSequence? = null } - private class CharKeyEvent(origin: KeyEvent, private val ch: Char) : KeyEvent(origin) { - override fun getUnicodeChar(): Int = ch.code - override fun getUnicodeChar(metaState: Int): Int = ch.code + private fun softControl(keyCode: Int): Char? = when (keyCode) { + KeyEvent.KEYCODE_DEL -> BACKSPACE + KeyEvent.KEYCODE_FORWARD_DEL -> FORWARD_DELETE + KeyEvent.KEYCODE_ENTER -> ENTER + KeyEvent.KEYCODE_TAB -> TAB + else -> null + } + + private fun KeyEvent.isModified(): Boolean = + isCtrlPressed || isShiftPressed || isAltPressed || isMetaPressed + + private companion object { + // Control characters represent editing keys on the guest text channel. + const val ENTER = '\r' + const val BACKSPACE = '\b' + const val FORWARD_DELETE = '\u007f' + const val TAB = '\t' } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt b/app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt new file mode 100644 index 0000000000..387351def2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/SessionTextInput.kt @@ -0,0 +1,327 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.net.LocalSocket +import android.net.LocalSocketAddress +import android.os.Handler +import android.os.Looper +import android.util.Log +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File +import java.io.IOException +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.ScheduledThreadPoolExecutor +import java.util.concurrent.TimeUnit + +private enum class TextDelivery(val result: Int) { + NOT_DELIVERED(WaylandCompositor.TEXT_NOT_DELIVERED), + DELIVERED(WaylandCompositor.TEXT_DELIVERED), + UNRESOLVED(WaylandCompositor.TEXT_UNRESOLVED), +} + +class SessionTextInput(context: Context, private val hasFocus: () -> Boolean) { + private val delivery = deliveryFor(context) + private val owner = Any() + + fun start() = delivery.start(owner, hasFocus) + fun stop() = delivery.stop(owner) + + private companion object { + private var instance: SessionTextDelivery? = null + + @Synchronized private fun deliveryFor(context: Context): SessionTextDelivery = + instance ?: SessionTextDelivery(context.applicationContext).also { instance = it } + } +} + +private class SessionTextDelivery(private val appContext: Context) { + private val handler = Handler(Looper.getMainLooper()) + private val lock = Any() + private var generation = 0L + @Volatile private var active = false + private var owner: Any? = null + private var focusCheck: (() -> Boolean)? = null + private var executor: ScheduledThreadPoolExecutor? = null + private var socket: LocalSocket? = null + private var pendingToken = 0 + private var runningToken = 0 + private var failedToken = 0 + private val guestListener = object : WaylandCompositor.TextInputFallbackListener { + override fun onTextInputFallback(text: String, token: Int): Boolean { + synchronized(lock) { + if (!active || pendingToken != 0 || failedToken != 0 || token <= 0) return false + val received = generation + pendingToken = token + val posted = try { + handler.post { enqueue(text, received, token) } + } catch (e: RuntimeException) { + false + } + if (!posted) pendingToken = 0 + return posted + } + } + } + + fun start(nextOwner: Any, hasFocus: () -> Boolean) { + val previous = synchronized(lock) { + if (owner === nextOwner) return + owner + } + if (previous != null) stop(previous) + val queue = ScheduledThreadPoolExecutor(1) { runnable -> + Thread(runnable, "session-text-input").apply { isDaemon = true } + } + queue.executeExistingDelayedTasksAfterShutdownPolicy = false + synchronized(lock) { + this.owner = nextOwner + focusCheck = hasFocus + active = true + executor = queue + if (failedToken != 0) scheduleRetryLocked(failedToken, INITIAL_DELAY_MS) + } + WaylandCompositor.setTextInputFallbackListener(guestListener) + } + + fun stop(oldOwner: Any) { + val detached = synchronized(lock) { + if (owner !== oldOwner) return + owner = null + focusCheck = null + active = false + generation += 1 + val queue = executor + val open = socket + val token = if (runningToken == 0 && failedToken == 0) pendingToken else 0 + executor = null + socket = null + Triple(queue, open, token) + } + WaylandCompositor.clearTextInputFallbackListener(guestListener) + handler.removeCallbacksAndMessages(null) + detached.second?.let { requestCancel(it) } + detached.first?.shutdown() + if (detached.third != 0) complete(detached.third) + } + + private fun enqueue(text: String, received: Long, token: Int) { + val currentFocus = synchronized(lock) { if (active && generation == received) focusCheck else null } + if (currentFocus == null || !currentFocus() || !WaylandCompositor.isTextInputFallbackListener(guestListener)) { + Log.d(TAG, "guest text fallback skipped outside the active focused session") + complete(token) + return + } + val bytes = text.toByteArray(Charsets.UTF_8) + if (bytes.isEmpty() || bytes.size > MAX_BYTES) { + complete(token) + return + } + val queue = synchronized(lock) { + if (active && generation == received) executor else null + } + if (queue == null) { + complete(token) + return + } + try { + queue.execute { + try { + val delivery = send(bytes, received, token) + if (delivery == TextDelivery.UNRESOLVED) recover(token) + else complete(token, delivery) + } finally { + releaseRunning(token) + } + } + } catch (e: RejectedExecutionException) { + complete(token) + } + } + + private fun recover(token: Int) { + if (probe()) { + complete(token) + return + } + val marked = synchronized(lock) { + if (pendingToken == token && failedToken == 0) { + failedToken = token + WaylandCompositor.completeTextInputFallback(token, TextDelivery.UNRESOLVED.result) + scheduleRetryLocked(token, INITIAL_DELAY_MS) + true + } else { + false + } + } + if (marked) Log.w(TAG, "text injection could not be confirmed") + } + + private fun scheduleRetryLocked(token: Int, delayMs: Long) { + if (!active || failedToken != token || pendingToken != token) return + val queue = executor ?: return + val current = generation + try { + queue.schedule({ retryProbe(current, token, delayMs) }, delayMs, TimeUnit.MILLISECONDS) + } catch (e: RejectedExecutionException) { + } + } + + private fun retryProbe(received: Long, token: Int, delayMs: Long) { + val ready = synchronized(lock) { + active && generation == received && failedToken == token && pendingToken == token + } + if (!ready) return + val proven = probe() + val owned = synchronized(lock) { + if (proven) { + if (active && generation == received && failedToken == token && pendingToken == token) { + pendingToken = 0 + runningToken = 0 + failedToken = 0 + true + } else { + false + } + } else { + if (active && generation == received && failedToken == token && pendingToken == token) { + val next = (delayMs * 2).coerceAtMost(MAX_DELAY_MS) + scheduleRetryLocked(token, next) + } + false + } + } + if (owned) WaylandCompositor.completeTextInputFallback(token, TextDelivery.NOT_DELIVERED.result) + } + + private fun probe(): Boolean { + val live = LocalSocket() + return try { + live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM)) + live.soTimeout = TIMEOUT_MS + val out = live.outputStream + out.write(lengthPrefix(0)) + out.flush() + live.inputStream.read() == 0 + } catch (e: IOException) { + Log.w(TAG, "could not probe guest text input state", e) + false + } finally { + close(live) + } + } + + private fun complete(token: Int, delivery: TextDelivery = TextDelivery.NOT_DELIVERED) { + val owned = synchronized(lock) { + if (pendingToken == token) { + pendingToken = 0 + runningToken = 0 + failedToken = 0 + true + } else { + false + } + } + if (owned) WaylandCompositor.completeTextInputFallback(token, delivery.result) + } + + private fun releaseRunning(token: Int) { + synchronized(lock) { + if (runningToken == token) runningToken = 0 + } + } + + private fun send(bytes: ByteArray, received: Long, token: Int): TextDelivery { + val live = LocalSocket() + if (!claim(live, received, token)) { + close(live) + return TextDelivery.NOT_DELIVERED + } + var requested = false + try { + live.connect(LocalSocketAddress(endpoint().path, LocalSocketAddress.Namespace.FILESYSTEM)) + live.soTimeout = TIMEOUT_MS + if (!isCurrent(received)) return TextDelivery.NOT_DELIVERED + val out = live.outputStream + out.write(lengthPrefix(bytes.size)) + requested = true + out.write(bytes) + out.flush() + val input = live.inputStream + val ack = try { + input.read() + } catch (e: IOException) { + // Android may report a socket read timeout as a plain IOException. + requestCancel(live) + input.read() + } + if (ack == 0) Log.d(TAG, "guest did not complete text delivery") + if (ack != 0 && ack != 1 && isCurrent(received)) Log.w(TAG, "guest did not acknowledge text delivery") + return when (ack) { + 1 -> TextDelivery.DELIVERED + 0 -> TextDelivery.NOT_DELIVERED + else -> TextDelivery.UNRESOLVED + } + } catch (e: IOException) { + if (isCurrent(received)) Log.w(TAG, "could not hand text to the guest", e) + if (!requested) return TextDelivery.NOT_DELIVERED + return TextDelivery.UNRESOLVED + } finally { + release(live) + close(live) + } + } + + private fun requestCancel(live: LocalSocket) { + try { + live.shutdownOutput() + } catch (e: IOException) { + Log.w(TAG, "could not request guest text input cancellation", e) + } + } + + private fun isCurrent(received: Long) = synchronized(lock) { active && generation == received } + + private fun claim(live: LocalSocket, received: Long, token: Int) = synchronized(lock) { + if (!active || generation != received || pendingToken != token || runningToken != 0 || failedToken != 0) { + false + } else { + runningToken = token + socket = live + true + } + } + + private fun release(live: LocalSocket) { + synchronized(lock) { + if (socket === live) socket = null + } + } + + private fun endpoint(): File = File(LinuxRuntime.sessionRoot(appContext), "text-input.sock") + + private fun lengthPrefix(size: Int): ByteArray { + val flagged = if (size == 0) size else size or Int.MIN_VALUE + return byteArrayOf( + (flagged ushr 24).toByte(), + (flagged ushr 16).toByte(), + (flagged ushr 8).toByte(), + flagged.toByte(), + ) + } + + private fun close(sock: LocalSocket) { + try { + sock.close() + } catch (e: IOException) { + } + } + + private companion object { + const val TAG = "SessionTextInput" + const val MAX_BYTES = 65536 + const val TIMEOUT_MS = 3000 + const val INITIAL_DELAY_MS = 500L + const val MAX_DELAY_MS = 5000L + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt index a8b76934ee..ffccd3e237 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt @@ -219,6 +219,19 @@ object BottomDesktop { fun sendText(text: String) { val target = service ?: return + if (text.isNotEmpty() && text.all { it == '\r' || it == '\n' || it == '\b' || it == '\u007f' || it == '\t' }) { + for (c in text) { + val evdev = when (c) { + '\r', '\n' -> 28 + '\b' -> 14 + '\u007f' -> 111 + else -> 15 + } + sendKey(evdev, true) + sendKey(evdev, false) + } + return + } send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } }) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index be11f5bb90..d28ae192db 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -11,6 +11,7 @@ import com.droiddeck.launcher.runtime.DesktopCatalog import com.droiddeck.launcher.runtime.LegacyNames import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.ProotFastPath +import org.json.JSONObject import java.io.File object SessionFiles { @@ -21,6 +22,8 @@ object SessionFiles { private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad" const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio" private const val STAGED_LEDGER = "usr/local/.droiddeck-staged" + private const val IME_MANIFEST = "usr/local/share/droiddeck/ime-files.json" + private const val IME_DEFAULT_MODE = 420 val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread") internal val DESKTOP_FILES = arrayOf( @@ -133,6 +136,8 @@ object SessionFiles { "usr/local/bin/droiddeck-spawn" to "usr/local/bin/droiddeck-spawn", "usr/local/bin/droiddeck-log-writer" to "usr/local/bin/droiddeck-log-writer", "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", + "usr/local/bin/droiddeck-text-input" to "usr/local/bin/droiddeck-text-input", + "usr/local/bin/droiddeck-steam-ime" to "usr/local/bin/droiddeck-steam-ime", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", "usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply", @@ -335,6 +340,7 @@ object SessionFiles { if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged") } for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger) + stageImeFiles(context, root, ledger) ledger.save() for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively() val preload = StringBuilder("/usr/local/lib/libddsession.so\n") @@ -421,6 +427,42 @@ object SessionFiles { seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) } } + private fun stageImeFiles(context: Context, root: File, ledger: StageLedger) { + val entries = LinkedHashMap() + try { + val text = context.assets.open("linuxfs/$IME_MANIFEST").bufferedReader().use { it.readText() } + val files = JSONObject(text).getJSONObject("files") + for (name in files.keys()) { + entries[name] = files.optJSONObject(name)?.optString("mode").orEmpty().toIntOrNull(8) ?: IME_DEFAULT_MODE + } + entries[IME_MANIFEST] = IME_DEFAULT_MODE + } catch (e: Exception) { + Log.w(TAG, "the Chinese input payload is not bundled; Steam sessions start without it", e) + return + } + for ((relative, mode) in entries) { + val target = File(root, relative) + if (ledger.current(relative, target)) continue + val staged = File(target.parentFile, target.name + ".staged") + var installed = false + try { + target.parentFile?.mkdirs() + context.assets.open("linuxfs/$relative").use { input -> + staged.outputStream().use { output -> FileUtils.copy(input, output) } + } + installed = staged.setReadable(true, false) && + staged.setWritable((mode and 0x80) != 0, true) && + staged.setExecutable((mode and 0x49) != 0, false) && + staged.renameTo(target) + } catch (e: Exception) { + Log.w(TAG, "could not stage $relative", e) + } finally { + if (!installed) staged.delete() + } + if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged") + } + } + internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean { synchronized(STEAM_CONFIG) { if (!config.isFile) return true diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt index c9e8362c4d..38359530db 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomDesktopPanel.kt @@ -46,7 +46,11 @@ class BottomDesktopPanel( private val status = ComposeView(context).apply { setContent { DroidDeckTheme { BottomDesktopStatus(state.value, ::startAgain) } } } - private val keyboardHost = KeyboardHost(context) { event -> sendKey(event) } + private val keyboardHost = KeyboardHost( + context, + sendKeyEvent = { event -> sendKey(event) }, + sendText = BottomDesktop::sendText, + ) private var directTouch = SessionPrefs.bottomDesktopDirectTouch(context) private val touchMode = mutableStateOf(directTouch) private val trackpad = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), TrackpadInput()).apply { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 73df657efe..c9609c311d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -25,6 +25,7 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner import com.droiddeck.launcher.input.DeckPanel import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.PadBridge +import com.droiddeck.launcher.wayland.WaylandCompositor import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.SessionActivity import com.droiddeck.launcher.session.BottomDesktop @@ -490,12 +491,19 @@ class SecondScreenPresentation( } private fun attachKeyboard() { - val host = KeyboardHost(context) { event -> - val handled = sessionActivity.dispatchKeyEvent(event) - if (fieldKeyboard && event.action == KeyEvent.ACTION_UP && - (event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() } - handled - } + val host = KeyboardHost( + context, + sendKeyEvent = { event -> + val handled = sessionActivity.dispatchImeKeyEvent(event) + if (fieldKeyboard && event.action == KeyEvent.ACTION_UP && + (event.keyCode == KeyEvent.KEYCODE_ENTER || event.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER)) root.post { closeFieldKeyboard() } + handled + }, + sendText = { text -> + WaylandCompositor.textInputCommit(text) + if (fieldKeyboard && text == "\r") root.post { closeFieldKeyboard() } + }, + ) host.onImeChanged = { visible -> if (!visible && keyboardShown.value) keyboardClosed() } keyboardHost = host root.addView(host, ViewGroup.LayoutParams(1, 1)) diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt b/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt index d1c64b4b39..4b9d25957a 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt @@ -31,7 +31,7 @@ class BottomDesktopCompositorService : Service() { MSG_RESIZE -> resize(msg.arg1, msg.arg2) MSG_TOUCH -> WaylandCompositor.nativeSendTouch(msg.arg1 and 0xff, msg.arg1 shr 8, msg.arg2 ushr 16, msg.arg2 and 0xffff) - MSG_KEY -> WaylandCompositor.nativeSendKey(msg.arg1, msg.arg2) + MSG_KEY -> WaylandCompositor.nativeSendKeyOrdered(msg.arg1, msg.arg2) MSG_POINTER -> WaylandCompositor.nativeSendPointer(1, msg.arg1, msg.arg2) MSG_SCENE -> WaylandCompositor.nativeSendSceneInput(msg.arg1, msg.arg2, msg.peekData()?.getInt(KEY_B) ?: 0) MSG_CURSOR -> if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(msg.arg1 != 0) 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 afe0df226f..70fdc0e595 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -202,6 +202,27 @@ public final class WaylandCompositor { if (l != null) l.onTextInput(enabled, program, x, y, w, h); } + public interface TextInputFallbackListener { + boolean onTextInputFallback(String text, int token); + } + + private static volatile TextInputFallbackListener textInputFallbackListener; + + public static void setTextInputFallbackListener(TextInputFallbackListener l) { textInputFallbackListener = l; } + + public static boolean isTextInputFallbackListener(TextInputFallbackListener l) { return textInputFallbackListener == l; } + + public static void clearTextInputFallbackListener(TextInputFallbackListener l) { + if (textInputFallbackListener == l) textInputFallbackListener = null; + } + + @SuppressWarnings("unused") + static boolean onTextInputFallback(byte[] utf8, int token) { + TextInputFallbackListener l = textInputFallbackListener; + if (l == null || utf8 == null) return false; + return l.onTextInputFallback(new String(utf8, java.nio.charset.StandardCharsets.UTF_8), token); + } + private static byte[] utf8(String s) { return s == null ? new byte[0] : s.getBytes(java.nio.charset.StandardCharsets.UTF_8); } @@ -210,14 +231,28 @@ public final class WaylandCompositor { public static void textInputCommit(String text) { if (text != null && !text.isEmpty()) nativeTextInputCommit(utf8(text)); } + public static void textInputCommitAndSubmit(String text) { + if (text != null && !text.isEmpty()) nativeTextInputCommitAndSubmit(utf8(text)); + } + public static void textInputPreedit(String text, int cursor) { nativeTextInputPreedit(utf8(text), cursor, cursor); } public static void textInputDelete(int before, int after) { nativeTextInputDelete(before, after); } + public static final int TEXT_NOT_DELIVERED = 0; + public static final int TEXT_DELIVERED = 1; + public static final int TEXT_UNRESOLVED = 2; + + public static void completeTextInputFallback(int token, int result) { + nativeCompleteTextInputFallback(token, result); + } + private static native void nativeSetClipboardText(byte[] utf8); private static native void nativeTextInputCommit(byte[] utf8); + private static native void nativeTextInputCommitAndSubmit(byte[] utf8); private static native void nativeTextInputPreedit(byte[] utf8, int cursorBegin, int cursorEnd); private static native void nativeTextInputDelete(int before, int after); + private static native void nativeCompleteTextInputFallback(int token, int result); public static native void nativeStart(String xdgRuntimeDir); @@ -248,6 +283,10 @@ public final class WaylandCompositor { public static native void nativeSendKey(int evdev, int state); + // Ordered delivery: key events share the host queue with text commits so keys cannot overtake pending text. + public static native void nativeSendKeyOrdered(int evdev, int state); + public static native void nativeSelectGameField(boolean copy); + public static native boolean nativeFocusTakesTouch(); public static native boolean nativeCursorInputPos(int[] out); diff --git a/app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt new file mode 100644 index 0000000000..bf25bf731f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/HeldInputTest.kt @@ -0,0 +1,57 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertEquals +import org.junit.Test + +class HeldInputTest { + @Test + fun normalRoutingUsesDefaultEmitter() { + val events = mutableListOf>() + val input = HeldInput { code, down -> events.add(code to down) } + input.set(1, 30, true) + input.set(1, 30, false) + assertEquals(listOf(30 to true, 30 to false), events) + } + + @Test + fun orderedSenderHandlesDownRepeatedDownSecondOwnerAndFinalRelease() { + val defaultEvents = mutableListOf>() + val orderedEvents = mutableListOf>() + val input = HeldInput { code, down -> defaultEvents.add(code to down) } + val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) } + input.set(1, 30, true, ordered) + input.set(1, 30, true, ordered) + input.set(2, 30, true, ordered) + input.set(1, 30, false) + input.set(2, 30, false) + assertEquals(listOf(30 to true, 30 to false), orderedEvents) + assertEquals(emptyList>(), defaultEvents) + } + + @Test + fun releaseChoosesMatchingRoute() { + val defaultEvents = mutableListOf>() + val orderedEvents = mutableListOf>() + val input = HeldInput { code, down -> defaultEvents.add(code to down) } + val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) } + input.set(1, 31, true, ordered) + input.set(2, 32, true) + input.release(2) + input.release(1) + assertEquals(listOf(31 to true, 31 to false), orderedEvents) + assertEquals(listOf(32 to true, 32 to false), defaultEvents) + } + + @Test + fun clearChoosesMatchingRoute() { + val defaultEvents = mutableListOf>() + val orderedEvents = mutableListOf>() + val input = HeldInput { code, down -> defaultEvents.add(code to down) } + val ordered: (Int, Boolean) -> Unit = { code, down -> orderedEvents.add(code to down) } + input.set(1, 40, true, ordered) + input.set(2, 41, true) + input.clear() + assertEquals(listOf(40 to true, 40 to false), orderedEvents) + assertEquals(listOf(41 to true, 41 to false), defaultEvents) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt b/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt index eff9197525..9961c1d2f8 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/KeyboardHostTest.kt @@ -3,9 +3,15 @@ package com.droiddeck.launcher.input import android.app.Activity import android.content.Context import android.os.Looper +import android.text.InputType +import android.view.KeyEvent +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -20,11 +26,13 @@ import org.robolectric.annotation.Config class KeyboardHostTest { private lateinit var imm: InputMethodManager private lateinit var host: KeyboardHost + private val keys = mutableListOf() + private val texts = mutableListOf() @Before fun setUp() { val activity = Robolectric.buildActivity(Activity::class.java).setup().get() imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager - host = KeyboardHost(activity) + host = KeyboardHost(activity, { keys += it; true }, { texts += it }) activity.setContentView(FrameLayout(activity).apply { addView(host) }) idle() } @@ -41,6 +49,36 @@ class KeyboardHostTest { assertTrue(host.shown) } + @Config(sdk = [33]) + @Test fun shownEditorIsNotDescribedAsAPasswordField() { + host.show() + idle() + + val attrs = EditorInfo() + val connection = host.onCreateInputConnection(attrs) + + assertNotNull("shown host must expose an input connection", connection) + assertEquals( + "editor must be declared as a text field", + InputType.TYPE_CLASS_TEXT, + attrs.inputType and InputType.TYPE_MASK_CLASS, + ) + + val variation = attrs.inputType and InputType.TYPE_MASK_VARIATION + assertFalse( + "text field must not be a password field", + variation == InputType.TYPE_TEXT_VARIATION_PASSWORD, + ) + assertFalse( + "text field must not be a visible password field", + variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD, + ) + assertFalse( + "text field must not be a web password field", + variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD, + ) + } + @Config(sdk = [28]) @Test fun toggleHidesAKeyboardThatIsShowing() { host.show() @@ -51,5 +89,436 @@ class KeyboardHostTest { assertFalse(host.shown) } + @Config(sdk = [33]) + @Test fun mixedScriptTextIsCommittedOnceWithoutKeyEvents() { + host.show() + idle() + val text = "中文ABC123,。é😀" + + assertTrue(connection().commitText(text, 1)) + idle() + + assertEquals("the whole string must reach the guest once", listOf(text), texts) + assertTrue("non-ASCII text must not be turned into key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun latestCompositionIsCommittedOnceWhenFinished() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("zhong", 1) + connection.setComposingText("中文", 1) + assertTrue(texts.isEmpty()) + connection.finishComposingText() + connection.finishComposingText() + idle() + + assertTrue(keys.isEmpty()) + assertEquals(listOf("中文"), texts) + } + + @Config(sdk = [33]) + @Test fun finishedCandidateIsCommittedExactlyOnce() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("zhong", 1) + connection.deleteSurroundingText(1, 0) + connection.commitText("中文", 1) + connection.finishComposingText() + connection.setComposingText("ab", 1) + connection.deleteSurroundingText(1, 0) + connection.setComposingText("xy", 1) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文", "xy"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun emptyCompositionCancelsPendingText() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("zhong", 1) + connection.setComposingText("", 1) + connection.finishComposingText() + idle() + + assertTrue(texts.isEmpty()) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun deleteWithinCompositionShortensPendingTextWithoutGuestBackspace() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("abc", 1) + connection.deleteSurroundingText(1, 0) + idle() + assertTrue(texts.isEmpty()) + assertTrue(keys.isEmpty()) + + connection.finishComposingText() + idle() + + assertEquals(listOf("ab"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun deleteBeyondCompositionForwardsOnlyResidualCountsWithoutResurrectingText() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("ab", 1) + connection.deleteSurroundingText(3, 1) + connection.finishComposingText() + connection.setComposingText("cd", 0) + connection.deleteSurroundingText(1, 3) + connection.finishComposingText() + idle() + + assertEquals(listOf("\b\u007f", "\b\u007f"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun composingCursorAtStartConsumesForwardDeleteAndForwardsBackspace() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("abc", 0) + connection.deleteSurroundingText(1, 0) + assertEquals(listOf("\b"), texts) + + connection.deleteSurroundingText(0, 1) + connection.finishComposingText() + idle() + + assertEquals(listOf("\b", "bc"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun utf16DeleteOfTrailingEmojiInCompositionPreservesChineseText() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("中文😀", 1) + connection.deleteSurroundingText(2, 0) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun chinesePendingTextFinishesBeforeEditorActionWithoutDuplication() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("中文", 1) + connection.performEditorAction(EditorInfo.IME_ACTION_SEND) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文", "\r"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun chinesePendingTextFinishesBeforePlainSoftEnterWithoutDuplication() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("中文", 1) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)) + connection.finishComposingText() + idle() + + assertEquals(listOf("中文", "\r"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun unknownUtf16DeleteOfCommittedEmojiIsRejectedWithoutGuestEdit() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("A\uD83D\uDE00", 1)) + idle() + texts.clear() + + assertFalse("unknown committed UTF-16 deletion must be rejected", + connection.deleteSurroundingText(2, 0)) + idle() + assertTrue("a rejected deletion must not edit the guest", texts.isEmpty()) + + assertTrue(connection.deleteSurroundingTextInCodePoints(1, 0)) + idle() + assertEquals(listOf("\b"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun codePointDeleteAtEndOfComposingSurrogateSendsOnlyTextBeforeEmoji() { + host.show() + idle() + val connection = connection() + + connection.setComposingText("A\uD83D\uDE00", 1) + assertFalse("half-surrogate UTF-16 deletion must be rejected", + connection.deleteSurroundingText(1, 0)) + idle() + assertTrue("a rejected half-surrogate deletion must retain original text", texts.isEmpty()) + + assertTrue(connection.deleteSurroundingTextInCodePoints(1, 0)) + connection.finishComposingText() + idle() + + assertEquals(listOf("A"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun codePointDeleteBeyondCompositionForwardsBothResidualControls() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("abcd", 1)) + idle() + texts.clear() + + assertTrue(connection.deleteSurroundingTextInCodePoints(2, 2)) + idle() + + assertEquals(listOf("\b\b\u007f\u007f"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun asciiTextIsCommittedAsOneTextCallback() { + host.show() + idle() + + assertTrue(connection().commitText("ab", 1)) + idle() + + assertEquals("ASCII must reach the guest as one whole commit", listOf("ab"), texts) + assertTrue("ASCII must not take the key event path", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun adjacentCommitsKeepTheirOrder() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("中文", 1)) + assertTrue(connection.commitText("中文", 1)) + assertTrue(connection.commitText(" ", 1)) + assertTrue(connection.commitText("abc", 1)) + idle() + + assertEquals("every commit must keep the order the IME sent it", listOf("中文", "中文", " ", "abc"), texts) + assertTrue("no commit may take the key event path", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun backspaceAndEnterQueueOrderedControls() { + host.show() + idle() + val connection = connection() + + connection.deleteSurroundingText(1, 0) + connection.performEditorAction(EditorInfo.IME_ACTION_SEND) + idle() + + assertEquals( + "soft edits must ride the ordered text FIFO, not the key event route", + listOf("\b", "\r"), texts, + ) + assertTrue("soft edits must not become key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun deleteSurroundingTextQueuesBackspaceThenForwardDelete() { + host.show() + idle() + + assertTrue(connection().deleteSurroundingText(1, 1)) + idle() + + assertEquals(listOf("\b\u007f"), texts) + assertTrue("deletions must not become key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun commitThenDeleteThenEditorActionKeepTheirOrder() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.commitText("中文", 1)) + assertTrue(connection.deleteSurroundingText(1, 0)) + assertTrue(connection.performEditorAction(EditorInfo.IME_ACTION_SEND)) + idle() + + assertEquals("a Chinese commit must not be overtaken by the soft edits after it", + listOf("中文", "\b", "\r"), texts) + assertTrue(keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun softEditKeysQueueExactlyOneControlPerPress() { + host.show() + idle() + val connection = connection() + + for ((keyCode, control) in listOf( + KeyEvent.KEYCODE_DEL to "\b", + KeyEvent.KEYCODE_FORWARD_DEL to "\u007f", + KeyEvent.KEYCODE_ENTER to "\r", + KeyEvent.KEYCODE_TAB to "\t", + )) { + texts.clear() + assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, keyCode))) + assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, keyCode))) + assertEquals("one down plus one up must queue exactly one control", + listOf(control), texts) + } + assertTrue("soft edit keys must not reach the key event route", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun modifiedSoftKeysStillTravelAsKeyEvents() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, + KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON))) + idle() + + assertEquals("a modifier shortcut must keep using key events", + listOf(KeyEvent.KEYCODE_ENTER), keys.map { it.keyCode }) + assertTrue(texts.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun unmodifiedSoftDownStaysSoftWhenTheUpGainsAModifier() { + host.show() + idle() + val connection = connection() + + assertTrue(connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))) + assertTrue(connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, KeyEvent.META_CTRL_ON))) + idle() + + assertEquals("a plain press must stay a soft edit for its whole press", listOf("\r"), texts) + assertTrue("the matching up must follow the route picked on down", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun modifiedSoftDownStaysAKeyEventWhenTheUpLosesTheModifier() { + host.show() + idle() + val connection = connection() + + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, KeyEvent.META_SHIFT_ON)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)) + idle() + + assertEquals("a shortcut press keeps both of its key events", + listOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_ENTER), keys.map { it.keyCode }) + assertTrue("a shortcut press must not leak into the text channel", texts.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun repeatedSoftDownKeepsOneRouteAcrossModifierChanges() { + host.show() + idle() + val connection = connection() + + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) + connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON, repeat = 2)) + connection.sendKeyEvent( + keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON)) + idle() + + assertEquals("autorepeat must stay on the soft control route", listOf("\b", "\b"), texts) + assertTrue("autorepeat must not turn into key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun interleavedSoftKeysKeepTheirOwnRoutes() { + host.show() + idle() + val connection = connection() + + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, KeyEvent.META_CTRL_ON)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL, KeyEvent.META_CTRL_ON)) + connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB)) + idle() + + assertEquals("only the plain press is a soft edit", listOf("\b"), texts) + assertEquals("the shortcut press keeps both of its key events", + listOf(KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_TAB), keys.map { it.keyCode }) + } + + @Config(sdk = [33]) + @Test fun typedChatTextAndSoftEditsStayOrdered() { + host.type("你好😀") + host.tap(KeyEvent.KEYCODE_DEL) + host.tap(KeyEvent.KEYCODE_ENTER) + idle() + + assertEquals("text, delete and enter must keep their order", + listOf("你好😀", "\b", "\r"), texts) + assertTrue("chat text and edits must not become key events", keys.isEmpty()) + } + + @Config(sdk = [33]) + @Test fun tappingEscapeStillSendsKeyEvents() { + host.tap(KeyEvent.KEYCODE_ESCAPE) + idle() + + assertEquals("escape must keep its down/up pair", + listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP), keys.map { it.action }) + assertEquals("escape must target the escape key", + listOf(KeyEvent.KEYCODE_ESCAPE, KeyEvent.KEYCODE_ESCAPE), keys.map { it.keyCode }) + assertTrue("escape must not use the text channel", texts.isEmpty()) + } + + private fun keyEvent(action: Int, keyCode: Int, metaState: Int = 0, repeat: Int = 0) = + KeyEvent(0L, 0L, action, keyCode, repeat, metaState) + + private fun connection(): InputConnection { + val connection = host.onCreateInputConnection(EditorInfo()) + assertNotNull("shown host must expose an input connection", connection) + return connection!! + } + private fun idle() = shadowOf(Looper.getMainLooper()).idle() } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt index 879c18233c..f4eac6423c 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt @@ -46,6 +46,7 @@ class SessionInputPointerTest { CompositorShadow.pointers.clear() CompositorShadow.events.clear() CompositorShadow.keys.clear() + CompositorShadow.ordered.clear() WriterShadow.mouse.clear() WriterShadow.beforeWheel = null } @@ -151,7 +152,8 @@ class SessionInputPointerTest { fun hardwareCtrl(down: Boolean) = ReflectionHelpers.callInstanceMethod(activity, "sendGuestKey", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 97), ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, down), - ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8)) + ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8), + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false)) output.key(29, true) hardwareCtrl(true) hardwareCtrl(false) @@ -249,10 +251,26 @@ class SessionInputPointerTest { @Test fun wowFieldSelectionPreservesCtrlHeldByTheInputProfile() { output.key(29, true) ReflectionHelpers.callInstanceMethod(activity, "selectGameField", - ReflectionHelpers.ClassParameter.from(IntArray::class.java, intArrayOf(46))) - assertEquals(listOf(29 to 1, 30 to 1, 30 to 0, 46 to 1, 46 to 0), CompositorShadow.keys) + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertEquals(listOf("select:true"), CompositorShadow.ordered) + assertEquals(listOf(29 to 1), CompositorShadow.keys) output.key(29, false) - assertEquals(29 to 0, CompositorShadow.keys.last()) + assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys) + } + + @Test fun wowChatQueuesCaretKeysBeforeAtomicTextAndSubmit() { + ReflectionHelpers.setField(activity, "keyboard", + KeyboardHost(activity, { false }, WaylandCompositor::textInputCommit)) + fun send(replace: Boolean) = ReflectionHelpers.callInstanceMethod(activity, "sendWowChat", + ReflectionHelpers.ClassParameter.from(String::class.java, "中文"), + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType!!, replace)) + send(true) + assertEquals(listOf("select:false", "submit:中文"), + CompositorShadow.ordered) + CompositorShadow.ordered.clear() + send(false) + assertEquals(listOf("key:107:1", "key:107:0", "submit:中文"), CompositorShadow.ordered) + assertEquals(emptyList>(), CompositorShadow.keys) } @Test fun horizontalWheelFinishesBeforeRawMouseDestruction() { @@ -311,10 +329,15 @@ class SessionInputPointerTest { val pointers = mutableListOf>() val events = mutableListOf>() val keys = mutableListOf>() + val ordered = mutableListOf() @JvmStatic @Implementation fun __staticInitializer__() {} @JvmStatic @Implementation fun nativeSendPointer(action: Int, x: Int, y: Int) { pointers += Triple(action, x, y) } @JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) { events += Triple(type, code, value) } @JvmStatic @Implementation fun nativeSendKey(code: Int, value: Int) { keys += code to value } + @JvmStatic @Implementation fun nativeSendKeyOrdered(code: Int, value: Int) { ordered += "key:$code:$value" } + @JvmStatic @Implementation fun nativeSelectGameField(copy: Boolean) { ordered += "select:$copy" } + @JvmStatic @Implementation fun textInputCommit(text: String) { ordered += "text:$text" } + @JvmStatic @Implementation fun textInputCommitAndSubmit(text: String) { ordered += "submit:$text" } } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt new file mode 100644 index 0000000000..9304c242c6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionTextInputTest.kt @@ -0,0 +1,314 @@ +package com.droiddeck.launcher.input + +import android.net.LocalSocket +import android.net.LocalSocketAddress +import android.os.Looper +import android.system.Os +import android.system.OsConstants +import com.droiddeck.launcher.wayland.WaylandCompositor +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.annotation.LooperMode +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], shadows = [SessionTextInputTest.ShadowLocalSocket::class, SessionTextInputTest.ShadowWaylandCompositor::class]) +@LooperMode(LooperMode.Mode.PAUSED) +class SessionTextInputTest { + + @Before + fun setUp() { + ShadowLocalSocket.reset() + ShadowWaylandCompositor.reset() + shadowOf(Looper.getMainLooper()).idle() + } + + @After + fun tearDown() { + shadowOf(Looper.getMainLooper()).idle() + } + + @Test + fun retriesUntilGuestProvesReadyThenCompletes() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + assertTrue(ShadowWaylandCompositor.submit(73)) + shadowOf(Looper.getMainLooper()).idle() + val negative = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(73 to WaylandCompositor.TEXT_UNRESOLVED, negative) + + val firstAttempt = ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS) + assertEquals(1, firstAttempt) + val retryAttempt = ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS) + assertEquals(2, retryAttempt) + + ShadowLocalSocket.proofAvailable.set(true) + shadowOf(Looper.getMainLooper()).idle() + + val completion = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(73 to WaylandCompositor.TEXT_NOT_DELIVERED, completion) + assertEquals(1, ShadowLocalSocket.frameCount.get()) + assertNull(ShadowWaylandCompositor.completions.poll()) + } finally { + input.stop() + } + } + + @Test + fun stopCancelsPendingRetryAndNewGenerationCanSucceed() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + assertTrue(ShadowWaylandCompositor.submit(74)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ShadowLocalSocket.attemptsQueue.poll(5, TimeUnit.SECONDS)) + val negative = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(74 to WaylandCompositor.TEXT_UNRESOLVED, negative) + + input.stop() + shadowOf(Looper.getMainLooper()).idle() + + val extra = ShadowLocalSocket.attemptsQueue.poll(600, TimeUnit.MILLISECONDS) + assertNull(extra) + + ShadowLocalSocket.proofAvailable.set(true) + input.start() + shadowOf(Looper.getMainLooper()).idle() + + val completion = ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS) + assertEquals(74 to WaylandCompositor.TEXT_NOT_DELIVERED, completion) + assertEquals(1, ShadowLocalSocket.frameCount.get()) + } finally { + input.stop() + } + } + + @Test + fun replacementActivityRecoversPendingTokenAndKeepsItsListener() { + val app = RuntimeEnvironment.getApplication() + val first = SessionTextInput(app) { true } + val replacement = SessionTextInput(app) { true } + try { + first.start() + assertTrue(ShadowWaylandCompositor.submit(80)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(80 to WaylandCompositor.TEXT_UNRESOLVED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + first.stop() + replacement.start() + first.stop() + ShadowLocalSocket.proofAvailable.set(true) + assertEquals(80 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.frameCount.get()) + ShadowLocalSocket.frameAck.set(1) + assertTrue(ShadowWaylandCompositor.submit(81)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(81 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(2, ShadowLocalSocket.frameCount.get()) + } finally { + replacement.stop() + first.stop() + } + } + + @Test + fun guestRefusalCompletesWithoutProbeAndNextCommitIsDelivered() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.frameAck.set(0) + assertTrue(ShadowWaylandCompositor.submit(75)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(75 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertNull(ShadowLocalSocket.attemptsQueue.poll()) + ShadowLocalSocket.frameAck.set(1) + assertTrue(ShadowWaylandCompositor.submit(76)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(76 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertNull(ShadowLocalSocket.attemptsQueue.poll()) + } finally { + input.stop() + } + } + + @Test + fun successfulProbeDoesNotConvertMissingCommitAckToDelivered() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.proofAvailable.set(true) + assertTrue(ShadowWaylandCompositor.submit(77)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(77 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.attemptsQueue.poll()) + assertNull(ShadowWaylandCompositor.completions.poll()) + } finally { + input.stop() + } + } + + @Test + fun nativeReadTimeoutCancelsThenHonorsDeliveredAck() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.frameReadError = IOException(Os.strerror(OsConstants.EAGAIN)) + ShadowLocalSocket.frameAck.set(1) + assertTrue(ShadowWaylandCompositor.submit(82)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(82 to WaylandCompositor.TEXT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.shutdowns.get()) + assertNull(ShadowLocalSocket.attemptsQueue.poll()) + } finally { + input.stop() + } + } + + @Test + fun brokenSocketUsesRecoveryAfterFinalAckReadAlsoFails() { + val input = SessionTextInput(RuntimeEnvironment.getApplication()) { true } + try { + input.start() + ShadowLocalSocket.frameReadError = IOException("Connection reset by peer") + ShadowLocalSocket.finalFrameReadError = IOException("Socket closed") + ShadowLocalSocket.proofAvailable.set(true) + assertTrue(ShadowWaylandCompositor.submit(83)) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(83 to WaylandCompositor.TEXT_NOT_DELIVERED, ShadowWaylandCompositor.completions.poll(5, TimeUnit.SECONDS)) + assertEquals(1, ShadowLocalSocket.shutdowns.get()) + assertEquals(1, ShadowLocalSocket.attemptsQueue.poll()) + } finally { + input.stop() + } + } + + @Implements(LocalSocket::class) + class ShadowLocalSocket { + private val written = ByteArrayOutputStream() + private var connected = false + + @Implementation + fun connect(address: LocalSocketAddress) { connected = true } + + @Implementation + fun setSoTimeout(timeout: Int) { + if (!connected) throw IOException("socket not created") + } + + @Implementation + fun getOutputStream(): OutputStream = object : OutputStream() { + override fun write(b: Int) { written.write(b) } + override fun write(b: ByteArray, off: Int, len: Int) { written.write(b, off, len) } + } + + @Implementation + fun getInputStream(): InputStream { + val bytes = written.toByteArray() + val isProbe = bytes.size == 4 && bytes.all { it == 0.toByte() } + return if (isProbe) { + probeCount.incrementAndGet() + val allowProof = proofAvailable.get() + attemptsQueue.offer(probeCount.get()) + ByteArrayInputStream(byteArrayOf(if (allowProof) 0 else 42)) + } else { + frameCount.incrementAndGet() + object : InputStream() { + private var attempts = 0 + override fun read(): Int { + val error = if (attempts++ == 0) frameReadError else finalFrameReadError + if (error != null) throw error + return frameAck.get() + } + } + } + } + + @Implementation + fun close() {} + + @Implementation + fun shutdownOutput() { shutdowns.incrementAndGet() } + + companion object { + private val probeCount = AtomicInteger(0) + val attemptsQueue = LinkedBlockingQueue() + val frameCount = AtomicInteger(0) + val frameAck = AtomicInteger(42) + val shutdowns = AtomicInteger(0) + @Volatile var frameReadError: IOException? = null + @Volatile var finalFrameReadError: IOException? = null + val proofAvailable = java.util.concurrent.atomic.AtomicBoolean(false) + + fun reset() { + probeCount.set(0) + attemptsQueue.clear() + frameCount.set(0) + frameAck.set(42) + shutdowns.set(0) + frameReadError = null + finalFrameReadError = null + proofAvailable.set(false) + } + } + } + + @Implements(WaylandCompositor::class, isInAndroidSdk = false) + class ShadowWaylandCompositor { + companion object { + val completions = LinkedBlockingQueue>() + @Volatile private var listener: WaylandCompositor.TextInputFallbackListener? = null + + fun reset() { + completions.clear() + listener = null + } + + fun submit(token: Int): Boolean = listener!!.onTextInputFallback("abc", token) + + @Implementation + @JvmStatic + fun __staticInitializer__() {} + + @Implementation + @JvmStatic + fun completeTextInputFallback(token: Int, result: Int) { + completions.offer(token to result) + } + + @Implementation + @JvmStatic + fun setTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?) { + listener = l + } + + @Implementation + @JvmStatic + fun isTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?): Boolean = + listener != null && listener === l + + @Implementation + @JvmStatic + fun clearTextInputFallbackListener(l: WaylandCompositor.TextInputFallbackListener?) { + if (listener === l) listener = null + } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt new file mode 100644 index 0000000000..f5ceb5b623 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BottomDesktopInputTest.kt @@ -0,0 +1,94 @@ +package com.droiddeck.launcher.session + +import android.os.Handler +import android.os.Looper +import android.os.Messenger +import android.view.KeyEvent +import android.view.inputmethod.EditorInfo +import com.droiddeck.launcher.input.KeyboardHost +import com.droiddeck.launcher.wayland.BottomDesktopCompositorService +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = android.app.Application::class) +class BottomDesktopInputTest { + + private data class Sent(val what: Int, val arg1: Int, val arg2: Int, val text: String?) + + private val sent = ArrayList() + private val key = BottomDesktopCompositorService.MSG_KEY + private val text = BottomDesktopCompositorService.MSG_TEXT + private val textKey = BottomDesktopCompositorService.KEY_TEXT + + private lateinit var desktop: BottomDesktop + private var original: Messenger? = null + + @Before + fun setUp() { + desktop = BottomDesktop + original = ReflectionHelpers.getField(desktop, "service") + sent.clear() + val recorder = Handler(Looper.getMainLooper(), Handler.Callback { msg -> + sent.add(Sent(msg.what, msg.arg1, msg.arg2, msg.data?.getString(textKey))) + true + }) + ReflectionHelpers.setField(desktop, "service", Messenger(recorder)) + } + + @After + fun tearDown() { + shadowOf(Looper.getMainLooper()).idle() + ReflectionHelpers.setField(desktop, "service", original) + } + + @Test + fun pureControlBatchSendsOneDownAndOneUpPerChar() { + BottomDesktop.sendText("\r\n\b\u007f\t") + shadowOf(Looper.getMainLooper()).idle() + assertEquals( + press(28) + press(28) + press(14) + press(111) + press(15), + sent + ) + assertTrue(sent.none { it.what == text }) + } + + @Test + fun ordinaryTextIncludingSupplementaryAndNewlineIsOneTextMessage() { + val value = "中文😀\nline" + BottomDesktop.sendText(value) + shadowOf(Looper.getMainLooper()).idle() + assertEquals(listOf(Sent(text, 0, 0, value)), sent) + } + + @Test + fun keyboardHostOrderMatchesImeEditingSequence() { + val host = KeyboardHost(RuntimeEnvironment.getApplication(), { true }, { BottomDesktop.sendText(it) }) + ReflectionHelpers.setField(host, "shown", true) + val connection = host.onCreateInputConnection(EditorInfo())!! + connection.commitText("中文", 1) + connection.performEditorAction(EditorInfo.IME_ACTION_NONE) + connection.deleteSurroundingText(1, 0) + connection.deleteSurroundingText(0, 1) + assertTrue(connection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB))) + assertTrue(connection.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_TAB))) + shadowOf(Looper.getMainLooper()).idle() + assertEquals( + listOf(Sent(text, 0, 0, "中文")) + press(28) + press(14) + press(111) + press(15), + sent + ) + assertEquals(1, sent.count { it.what == key && it.arg1 == 15 && it.arg2 == 1 }) + assertEquals(1, sent.count { it.what == key && it.arg1 == 15 && it.arg2 == 0 }) + } + + private fun press(evdev: Int) = listOf(Sent(key, evdev, 1, null), Sent(key, evdev, 0, null)) +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt new file mode 100644 index 0000000000..d88af65090 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SecondScreenImeTest.kt @@ -0,0 +1,177 @@ +package com.droiddeck.launcher.ui + +import androidx.activity.ComponentActivity +import android.hardware.display.DisplayManager +import android.os.Looper +import android.view.Display +import android.view.KeyEvent +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.input.KeyboardHost +import com.droiddeck.launcher.input.SecondScreenMode +import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.wayland.WaylandCompositor +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.android.controller.ActivityController +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.util.ReflectionHelpers +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w800dp-h600dp", shadows = [SecondScreenImeTest.CompositorShadow::class]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class SecondScreenImeTest { + private var previousMode = "" + private var previousDeckPad = false + + @Before fun setUp() { + previousMode = SessionState.mode + previousDeckPad = SessionState.deckPad + SessionState.deckPad = false + CompositorShadow.commits.clear() + } + + @After fun tearDown() { + SessionState.mode = previousMode + SessionState.deckPad = previousDeckPad + } + + @Test fun editorActionClosesFieldKeyboardAfterOneCommit() { + var closes = 0 + val fixture = keyboard(forField = true) { closes++ } + try { + assertTrue(fixture.connection.performEditorAction(EditorInfo.IME_ACTION_SEND)) + idle() + + assertEquals(listOf("\r"), CompositorShadow.commits) + assertEquals(1, closes) + assertFalse(fixture.host.shown) + assertFalse(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + @Test fun unmodifiedEnterKeyClosesFieldKeyboard() { + var closes = 0 + val fixture = keyboard(forField = true) { closes++ } + try { + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))) + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP))) + idle() + + assertEquals(listOf("\r"), CompositorShadow.commits) + assertEquals(1, closes) + assertFalse(fixture.host.shown) + assertFalse(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + @Test fun ordinaryTextAndNewlineLeaveFieldKeyboardOpen() { + var closes = 0 + val fixture = keyboard(forField = true) { closes++ } + try { + assertTrue(fixture.connection.commitText("hello", 1)) + assertTrue(fixture.connection.commitText("line\n", 1)) + idle() + + assertEquals(listOf("hello", "line\n"), CompositorShadow.commits) + assertEquals(0, closes) + assertTrue(fixture.host.shown) + assertTrue(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + @Test fun enterLeavesNonFieldKeyboardOpen() { + var closes = 0 + val fixture = keyboard(forField = false) { closes++ } + try { + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_DOWN))) + assertTrue(fixture.connection.sendKeyEvent(keyEvent(KeyEvent.ACTION_UP))) + idle() + + assertEquals(listOf("\r"), CompositorShadow.commits) + assertEquals(0, closes) + assertTrue(fixture.host.shown) + assertFalse(fixture.panel.fieldKeyboardOpen) + } finally { + fixture.close() + } + } + + private fun keyboard(forField: Boolean, onClosed: () -> Unit): Fixture { + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY) + val panel = SecondScreenPresentation(activity, display, {}, {}, {}, onKeyboardClosed = onClosed) + panel.show() + panel.showMode(SecondScreenMode.CUSTOM_CONTROLS) + panel.requestKeyboard(forField) + val host: KeyboardHost = ReflectionHelpers.getField(panel, "keyboardHost") + val root: View = ReflectionHelpers.getField(panel, "root") + val owner = Robolectric.buildActivity(ComponentActivity::class.java).setup() + try { + (root.parent as ViewGroup).removeView(root) + owner.get().setContentView(root) + host.show() + idle() + assertTrue("Presentation root is not attached to window after host.show()", root.isAttachedToWindow) + assertTrue(host.shown) + val connection = host.onCreateInputConnection(EditorInfo()) + assertNotNull(connection) + return Fixture(panel, host, connection!!, owner) + } catch (t: Throwable) { + panel.closeControls() + owner.pause().stop().destroy() + throw t + } + } + + private fun keyEvent(action: Int) = KeyEvent(0L, 0L, action, KeyEvent.KEYCODE_ENTER, 0) + + private fun idle() = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(50)) + + private data class Fixture( + val panel: SecondScreenPresentation, + val host: KeyboardHost, + val connection: InputConnection, + val owner: ActivityController, + ) { + fun close() { + panel.closeControls() + owner.pause().stop().destroy() + } + } + + @Implements(WaylandCompositor::class, isInAndroidSdk = false) + class CompositorShadow { + companion object { + val commits = mutableListOf() + + @JvmStatic @Implementation fun __staticInitializer__() {} + + @JvmStatic @Implementation fun textInputCommit(text: String) { + commits += text + } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt b/app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt new file mode 100644 index 0000000000..12811f8d54 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorInputTest.kt @@ -0,0 +1,122 @@ +package com.droiddeck.launcher.wayland + +import android.app.Application +import android.content.Intent +import android.os.Bundle +import android.os.Looper +import android.os.Message +import android.os.Messenger +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class, shadows = [BottomDesktopCompositorInputTest.CompositorShadow::class]) +class BottomDesktopCompositorInputTest { + @Before fun setUp() { + CompositorShadow.calls.clear() + } + + @Test fun chineseTextThenEnterUsesTheOrderedHostQueue() { + withService { messenger -> + messenger.send(text("中文输入")) + messenger.send(key(KEY_ENTER, PRESSED)) + messenger.send(key(KEY_ENTER, RELEASED)) + idle() + + assertEquals(listOf("text:中文输入", "key:28:1", "key:28:0"), CompositorShadow.calls) + assertTrue(CompositorShadow.calls.none { it.startsWith("unordered") }) + } + } + + @Test fun editingKeysAndTextShareOneOrderedQueue() { + withService { messenger -> + messenger.send(text("ab")) + messenger.send(key(KEY_BACKSPACE, PRESSED)) + messenger.send(key(KEY_BACKSPACE, RELEASED)) + messenger.send(key(KEY_DELETE, PRESSED)) + messenger.send(key(KEY_DELETE, RELEASED)) + messenger.send(key(KEY_TAB, PRESSED)) + messenger.send(key(KEY_TAB, RELEASED)) + messenger.send(text("cd")) + messenger.send(key(KEY_DOWN, PRESSED)) + messenger.send(key(KEY_DOWN, RELEASED)) + messenger.send(key(KEY_UP, PRESSED)) + messenger.send(key(KEY_UP, RELEASED)) + idle() + + assertEquals( + listOf( + "text:ab", + "key:14:1", "key:14:0", + "key:111:1", "key:111:0", + "key:15:1", "key:15:0", + "text:cd", + "key:108:1", "key:108:0", + "key:103:1", "key:103:0", + ), + CompositorShadow.calls, + ) + assertTrue(CompositorShadow.calls.none { it.startsWith("unordered") }) + } + } + + private fun withService(block: (Messenger) -> Unit) { + val controller = Robolectric.buildService(BottomDesktopCompositorService::class.java).create() + try { + val messenger = Messenger(controller.get().onBind(Intent())) + block(messenger) + } finally { + controller.destroy() + } + } + + private fun text(value: String) = Message.obtain(null, BottomDesktopCompositorService.MSG_TEXT).apply { + data = Bundle().apply { putString(BottomDesktopCompositorService.KEY_TEXT, value) } + } + + private fun key(code: Int, state: Int) = + Message.obtain(null, BottomDesktopCompositorService.MSG_KEY, code, state) + + private fun idle() = shadowOf(Looper.getMainLooper()).idle() + + companion object { + private const val KEY_ENTER = 28 + private const val KEY_BACKSPACE = 14 + private const val KEY_DELETE = 111 + private const val KEY_TAB = 15 + private const val KEY_DOWN = 108 + private const val KEY_UP = 103 + private const val PRESSED = 1 + private const val RELEASED = 0 + } + + @Implements(WaylandCompositor::class, isInAndroidSdk = false) + class CompositorShadow { + companion object { + val calls = mutableListOf() + + @JvmStatic @Implementation fun __staticInitializer__() {} + + @JvmStatic @Implementation fun textInputCommit(text: String) { + calls += "text:$text" + } + + @JvmStatic @Implementation fun nativeSendKey(evdev: Int, state: Int) { + calls += "unordered:$evdev:$state" + } + + @JvmStatic @Implementation fun nativeSendKeyOrdered(evdev: Int, state: Int) { + calls += "key:$evdev:$state" + } + } + } +} diff --git a/docs/testing/chinese-input.md b/docs/testing/chinese-input.md new file mode 100644 index 0000000000..ef2546efce --- /dev/null +++ b/docs/testing/chinese-input.md @@ -0,0 +1,23 @@ +# Chinese input + +The app ships a pinyin input method payload with the session files; it needs no network at run time. + +## Android keyboard + +1. Select your Android input method (for example Sogou or Gboard) in the system settings, then start a DroidDeck session and open its Android keyboard. +2. Type pinyin, pick a candidate, and commit it; confirm mixed Chinese/Latin and emoji text such as `中文` and `😀` arrives in the focused field, and that a backspace or Enter sent after a commit stays after it. + +## Steam on-screen keyboard + +Steam pinyin requires a Linux runtime built with IBus. The APK installs the pinyin engine and its data, but does not replace an installed Linux runtime. A runtime without IBus can still start Steam and cannot offer pinyin until it is updated. + +Start a Steam session, open Steam's on-screen keyboard on a text field, switch it to Simplified Chinese (pinyin), and confirm committing a candidate puts the characters in the field. Physical keys, shortcuts, and Latin input keep working as before. + +## X11 text-input fallback + +For clients without native Wayland text input, committed Android IME text is delivered to the focused X11 display. + +- **One focused display.** Text goes only to the focused X11 display. +- **Mappings stay stable.** Each keysym keeps its keycode and mapping until the helper exits, because clients may decode key events after they arrive. +- **Capacity is finite.** Only originally empty, non-modifier, unheld keycodes 8..255 can be reserved (at most 248 per display, in practice fewer); a frame that needs more distinct symbols than remain is refused before anything is injected, so restart the session to reclaim the slots. +- **Scope of the limitation.** Steam's own built-in IBus pinyin keyboard and native Wayland text input do not use this fallback and are not subject to it. diff --git a/tools/build_local.sh b/tools/build_local.sh index b5d15acea6..3c4feff55f 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -50,7 +50,7 @@ if ! command -v docker >/dev/null 2>&1; then echo "Docker is required to cross-compile the glibc ARM64 preload libraries." >&2 exit 1 fi -for tool in curl tar zstd shasum unzip python3 go; do +for tool in curl tar zstd shasum unzip python3 go rpm2cpio cpio; do if ! command -v "${tool}" >/dev/null 2>&1; then echo "${tool} is required to build the CI-equivalent APK." >&2 exit 1 @@ -540,6 +540,8 @@ if [[ "${DROIDDECK_SKIP_RUST:-0}" != 1 ]]; then fi python3 tools/powervr/fetch.py bash tools/packs/build.sh app/build/packs +mkdir -p "${cache_dir}/ime" +python3 "${repo_root}/tools/ime/prepare.py" --packages "${cache_dir}/ime" --download --output "${linuxfs_dir}" python3 tools/release/runtime_inputs.py record ./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg} python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk" diff --git a/tools/components/recipes.json b/tools/components/recipes.json index 5cccf80ffa..9f78ac708b 100644 --- a/tools/components/recipes.json +++ b/tools/components/recipes.json @@ -15,6 +15,7 @@ "tools/msitools", "tools/pipewire", "tools/vr", + "tools/ime", "tools/gpuload", "app/src/main/cpp/waylandcomp/generated", "app/src/main/cpp/waylandcomp/src/headpose_shm.h", @@ -24,6 +25,10 @@ "outputs": [ "app/src/main/assets/linuxfs/usr/local/bin/gamescope", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-vr/droiddeck/bin/linuxarm64/driver_droiddeck.so", + "app/src/main/assets/linuxfs/usr/local/share/droiddeck/ime-files.json", + "app/src/main/assets/linuxfs/usr/local/share/droiddeck/ibus.profile", + "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ime/ibus-engine-pinyin", + "app/src/main/assets/linuxfs/usr/share/pyzy/db/android.db", "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-gpuload/libVkLayer_droiddeck_gpuload.so" ], "ndk": true, @@ -32,7 +37,9 @@ "libc6-dev-arm64-cross", "g++-aarch64-linux-gnu", "libvulkan1", - "mesa-vulkan-drivers" + "mesa-vulkan-drivers", + "rpm2cpio", + "cpio" ] }, "esync": { diff --git a/tools/components/recipes/runtime.sh b/tools/components/recipes/runtime.sh index 9de7efba18..70628c5638 100644 --- a/tools/components/recipes/runtime.sh +++ b/tools/components/recipes/runtime.sh @@ -12,6 +12,8 @@ done for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do [ -f "$f" ] && install -Dm644 "$f" "$D/${f#tools/linuxfs/overlay/}" done +mkdir -p app/build/ime-packages +python3 tools/ime/prepare.py --packages app/build/ime-packages --download --output "$D" if [ -f tools/gamescope/release.env ]; then . tools/gamescope/release.env curl -fsSL --retry 5 --retry-all-errors --connect-timeout 20 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst" diff --git a/tools/docker_platform.sh b/tools/docker_platform.sh index 3360c81ec0..40e38e7d97 100644 --- a/tools/docker_platform.sh +++ b/tools/docker_platform.sh @@ -4,7 +4,7 @@ if [[ -z "${docker_platform}" ]]; then fi case "${docker_platform}" in linux/arm64|linux/arm64/*) docker_platform=linux/arm64 ;; esac if [[ -z "${DROIDDECK_BUILD_IMAGE:-}" ]]; then - DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v4 + DROIDDECK_BUILD_IMAGE=droiddeck-local-cross:24.04-v5 [[ "${docker_platform}" == linux/arm64 ]] && DROIDDECK_BUILD_IMAGE+=-arm64 fi export DROIDDECK_DOCKER_PLATFORM=${docker_platform} DROIDDECK_BUILD_IMAGE diff --git a/tools/ime/packages.json b/tools/ime/packages.json new file mode 100644 index 0000000000..846dfebcea --- /dev/null +++ b/tools/ime/packages.json @@ -0,0 +1,27 @@ +{ + "version": 1, + "release": "Fedora 44 Everything aarch64", + "mirror": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/", + "packages": { + "ibus-pinyin": { + "filename": "ibus-pinyin-1.5.1-7.fc44.aarch64.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/i/ibus-pinyin-1.5.1-7.fc44.aarch64.rpm", + "sha256": "fcae3a5f4263c005efa0751737bd653d4dca8ca53777362ad519f6bcbd99587c" + }, + "pyzy": { + "filename": "pyzy-0.1.0-37.fc44.aarch64.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-0.1.0-37.fc44.aarch64.rpm", + "sha256": "aa41dfdaa052ac5432e2fd4c64ea706a7153b6e7b72f18bf1633006f7190b76f" + }, + "pyzy-db-android": { + "filename": "pyzy-db-android-0.1.0-37.fc44.noarch.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/p/pyzy-db-android-0.1.0-37.fc44.noarch.rpm", + "sha256": "bcaafe36fc93b892b1901607c887fd4efbc47eaa5b829bfe0347aa3137f41576" + }, + "lua-libs": { + "filename": "lua-libs-5.4.8-5.fc44.aarch64.rpm", + "url": "https://mirrors.kernel.org/fedora/releases/44/Everything/aarch64/os/Packages/l/lua-libs-5.4.8-5.fc44.aarch64.rpm", + "sha256": "d719e35a8c2f771084f0b0d135a3ac68c51b032fc2199507685fe3ea32cee8fc" + } + } +} diff --git a/tools/ime/prepare.py b/tools/ime/prepare.py new file mode 100644 index 0000000000..be290f346f --- /dev/null +++ b/tools/ime/prepare.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Prepare the pinned pinyin engine and its runtime dependencies.""" + +import argparse +import hashlib +import json +from pathlib import Path, PurePosixPath +import shutil +import subprocess +import tempfile +import urllib.request +import xml.etree.ElementTree as ElementTree + +PACKAGES = Path(__file__).with_name('packages.json') +LIBRARY_DIR = 'usr/local/lib/droiddeck-ime' +ENGINE_NAME = 'ibus-engine-pinyin' +ENGINE_MEMBERS = ('usr/libexec/' + ENGINE_NAME, 'usr/bin/' + ENGINE_NAME) +COMPONENT = 'usr/share/ibus/component/pinyin.xml' +PROFILE = 'usr/local/share/droiddeck/ibus.profile' +MANIFEST = 'usr/local/share/droiddeck/ime-files.json' +LICENSES = 'usr/local/share/licenses/droiddeck-ime' +PROFILE_TEXT = 'user-db:user\nsystem-db:ibus\n' +# The engine links these by soname, so the dereferenced copies keep the RPM member names. +LIBRARIES = {'pyzy': ('usr/lib64/libpyzy-1.0.so.0',), + 'lua-libs': ('usr/lib64/liblua-5.4.so', 'usr/lib64/liblua-5.4.so.0')} +DATA = {'ibus-pinyin': ('usr/share/ibus-pinyin/base.lua', 'usr/share/ibus-pinyin/phrases.txt', + 'usr/share/ibus-pinyin/db/english.db'), + 'pyzy': ('usr/share/pyzy/phrases.txt',), + 'pyzy-db-android': ('usr/share/pyzy/db/android.db',)} +NOTICES = ('COPYING', 'LICENSE', 'COPYRIGHT', 'README', 'NOTICE') + + +def digest(path): + result = hashlib.sha256() + with path.open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + result.update(block) + return result.hexdigest() + + +def specifications(): + return json.loads(PACKAGES.read_text())['packages'] + + +def fetch(directory, spec): + directory.mkdir(parents=True, exist_ok=True) + path = directory / spec['filename'] + pending = path.with_name(path.name + '.pending') + with urllib.request.urlopen(spec['url'], timeout=60) as response, pending.open('wb') as stream: + shutil.copyfileobj(response, stream) + if digest(pending) != spec['sha256']: + pending.unlink() + raise ValueError('SHA256 mismatch for downloaded ' + spec['filename']) + pending.replace(path) + return path + + +def verified(directory, download=False): + sources = {} + for name, spec in specifications().items(): + path = directory / spec['filename'] + if download and not (path.is_file() and digest(path) == spec['sha256']): + path = fetch(directory, spec) + if not path.is_file(): + raise ValueError('missing RPM ' + spec['filename']) + if digest(path) != spec['sha256']: + raise ValueError('SHA256 mismatch for ' + spec['filename']) + sources[name] = path + return sources + + +def extract(name, rpm, destination): + for tool in ('rpm2cpio', 'cpio'): + if shutil.which(tool) is None: + raise ValueError(tool + ' is required to unpack the RPM payload') + destination.mkdir(parents=True) + with tempfile.TemporaryFile(dir=destination.parent) as payload: + subprocess.run(['rpm2cpio', str(rpm)], stdout=payload, check=True) + payload.seek(0) + listing = subprocess.run(['cpio', '-it', '--quiet'], stdin=payload, + stdout=subprocess.PIPE, check=True) + payload.seek(0) + for line in listing.stdout.splitlines(): + path = PurePosixPath(line.decode('utf-8', 'surrogateescape')) + if path.is_absolute() or '..' in path.parts: + raise ValueError(f'{name}: RPM payload contains unsafe path {path}') + subprocess.run(['cpio', '-idm', '--quiet'], stdin=payload, + cwd=destination, check=True) + + +def member(tree, name): + path = (tree / name).resolve() + if not path.is_relative_to(tree.resolve()) or not path.is_file(): + raise ValueError(f'{tree.name}: RPM payload is missing {name}') + return path + + +def install(source, target, output, files, executable=False): + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + target.chmod(0o755 if executable else 0o644) + files.add(target.relative_to(output).as_posix()) + + +def engine(tree): + for candidate in ENGINE_MEMBERS: + if (tree / candidate).is_file(): + return candidate + raise ValueError('ibus-pinyin RPM has no ' + ENGINE_NAME + ' executable') + + +def component(tree): + root = ElementTree.parse(member(tree, COMPONENT)).getroot() + for element in list(root.iter()): + for child in list(element): + if child.tag == 'setup': + element.remove(child) + executable = root.find('exec') + if executable is None: + raise ValueError('pinyin.xml has no engine exec element') + executable.text = f'/{LIBRARY_DIR}/{ENGINE_NAME} --ibus' + engines = {node.findtext('name', '').strip() for node in root.iter('engine')} + if not {'pinyin', 'bopomofo'} <= engines: + raise ValueError('pinyin.xml no longer defines the pinyin and bopomofo engines') + return root + + +def icons(root, tree, output, files): + names = set() + for node in root.iter('icon'): + text = (node.text or '').strip() + if text: + names.add(Path(text).stem if '/' in text else text) + found = sorted(path for path in (tree / 'usr/share').rglob('*') + if path.is_file() and path.suffix in ('.svg', '.png') and path.stem in names) + if names and not found: + raise ValueError('pinyin.xml icons are not in the ibus-pinyin RPM: ' + ', '.join(sorted(names))) + for path in found: + install(path, output / path.relative_to(tree), output, files) + + +def notices(name, tree, output, files): + copied = [] + for folder in ('usr/share/licenses/' + name, 'usr/share/doc/' + name): + base = tree / folder + if not base.is_dir(): + continue + for path in sorted(base.rglob('*')): + if path.is_file() and path.name.upper().startswith(NOTICES): + target = output / LICENSES / name / path.relative_to(base) + install(path, target, output, files) + copied.append(target.relative_to(output / LICENSES).as_posix()) + return copied + + +def prepare(directory, output, work=None, download=False): + specs = specifications() + sources = verified(directory, download) + output = output.resolve() + output.mkdir(parents=True, exist_ok=True) + created = work is None + work = Path(tempfile.mkdtemp(prefix='.droiddeck-ime-', dir=output.parent)) if created else Path(work) + work.mkdir(parents=True, exist_ok=True) + try: + trees = {} + for name, source in sources.items(): + trees[name] = work / name + shutil.rmtree(trees[name], ignore_errors=True) + extract(name, source, trees[name]) + files = set() + pinyin = trees['ibus-pinyin'] + install(member(pinyin, engine(pinyin)), output / LIBRARY_DIR / ENGINE_NAME, output, files, executable=True) + for name, candidates in LIBRARIES.items(): + installed = [candidate for candidate in candidates if (trees[name] / candidate).exists()] + if not installed: + raise ValueError(f'{name}: RPM has none of {list(candidates)}') + for candidate in installed: + install(member(trees[name], candidate), output / LIBRARY_DIR / Path(candidate).name, output, files) + for name, members in DATA.items(): + for relative in members: + install(member(trees[name], relative), output / relative, output, files) + root = component(pinyin) + icons(root, pinyin, output, files) + target = output / COMPONENT + target.parent.mkdir(parents=True, exist_ok=True) + ElementTree.ElementTree(root).write(target, encoding='utf-8', xml_declaration=True) + files.add(COMPONENT) + profile = output / PROFILE + profile.parent.mkdir(parents=True, exist_ok=True) + profile.write_text(PROFILE_TEXT, newline='\n') + files.add(PROFILE) + packages = {} + for name, spec in specs.items(): + license_files = notices(name, trees[name], output, files) + packages[name] = {'filename': spec['filename'], 'url': spec['url'], 'sha256': spec['sha256'], + 'license_files': license_files} + if not license_files: + packages[name]['license_note'] = ('RPM bundles no separate license file; ' + 'the payload is unmodified Fedora package content') + manifest = {'version': 1, 'engine': 'pinyin', 'packages': packages, + 'files': {path: {'sha256': digest(output / path), + 'mode': f'{(output / path).stat().st_mode & 0o777:04o}'} + for path in sorted(files)}} + destination = output / MANIFEST + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(manifest, sort_keys=True, indent=2) + '\n', newline='\n') + return destination, len(files) + finally: + if created: + shutil.rmtree(work, ignore_errors=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--packages', type=Path, required=True, help='Directory with the exact pinned RPMs') + parser.add_argument('--output', type=Path, required=True, + help='Prepared linuxfs root, for example app/build/prepared-assets/linuxfs') + parser.add_argument('--work', type=Path, help='Kept extraction cache instead of a temporary directory') + parser.add_argument('--download', action='store_true', + help='Fetch missing or mismatched RPMs into --packages and verify their SHA256') + args = parser.parse_args() + try: + destination, count = prepare(args.packages, args.output, args.work, args.download) + except (OSError, ValueError, subprocess.CalledProcessError, ElementTree.ParseError) as error: + parser.exit(1, f'error: {error}\n') + print(f'Wrote {count} IME payload files; manifest {destination}') + + +if __name__ == '__main__': + main() diff --git a/tools/ime/smoke.py b/tools/ime/smoke.py new file mode 100644 index 0000000000..4a9f17bfc5 --- /dev/null +++ b/tools/ime/smoke.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Check pinyin configuration and text commits over IBus.""" + +import os +import time + +try: + import gi + + gi.require_version('IBus', '1.0') + from gi.repository import GLib, IBus +except (ImportError, ValueError) as error: + raise SystemExit(f'error: PyGObject with the IBus 1.0 typelib is required: {error}') + +CLIENT = 'droiddeck-ime-test' +ENGINE = 'pinyin' +SECTION = 'engine/Pinyin' +BOOLEAN_KEYS = ('DoublePinyin', 'InitPinyin', 'GBK') +KEYCODES = {'a': 38, 'h': 43, 'i': 31, 'n': 57, 'o': 32, 'space': 65, '1': 10} + + +def pump(seconds, condition): + deadline = time.monotonic() + seconds + while True: + GLib.MainContext.default().iteration(False) + if condition(): + return True + if time.monotonic() >= deadline: + return False + time.sleep(0.02) + + +def press(context, name): + keyval = IBus.keyval_from_name(name) + keycode = KEYCODES[name] + context.process_key_event(keyval, keycode, 0) + context.process_key_event(keyval, keycode, IBus.ModifierType.RELEASE_MASK) + + +def boolean(config, key): + value = config.get_value(SECTION, key) + if value is None or value.get_type_string() != 'b': + return None + return value.get_boolean() + + +def unchanged(value, original): + if original is None: + return value is None + return value is not None and value.print_(True) == original.print_(True) + + +def configured(bus): + config = bus.get_config() + if config is None: + raise SystemExit('error: the bus exposes no configuration service') + saved = {key: config.get_value(SECTION, key) for key in BOOLEAN_KEYS} + probed = 0 + try: + for key in BOOLEAN_KEYS: + original = saved[key] + current = original is not None and original.get_type_string() == 'b' \ + and original.get_boolean() + wanted = not current + # The PyGObject override returns None on success, so verify writes by readback. + config.set_value(SECTION, key, GLib.Variant.new_boolean(wanted)) + if not pump(3.0, lambda key=key, wanted=wanted: boolean(config, key) == wanted): + raise SystemExit(f'error: {SECTION}/{key} did not read back as written') + probed += 1 + finally: + restore_failed = [] + for key in BOOLEAN_KEYS: + original = saved[key] + try: + if original is None: + config.unset(SECTION, key) + else: + config.set_value(SECTION, key, original) + if not pump(3.0, lambda key=key, original=original: + unchanged(config.get_value(SECTION, key), original)): + restore_failed.append(key) + except GLib.Error: + restore_failed.append(key) + if restore_failed: + raise SystemExit('error: could not restore ' + SECTION + ' settings: ' + + ', '.join(restore_failed)) + return probed + + +def main(): + if not os.environ.get('IBUS_ADDRESS'): + raise SystemExit('error: IBUS_ADDRESS is not set; the smoke test needs the private ibus-daemon') + bus = IBus.Bus() + if not bus.is_connected(): + raise SystemExit('error: cannot connect to the IBus bus from IBUS_ADDRESS') + engines = {engine.get_name() for engine in bus.list_engines() or []} + if ENGINE not in engines: + raise SystemExit('error: pinyin is not registered: ' + ', '.join(sorted(engines))) + print('IBus bus connected; pinyin engine registered') + + keys = configured(bus) + print(f'engine/Pinyin config write/readback ok ({keys} boolean settings)') + + if not bus.set_global_engine(ENGINE): + raise SystemExit('error: the bus rejected the pinyin global engine') + context = bus.create_input_context(CLIENT) + state = {'candidates': 0, 'commit': ''} + + def lookup(_, table, visible): + if table is not None: + state['candidates'] = table.get_number_of_candidates() + + def commit(_, text): + state['commit'] = text.get_text() or state['commit'] + + context.connect('update-lookup-table', lookup) + context.connect('commit-text', commit) + context.set_capabilities(IBus.Capabilite.PREEDIT_TEXT | IBus.Capabilite.LOOKUP_TABLE + | IBus.Capabilite.FOCUS) + context.focus_in() + pump(1.0, lambda: False) + context.set_engine(ENGINE) + pump(1.0, lambda: False) + + for _ in range(3): + for name in 'nihao': + press(context, name) + if pump(3.0, lambda: state['candidates'] > 0): + break + else: + raise SystemExit('error: no pinyin candidates after typing the test syllable') + print('lookup table ok') + + def chinese(): + return any('\u4e00' <= character <= '\u9fff' for character in state['commit']) + + for name in ('space', '1'): + press(context, name) + if pump(3.0, chinese): + break + if not chinese(): + raise SystemExit('error: pinyin committed no Chinese text for the test syllable') + print('commit-text ok') + context.focus_out() + print('droiddeck IBus pinyin smoke test passed') + + +if __name__ == '__main__': + try: + main() + except GLib.Error as error: + raise SystemExit(f'error: IBus call failed: {error.message}') diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard index 014f305350..9db81b7e1c 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard @@ -1,7 +1,15 @@ #!/bin/bash -[ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0 -/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & -child=$! -trap 'kill "$child" 2>/dev/null' EXIT +[ -n "${DISPLAY:-}" ] || exit 0 +children=() +if [ -n "${DD_ANDROID_CLIPBOARD:-}" ]; then + /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & + children+=("$!") +fi +if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-text-input ]; then + /usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" & + children+=("$!") +fi +[ "${#children[@]}" -gt 0 ] || exit 0 +trap 'kill "${children[@]}" 2>/dev/null' EXIT trap 'exit 0' TERM INT -wait "$child" +wait "${children[@]}" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index e8a0f83db4..cced83f6f6 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -13,6 +13,12 @@ fi export HOME=${HOME:-/root} mode=${1:-desktop} shift || true + +# Steam and its helpers share one session bus per session; an existing desktop bus is inherited. +if [ "$mode" = steam ] && [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then + exec dbus-run-session -- "$0" "$mode" "$@" +fi + step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; } # Starts a long-lived program in its own Android process, which Android does not count against # the session's child processes (docs/phantom-processes.md); a normal background job otherwise. @@ -712,6 +718,13 @@ if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr dd_spawn /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" fi +ime_text_pid= +if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DISPLAY:-}" ] && [ -n "${DD_LAUNCH_DIR:-}" ] \ + && [ -x /usr/local/bin/droiddeck-text-input ]; then + /usr/local/bin/droiddeck-text-input "$DD_LAUNCH_DIR/text-input.sock" & + ime_text_pid=$! +fi + [ "${DD_DESKTOP:-}" = 1 ] || start_agent case $mode in @@ -1978,6 +1991,46 @@ case $mode in fi fi rm -f "$HOME/.dd-restart-game" "$HOME/.dd-restarted-for" + unset IBUS_ADDRESS + ime_ibus_pid= + ime_ibus_socket= + stop_steam_ime() { + if [ -n "$ime_ibus_pid" ]; then + kill "$ime_ibus_pid" 2>/dev/null || true + wait "$ime_ibus_pid" 2>/dev/null || true + ime_ibus_pid= + fi + [ -S "$ime_ibus_socket" ] && rm -f "$ime_ibus_socket" + ime_ibus_socket= + unset IBUS_ADDRESS + } + if [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ] \ + && [ -x /usr/bin/ibus-daemon ] && [ -x /usr/bin/ibus ]; then + ime_ibus_socket="${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-ibus-$$.sock" + export IBUS_ADDRESS="unix:path=$ime_ibus_socket" + /usr/local/bin/droiddeck-steam-ime & + ime_ibus_pid=$! + ime_ready=0 + _ime_deadline=$((SECONDS + 5)) + while [ "$SECONDS" -lt "$_ime_deadline" ]; do + if env -u LD_LIBRARY_PATH -u LD_PRELOAD -u GSETTINGS_SCHEMA_DIR -u DCONF_PROFILE \ + timeout 1 /usr/bin/ibus list-engine --name-only 2>/dev/null | grep -qx 'pinyin'; then + ime_ready=1 + break + fi + kill -0 "$ime_ibus_pid" 2>/dev/null || break + nap 0.1 + done + unset _ime_deadline + if [ "$ime_ready" = 1 ]; then + echo "== ime: pinyin engine ready at $IBUS_ADDRESS" + else + echo "== ime: the pinyin engine did not start at $IBUS_ADDRESS; Steam starts without Chinese input" + stop_steam_ime + fi + elif [ -x /usr/local/bin/droiddeck-steam-ime ] && [ -x /usr/local/lib/droiddeck-ime/ibus-engine-pinyin ]; then + echo "== ime: the installed Linux runtime does not include IBus; Steam starts without pinyin" + fi while :; do rm -f "$HOME/.dd-restart-once" "$HOME/.dd-restart-lost" if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then @@ -2093,6 +2146,12 @@ case $mode in kill "$games_watcher" 2>/dev/null || true wait "$games_watcher" 2>/dev/null || true fi + stop_steam_ime + if [ -n "${ime_text_pid:-}" ]; then + kill "$ime_text_pid" 2>/dev/null || true + wait "$ime_text_pid" 2>/dev/null || true + ime_text_pid= + fi if [ -n "${DD_DESKTOP:-}" ]; then if [ -n "${decky_supervisor:-}" ]; then kill "$decky_supervisor" 2>/dev/null || true diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime new file mode 100755 index 0000000000..d7d683cbc5 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime @@ -0,0 +1,7 @@ +#!/bin/bash +[ -n "${IBUS_ADDRESS:-}" ] || exit 0 +unset LD_PRELOAD LD_LIBRARY_PATH GSETTINGS_SCHEMA_DIR +export LD_LIBRARY_PATH=/usr/local/lib/droiddeck-ime +export DCONF_PROFILE=/usr/local/share/droiddeck/ibus.profile +exec /usr/bin/ibus-daemon --address "$IBUS_ADDRESS" --panel disable --config default \ + --emoji-extension disable --cache none diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input b/tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input new file mode 100755 index 0000000000..0829dcb3d8 --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input @@ -0,0 +1,510 @@ +#!/usr/bin/python3 +"""Deliver committed Android IME text to the focused X11 client.""" +import ctypes +import ctypes.util +import errno +import os +import select +import signal +import socket +import stat +import struct +import sys + +MAX_TEXT = 65536 +CANCELLABLE = 1 << 31 +CLIENT_TIMEOUT = 2.0 +PROBE_TIMEOUT = 0.5 +FOCUS_PROPERTY = b'GAMESCOPE_KEYBOARD_FOCUS_DISPLAY' +ANY_PROPERTY_TYPE = 0 +PROPERTY_WORDS = 1024 +PR_SET_PDEATHSIG = 1 +UNICODE_KEYSYM_FLAG = 0x01000000 +X11_SPECIAL_KEYSYMS = { + '\r': 0xff0d, # XK_Return + '\n': 0xff0d, # XK_Return + '\b': 0xff08, # XK_BackSpace + '\u007f': 0xffff, # XK_Delete + '\t': 0xff09, # XK_Tab +} + +_STOP = False + + +class XModifierKeymap(ctypes.Structure): + _fields_ = [('max_keypermod', ctypes.c_int), + ('modifiermap', ctypes.POINTER(ctypes.c_ubyte))] + + +class _DisplayState: + """Keep mappings stable until shutdown because clients may decode key events later.""" + + __slots__ = ('handle', 'codes', 'owned') + + def __init__(self, handle): + self.handle = handle + self.codes = {} # keysym -> keycode, stable for the session + self.owned = {} # keycode -> (width, original row) for shutdown restore + + +class XBridge: + def __init__(self): + self.lib = ctypes.CDLL(ctypes.util.find_library('X11') or 'libX11.so.6') + self.xtst = ctypes.CDLL(ctypes.util.find_library('Xtst') or 'libXtst.so.6') + self._open_displays = {} + self._declare() + + def _declare(self): + lib = self.lib + lib.XOpenDisplay.argtypes = [ctypes.c_char_p] + lib.XOpenDisplay.restype = ctypes.c_void_p + lib.XCloseDisplay.argtypes = [ctypes.c_void_p] + lib.XCloseDisplay.restype = ctypes.c_int + lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + lib.XDefaultRootWindow.restype = ctypes.c_ulong + lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] + lib.XInternAtom.restype = ctypes.c_ulong + lib.XGetWindowProperty.argtypes = [ + ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_long, ctypes.c_long, + ctypes.c_int, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_void_p)] + lib.XGetWindowProperty.restype = ctypes.c_int + lib.XFree.argtypes = [ctypes.c_void_p] + lib.XFree.restype = ctypes.c_int + lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_int)] + lib.XDisplayKeycodes.restype = ctypes.c_int + lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int, + ctypes.POINTER(ctypes.c_int)] + lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong) + lib.XChangeKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, + ctypes.POINTER(ctypes.c_ulong), ctypes.c_int] + lib.XChangeKeyboardMapping.restype = ctypes.c_int + lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] + lib.XSync.restype = ctypes.c_int + lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + lib.XQueryKeymap.restype = ctypes.c_int + lib.XGetModifierMapping.argtypes = [ctypes.c_void_p] + lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap) + lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)] + lib.XFreeModifiermap.restype = ctypes.c_int + self.xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, + ctypes.c_ulong] + self.xtst.XTestFakeKeyEvent.restype = ctypes.c_int + + def state(self, name): + existing = self._open_displays.get(name) + if existing is not None: + return existing + handle = self.lib.XOpenDisplay(name.encode()) + if not handle: + return None + state = _DisplayState(handle) + self._open_displays[name] = state + return state + + def display(self, name): + state = self.state(name) + return state.handle if state else None + + def close(self): + for state in self._open_displays.values(): + for keycode, (width, original) in state.owned.items(): + row = (ctypes.c_ulong * width)(*original) + self.lib.XChangeKeyboardMapping(state.handle, keycode, width, row, 1) + self.lib.XSync(state.handle, 0) + self.lib.XCloseDisplay(state.handle) + self._open_displays.clear() + + def target_display(self): + main = os.environ.get('DISPLAY', '').strip() + if not main: + return None + game = os.environ.get('STEAM_GAME_DISPLAY_0', '').strip() + if not game or game == main: + return main + main_display = self.display(main) + if not main_display: + return None + focused = self._focused_display(main_display) + if focused == game: + return game + if focused == main: + return main + return None + + def _focused_display(self, display): + root = self.lib.XDefaultRootWindow(display) + atom = self.lib.XInternAtom(display, FOCUS_PROPERTY, 0) + if not atom: + return None + actual_type = ctypes.c_ulong(0) + actual_format = ctypes.c_int(0) + items = ctypes.c_ulong(0) + remaining = ctypes.c_ulong(0) + data = ctypes.c_void_p() + status = self.lib.XGetWindowProperty( + display, root, atom, 0, PROPERTY_WORDS, 0, ANY_PROPERTY_TYPE, + ctypes.byref(actual_type), ctypes.byref(actual_format), ctypes.byref(items), + ctypes.byref(remaining), ctypes.byref(data)) + if status != 0 or not data or not items.value: + if data: + self.lib.XFree(data) + return None + try: + raw = _property_bytes(data, actual_format.value, items.value) + finally: + self.lib.XFree(data) + if raw is None: + return None + raw = raw.split(b'\0', 1)[0] + if not raw: + return None + try: + return raw.decode('ascii') + except UnicodeDecodeError: + return None + + def keymap(self, display): + lowest = ctypes.c_int(0) + highest = ctypes.c_int(0) + self.lib.XDisplayKeycodes(display, ctypes.byref(lowest), ctypes.byref(highest)) + if lowest.value < 0 or highest.value < lowest.value: + return None + count = highest.value - lowest.value + 1 + width = ctypes.c_int(0) + symbols = self.lib.XGetKeyboardMapping(display, lowest.value, count, ctypes.byref(width)) + if not symbols: + return None + if width.value <= 0: + self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p)) + return None + rows = [[symbols[index * width.value + level] for level in range(width.value)] + for index in range(count)] + self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p)) + return lowest.value, width.value, rows + + def held_keys(self, display): + state = ctypes.create_string_buffer(32) + if not self.lib.XQueryKeymap(display, ctypes.cast(state, ctypes.c_void_p)): + return set() + raw = state.raw + return {keycode for keycode in range(len(raw) * 8) + if raw[keycode >> 3] >> (keycode & 7) & 1} + + def modifier_keys(self, display): + mapping = self.lib.XGetModifierMapping(display) + if not mapping: + return set() + try: + width = mapping.contents.max_keypermod + keys = mapping.contents.modifiermap + return {keys[index] for index in range(8 * width) if keys[index]} + finally: + self.lib.XFreeModifiermap(mapping) + + def empty_rows(self, display, reserved): + keymap = self.keymap(display) + if keymap is None: + return [] + lowest, width, rows = keymap + held = self.held_keys(display) + modifiers = self.modifier_keys(display) + available = [] + for index in range(len(rows) - 1, -1, -1): + keycode = lowest + index + if keycode < 8 or keycode > 255 or keycode in held or keycode in modifiers: + continue + if keycode in reserved: + continue + row = rows[index] + if any(row): + continue + available.append((keycode, width, tuple(row))) + return available + + def type_text(self, state, text, cancelled=None): + """Reserve all required mappings before injecting any part of a frame.""" + handle = state.handle + needed = [] + seen = set() + for character in text: + keysym = _character_keysym(character) + if keysym not in seen: + seen.add(keysym) + needed.append(keysym) + missing = [keysym for keysym in needed if keysym not in state.codes] + if missing: + available = self.empty_rows(handle, set(state.codes.values())) + if len(available) < len(missing): + _log_capacity_exhausted() + return False + for keysym, (keycode, width, original) in zip(missing, available): + row = (ctypes.c_ulong * width)(*[keysym] * width) + # XChangeKeyboardMapping queues the request and returns 0. + self.lib.XChangeKeyboardMapping(handle, keycode, width, row, 1) + state.codes[keysym] = keycode + state.owned[keycode] = (width, original) + self.lib.XSync(handle, 0) + for character in text: + if _STOP: + return False + if cancelled is not None and cancelled(): + return False + keycode = state.codes[_character_keysym(character)] + if not self._tap(handle, keycode): + return False + return True + + def _tap(self, handle, keycode): + pressed = False + try: + if not self.xtst.XTestFakeKeyEvent(handle, keycode, 1, 0): + return False + pressed = True + self.lib.XSync(handle, 0) + if not self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0): + return False + pressed = False + self.lib.XSync(handle, 0) + finally: + if pressed: + self.xtst.XTestFakeKeyEvent(handle, keycode, 0, 0) + self.lib.XSync(handle, 0) + return True + + +def _character_keysym(character): + keysym = X11_SPECIAL_KEYSYMS.get(character) + if keysym is not None: + return keysym + codepoint = ord(character) + return codepoint if codepoint < 256 else UNICODE_KEYSYM_FLAG | codepoint + + +def _log_capacity_exhausted(): + try: + sys.stderr.write('droiddeck-text-input: not enough empty keycodes for this frame\n') + sys.stderr.flush() + except OSError: + pass + + +def _property_bytes(data, actual_format, items): + if actual_format == 8: + return ctypes.string_at(data, items) + if actual_format == 32: + # Xlib exposes format-32 property items as native longs, including on 64-bit systems. + words = ctypes.cast(data, ctypes.POINTER(ctypes.c_ulong)) + return b''.join(struct.pack(' 0: + try: + chunk = connection.recv(remaining) + except OSError: + return None + if not chunk: + return None + chunks.append(chunk) + remaining -= len(chunk) + return b''.join(chunks) + + +def read_request(connection): + header = _recv_exact(connection, 4) + if header is None: + return None + raw = struct.unpack('>I', header)[0] + cancellable = bool(raw & CANCELLABLE) + length = raw & ~CANCELLABLE + if length < 1 or length > MAX_TEXT: + return None + body = _recv_exact(connection, length) + if body is None: + return None + if b'\0' in body: + return None + try: + return body.decode('utf-8'), cancellable + except UnicodeDecodeError: + return None + + +def answer(connection, accepted): + try: + connection.sendall(b'\x01' if accepted else b'\x00') + connection.shutdown(socket.SHUT_WR) + except OSError: + return + # Drain unread bytes so close() does not reset the connection after the ACK. + try: + connection.settimeout(0.2) + while connection.recv(4096): + pass + except OSError: + pass + + +def _cancellation_probe(connection): + """Return a predicate that is true once the peer has cancelled a flagged frame. + + After the full frame has been read, any readable event (POLLIN/POLLHUP/POLLERR) + means extra data, half-close or reset - all of which are cancellation for a + cancellable client. + """ + poller = select.poll() + poller.register(connection, select.POLLIN) + return lambda: bool(poller.poll(0)) + + +def deliver(bridge, text, cancelled=None): + if cancelled is not None and cancelled(): + return False + target = bridge.target_display() + if target is None: + return False + state = bridge.state(target) + if state is None: + return False + return bridge.type_text(state, text, cancelled) + + +def serve_connection(connection, bridge): + connection.settimeout(CLIENT_TIMEOUT) + request = read_request(connection) + accepted = False + if request is not None: + text, cancellable = request + cancelled = _cancellation_probe(connection) if cancellable else None + try: + accepted = deliver(bridge, text, cancelled) + except Exception: + accepted = False + answer(connection, accepted) + + +def _identity(path): + try: + info = os.stat(path) + except OSError: + return None + return info.st_dev, info.st_ino + + +def _release(path, owned): + if owned is None: + return + try: + info = os.lstat(path) + except OSError: + return + if stat.S_ISSOCK(info.st_mode) and (info.st_dev, info.st_ino) == owned: + try: + os.unlink(path) + except OSError: + pass + + +def serve(path, bridge): + if not _remove_stale(path): + print("droiddeck-text-input: refusing to replace %s" % path, file=sys.stderr) + return 1 + server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + owned = None + try: + server.bind(path) + os.chmod(path, 0o600) + server.listen(8) + server.setblocking(False) + owned = _identity(path) + while not _STOP: + try: + ready, _, _ = select.select([server], [], [], 0.25) + except OSError: + break + if not ready: + continue + try: + connection, _ = server.accept() + except OSError: + if _STOP: + break + continue + try: + serve_connection(connection, bridge) + finally: + connection.close() + finally: + server.close() + _release(path, owned) + return 0 + + +def _remove_stale(path): + try: + info = os.lstat(path) + except FileNotFoundError: + return True + except OSError: + return False + if not stat.S_ISSOCK(info.st_mode): + return False + probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + probe.settimeout(PROBE_TIMEOUT) + probe.connect(path) + except OSError as error: + if error.errno == errno.ENOENT: + return True + if error.errno != errno.ECONNREFUSED: + return False + else: + return False + finally: + probe.close() + _release(path, (info.st_dev, info.st_ino)) + return True + + +def _stop(signum, frame): + global _STOP + _STOP = True + + +def _adopt_parent_death(): + parent = os.getppid() + try: + libc = ctypes.CDLL(None, use_errno=True) + libc.prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, + ctypes.c_ulong] + libc.prctl.restype = ctypes.c_int + libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) + except (OSError, AttributeError): + return True + return os.getppid() == parent and parent > 1 + + +def main(argv): + if len(argv) != 2 or not argv[1]: + return 2 + if not _adopt_parent_death(): + return 0 + os.umask(0o077) + for name in ('SIGTERM', 'SIGINT', 'SIGHUP'): + signal.signal(getattr(signal, name), _stop) + bridge = XBridge() + try: + return serve(argv[1], bridge) + finally: + bridge.close() + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/tools/local-cross.Dockerfile b/tools/local-cross.Dockerfile index badaaf5efe..a517ee87c8 100644 --- a/tools/local-cross.Dockerfile +++ b/tools/local-cross.Dockerfile @@ -3,7 +3,7 @@ FROM ubuntu:24.04 ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update \ - && apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip \ + && apt-get install -y binutils gcc g++ libvulkan-dev python3 zstd unzip rpm2cpio cpio \ && if [ "$(uname -m)" = aarch64 ]; then \ for tool in gcc g++ strip readelf objdump ar; do ln -s "$(command -v $tool)" /usr/local/bin/aarch64-linux-gnu-$tool; done; \ else \ diff --git a/tools/prepare_windows_runtime.py b/tools/prepare_windows_runtime.py index 886deb2a0e..be08f48296 100644 --- a/tools/prepare_windows_runtime.py +++ b/tools/prepare_windows_runtime.py @@ -10,6 +10,7 @@ import argparse import hashlib import io import json +import os from pathlib import Path, PurePosixPath import shutil import struct @@ -49,8 +50,14 @@ LOCAL_ANDROID_SOURCES = {'app/src/main/cpp/CMakeLists.txt', 'app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c', 'app/src/main/cpp/waylandcomp/src/spatialpose.c', 'app/src/main/cpp/waylandcomp/CMakeLists.txt'} -LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat', - 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr'} +LOCAL_SESSION_HELPERS = {'tools/linuxfs/overlay/usr/local/bin/droiddeck-session', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input'} +IME_SOURCES = {'tools/ime/packages.json', 'tools/ime/prepare.py', 'tools/ime/smoke.py'} +IME_MANIFEST = 'usr/local/share/droiddeck/ime-files.json' +IME_PACKAGES = 'build/windows-setup/ime-packages' VR_PREFIX = 'assets/linuxfs/usr/local/lib/droiddeck-vr/' CHECK_PATHS = list(dict.fromkeys(runtime.SOURCE_PATHS + [ 'app/src/main/cpp', 'app/src/main/jniLibs', 'app/src/main/rust/stores', 'tools/vr'])) @@ -82,20 +89,23 @@ def check_sources(): if git('merge-tree', '--write-tree', DONOR_PR_SOURCE, DONOR_MAIN_SOURCE).decode().splitlines()[0] != DONOR_TREE: raise ValueError('The donor CI merge does not match the audited source tree') helper_sources = {path.relative_to(ROOT).as_posix() for path in source_assets()} - reviewed = LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | (LOCAL_SESSION_HELPERS & helper_sources) + reviewed = (LOCAL_BUILD_PLUMBING | LOCAL_ANDROID_SOURCES | IME_SOURCES | + (LOCAL_SESSION_HELPERS & helper_sources)) unexpected = {p for p in changed(AUDITED_SOURCE, 'HEAD') - reviewed if not vr_build.is_source(p)} if unexpected: raise ValueError('Sources changed since the component audit:\n' + '\n'.join(sorted(unexpected))) local = changed('HEAD') untracked = set(filter(None, git('ls-files', '--others', '--exclude-standard', '-z', '--', *CHECK_PATHS).decode().split('\0'))) - unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES) + unexpected = {p for p in (local - reviewed) | (untracked - LOCAL_ANDROID_SOURCES - IME_SOURCES) if not vr_build.is_source(p)} if unexpected: raise ValueError('Unreviewed runtime/native/Rust changes:\n' + '\n'.join(sorted(unexpected))) classifications = {} for path in sorted(changed(DONOR_TREE, 'HEAD') | local | untracked): - if vr_build.is_source(path): + if path in IME_SOURCES: + action = 'regenerated from checksum-pinned RPMs; never reused from donor' + elif vr_build.is_source(path): action = 'VR component rebuilt from current source and verified; never imported from donor' elif path in LOCAL_ANDROID_SOURCES: action = 'Android native source compiled by Gradle; not imported from donor' @@ -161,6 +171,92 @@ def read_gamescope(path): return files, pins +def find_docker(): + docker = shutil.which('docker') + if docker: + return docker + desktop = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Docker/Docker/resources/bin/docker.exe' + if desktop.is_file(): + return str(desktop) + raise ValueError('Docker is required to prepare IME files on Windows; install Docker Desktop or add docker to PATH') + + +def prepare_ime(image): + workspace = ROOT / 'build/windows-setup' + workspace.mkdir(parents=True, exist_ok=True) + packages = ROOT / IME_PACKAGES + packages.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix='droiddeck-ime-', dir=workspace) as folder: + temporary = Path(folder) + linuxfs = temporary / 'linuxfs' + linuxfs.mkdir() + script = ROOT / 'tools/ime/prepare.py' + if sys.platform == 'win32': + docker = find_docker() + inspect_cmd = [docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image] + inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False) + fields = inspected.stdout.strip().split() if inspected.returncode == 0 else [] + image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else '' + if not image_id and image == vr_build.IMAGE: + dockerfile = (ROOT / 'tools/local-cross.Dockerfile').read_bytes().replace(b'\r\n', b'\n') + try: + subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image, + '--file', '-', str(temporary)], input=dockerfile, check=True) + except subprocess.CalledProcessError as error: + raise ValueError('IME preparation failed to build default compiler Docker image ' + image + + '; inspect the Docker build output above, resolve the build error, and rerun preparation') from error + inspected = subprocess.run(inspect_cmd, capture_output=True, text=True, check=False) + fields = inspected.stdout.strip().split() if inspected.returncode == 0 else [] + image_id = fields[0] if len(fields) == 2 and fields[0] and fields[1] == 'linux/amd64' else '' + if not image_id: + detail = inspected.stdout.strip() if inspected.returncode == 0 else inspected.stderr.strip() + detail = detail or 'no image id or platform returned' + raise ValueError('IME preparation requires the existing Docker image ' + image + + ' for linux/amd64; build or load it first (inspect result: ' + detail + ')') + snapshot = temporary / 'src' + (snapshot / 'tools/ime').mkdir(parents=True) + shutil.copy2(script, snapshot / 'tools/ime/prepare.py') + shutil.copy2(ROOT / 'tools/ime/packages.json', snapshot / 'tools/ime/packages.json') + command = [docker, 'run', '--rm', '--platform', 'linux/amd64', + '-v', str(snapshot) + ':/src:ro', + '-v', str(packages) + ':/cache', + '-v', str(linuxfs) + ':/out', + image_id, 'sh', '-c', + 'for tool in rpm2cpio cpio; do command -v "$tool" >/dev/null 2>&1 || { ' + 'echo "missing $tool; rebuild compiler image using tools/local-cross.Dockerfile" >&2; exit 1; }; done; ' + 'exec python3 /src/tools/ime/prepare.py --packages /cache --download --output /out'] + else: + command = [sys.executable, str(script), '--packages', str(packages), '--download', + '--output', str(linuxfs)] + try: + subprocess.run(command, check=True) + except subprocess.CalledProcessError as error: + if sys.platform == 'win32': + raise ValueError('IME preparation failed; ensure Docker is running and image ' + image + + ' is available') from error + raise + manifest_path = linuxfs / IME_MANIFEST + if not manifest_path.is_file(): + raise ValueError('IME preparation did not produce ' + IME_MANIFEST) + manifest = json.loads(manifest_path.read_text(encoding='utf-8')) + if manifest.get('version') != 1 or not isinstance(manifest.get('files'), dict): + raise ValueError('Unexpected IME manifest format') + files = {} + for relative, entry in sorted(manifest['files'].items()): + if not isinstance(entry, dict): + raise ValueError('Unexpected IME manifest entry: ' + str(relative)) + validate_relative(relative) + path = linuxfs / relative + if not path.is_file(): + raise ValueError('IME manifest references a missing file: ' + relative) + data = path.read_bytes() + if hashlib.sha256(data).hexdigest() != entry.get('sha256'): + raise ValueError('IME file checksum mismatch: ' + relative) + files[relative] = data + files[IME_MANIFEST] = manifest_path.read_bytes() + return files, manifest + + def validate_rebuilt(path, machine): data = path.read_bytes() if len(data) < 20 or data[:4] != b'\x7fELF' or data[5] != 1 or struct.unpack('&2 +exit {exit_code} +''' + else: + fixture.write_bytes(payload) + script = f'''#!/bin/sh +exec cat {shlex.quote(str(fixture))} +''' + self._write_executable(tools / 'rpm2cpio', script) + self._write_executable(tools / 'cpio', f'''#!/bin/sh +exec {shlex.quote(str(cpio))} "$@" +''') + return tools + + @contextlib.contextmanager + def _path(self, tools): + with mock.patch.dict(os.environ, + {'PATH': str(tools) + os.pathsep + os.environ.get('PATH', '')}): + yield + + def _cpio_candidates(self): + candidates = [] + for command in ('cpio', 'bsdcpio'): + path = shutil.which(command) + if path: + candidates.append((command, Path(path))) + return candidates + + def test_extract_normal_payload_with_available_cpio(self): + candidates = self._cpio_candidates() + if not candidates: + self.skipTest('no cpio implementation is available') + payload = _newc({'usr/share/demo.txt': b'hello'}) + for command, cpio in candidates: + with self.subTest(cpio=command): + base = self.root / ('normal-' + command) + base.mkdir() + tools = self._tools(base, cpio, payload) + destination = base / 'destination' + with self._path(tools): + PREPARE.extract('demo', base / 'demo.rpm', destination) + self.assertEqual((destination / 'usr/share/demo.txt').read_bytes(), b'hello') + + def test_extract_rejects_unsafe_paths_before_writing(self): + candidates = self._cpio_candidates() + if not candidates: + self.skipTest('no cpio implementation is available') + cpio = candidates[0][1] + for label in ('absolute', 'parent'): + with self.subTest(case=label): + base = self.root / ('unsafe-' + label) + base.mkdir() + outside = base / (label + '-escaped.txt') + name = str(outside) if label == 'absolute' else '../' + outside.name + tools = self._tools(base, cpio, _newc({'payload/safe.txt': b'safe', name: b'bad'})) + destination = base / 'destination' + with self._path(tools), self.assertRaises(ValueError) as caught: + PREPARE.extract('unsafe', base / 'unsafe.rpm', destination) + self.assertIn('unsafe path', str(caught.exception)) + self.assertFalse((destination / 'payload/safe.txt').exists()) + self.assertFalse(outside.exists()) + + def test_extract_propagates_rpm2cpio_failure(self): + candidates = self._cpio_candidates() + if not candidates: + self.skipTest('no cpio implementation is available') + base = self.root / 'failed' + base.mkdir() + tools = self._tools(base, candidates[0][1], exit_code=7) + with self._path(tools), self.assertRaises(subprocess.CalledProcessError) as caught: + PREPARE.extract('broken', base / 'broken.rpm', base / 'destination') + self.assertEqual(caught.exception.returncode, 7) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_output_refresh.py b/tools/tests/test_output_refresh.py index e931c4b187..0cb109c0e4 100644 --- a/tools/tests/test_output_refresh.py +++ b/tools/tests/test_output_refresh.py @@ -128,7 +128,9 @@ int main(void) { while (write(g_input_pipe[1], &wake, sizeof(wake)) == sizeof(wake)) n++; assert(n > 0 && errno == EAGAIN); droiddeck_wayland_set_output_refresh_rate(120000); - drain(); expect(4, 120000, 1); + droiddeck_dispatch_pending_input(); + assert(queued() == 0); + expect(4, 120000, 1); droiddeck_wayland_set_output_refresh_rate(0); drain(); expect(5, 60000, 1); droiddeck_wayland_set_output_refresh_rate(-1); @@ -162,7 +164,8 @@ class OutputRefreshTest(unittest.TestCase): self.skipTest('A host C compiler is required') source = SOURCE.read_text() functions = ('nominal_refresh_ns', 'output_send_mode', 'output_notify_mode', - 'output_resized', 'on_input_readable', 'droiddeck_wayland_output_resized', + 'output_resized', 'dispatch_input', 'on_input_readable', + 'droiddeck_dispatch_pending_input', 'droiddeck_wayland_output_resized', 'droiddeck_wayland_set_scale_mode', 'droiddeck_wayland_set_output_refresh_rate') harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS diff --git a/tools/tests/test_prepare_windows_runtime.py b/tools/tests/test_prepare_windows_runtime.py index 56e8d59306..6ee26692de 100644 --- a/tools/tests/test_prepare_windows_runtime.py +++ b/tools/tests/test_prepare_windows_runtime.py @@ -1,4 +1,6 @@ +import hashlib import importlib.util +import json from pathlib import Path import struct import tempfile @@ -78,6 +80,7 @@ class WindowsRuntimePreparationTest(unittest.TestCase): mock.patch.object(prepare, 'read_gamescope', return_value=({}, { 'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \ mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \ + mock.patch.object(prepare, 'prepare_ime', return_value=({}, {})), \ mock.patch.object(prepare, 'git', return_value=b''), \ mock.patch.object(prepare.runtime, 'record'), mock.patch.object(prepare.runtime, 'verify'), \ mock.patch.object(prepare.vr_build, 'build', return_value=({vr_name: b'new library'}, vr_manifest)) as build: @@ -109,7 +112,14 @@ class WindowsRuntimePreparationTest(unittest.TestCase): archive.assert_not_called() def test_current_helpers_are_allowed_only_when_restaged_from_source(self): - helpers = prepare.LOCAL_SESSION_HELPERS + helpers = { + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-session', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-ime', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-steamvr', + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-text-input', + } + self.assertEqual(prepare.LOCAL_SESSION_HELPERS, helpers) sources = {prepare.ROOT / path: 'assets/linuxfs/' + path.split('/overlay/')[1] for path in helpers} for local_changes in (set(), helpers): @@ -138,7 +148,7 @@ class WindowsRuntimePreparationTest(unittest.TestCase): def test_other_helper_changes_still_need_an_audit(self): with mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \ mock.patch.object(prepare, 'changed', return_value={ - 'tools/linuxfs/overlay/usr/local/bin/droiddeck-session'}): + 'tools/linuxfs/overlay/usr/local/bin/droiddeck-unreviewed'}): with self.assertRaisesRegex(ValueError, 'Sources changed since'): prepare.check_sources() @@ -175,5 +185,337 @@ class WindowsRuntimePreparationTest(unittest.TestCase): prepare.check_sources() + def test_ime_sources_are_regenerated_from_pinned_rpms_in_every_stage(self): + ime = {'tools/ime/prepare.py', 'tools/ime/packages.json', 'tools/ime/smoke.py'} + with mock.patch.object(prepare, 'changed', side_effect=[ime, ime, ime]), \ + mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), b'']): + classifications = prepare.check_sources() + self.assertEqual(set(classifications), ime) + for action in classifications.values(): + self.assertIn('regenerated from checksum-pinned RPMs', action) + self.assertIn('never reused from donor', action) + + def test_unknown_ime_and_native_sources_still_fail_the_audit(self): + for path in ('tools/ime/unreviewed.py', 'app/src/main/cpp/unreviewed.cpp'): + with self.subTest(path=path), \ + mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \ + mock.patch.object(prepare, 'changed', return_value={path}): + with self.assertRaisesRegex(ValueError, 'Sources changed since'): + prepare.check_sources() + with mock.patch.object(prepare, 'changed', side_effect=[set(), set(), set()]), \ + mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), + b'tools/ime/unreviewed.py\0']): + with self.assertRaisesRegex(ValueError, 'Unreviewed runtime'): + prepare.check_sources() + + def test_ime_payload_is_staged_before_record_and_overrides_donor_files(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + apk = root / 'donor.apk' + files = {prepare.IME_MANIFEST: b'generated manifest', + 'usr/local/share/droiddeck/pinyin.so': b'generated ime'} + with ZipFile(apk, 'w') as package: + package.writestr('assets/linuxfs/' + prepare.IME_MANIFEST, b'donor manifest') + package.writestr('assets/linuxfs/usr/local/share/droiddeck/pinyin.so', b'donor ime') + (root / 'app/build').mkdir(parents=True) + (root / 'app/build/runtime-inputs.json').write_text('{}') + staged = {} + + def record(): + for name in files: + staged[name] = (root / 'app/src/main/assets/linuxfs' / name).read_bytes() + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare, 'check_sources', return_value={}), \ + mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \ + mock.patch.object(prepare, 'REBUILT', {}), \ + mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \ + mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \ + mock.patch.object(prepare, 'source_assets', return_value={}), \ + mock.patch.object(prepare, 'read_gamescope', return_value=({}, { + 'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \ + mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \ + mock.patch.object(prepare, 'prepare_ime', + return_value=(files, {'version': 1, 'files': {}})), \ + mock.patch.object(prepare, 'git', return_value=b''), \ + mock.patch.object(prepare.runtime, 'record', side_effect=record), \ + mock.patch.object(prepare.runtime, 'verify'), \ + mock.patch.object(prepare.vr_build, 'build', return_value=({}, {})): + prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip') + self.assertEqual(staged, files) + output = json.loads((root / 'app/build/windows-runtime-provenance.json').read_text()) + self.assertEqual(output['ime_build'], {'version': 1, 'files': {}}) + self.assertIn('regenerated from checksum-pinned RPMs', + output['outputs']['app/src/main/assets/linuxfs/' + prepare.IME_MANIFEST]['origin']) + + def test_second_preparation_accepts_existing_generated_ime_files(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + apk = root / 'donor.apk' + with ZipFile(apk, 'w') as package: + package.writestr('assets/linuxfs/unchanged.so', b'unchanged component') + (root / 'app/build').mkdir(parents=True) + (root / 'app/build/runtime-inputs.json').write_text('{}') + files = {prepare.IME_MANIFEST: b'generated manifest'} + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare, 'check_sources', return_value={}), \ + mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \ + mock.patch.object(prepare, 'REBUILT', {}), \ + mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \ + mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \ + mock.patch.object(prepare, 'source_assets', return_value={}), \ + mock.patch.object(prepare, 'read_gamescope', return_value=({}, { + 'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \ + mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \ + mock.patch.object(prepare, 'prepare_ime', + return_value=(files, {'version': 1, 'files': {}})) as prepare_ime, \ + mock.patch.object(prepare, 'git', return_value=b''), \ + mock.patch.object(prepare.runtime, 'record'), \ + mock.patch.object(prepare.runtime, 'verify'), \ + mock.patch.object(prepare.vr_build, 'build', return_value=({}, {})) as build_vr, \ + mock.patch.object(prepare.vr_build, 'validate', return_value=({}, {})) as validate_vr: + prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip') + prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip', rebuilt_vr=root / 'cached-vr') + build_vr.assert_called_once() + validate_vr.assert_called_once() + self.assertEqual(prepare_ime.call_args_list, [ + mock.call(prepare.vr_build.IMAGE), + mock.call(prepare.vr_build.IMAGE), + ]) + self.assertEqual((root / 'app/src/main/assets/linuxfs' / prepare.IME_MANIFEST).read_bytes(), + b'generated manifest') + + def test_windows_ime_preparation_uses_docker_without_local_extractors(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools/ime').mkdir(parents=True) + (root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8') + (root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8') + manifest = {'version': 1, 'files': { + 'usr/local/share/droiddeck/pinyin.so': { + 'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}} + commands = [] + + def run(command, check=True, capture_output=True, text=True): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return mock.Mock(returncode=0, stdout='sha256:image-id linux/amd64\n', stderr='') + mounted = next(part for part in command if part.endswith(':/out')) + output = Path(mounted.removesuffix(':/out')) + target = output / 'usr/local/share/droiddeck/pinyin.so' + target.parent.mkdir(parents=True) + target.write_bytes(b'ime') + (output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8') + return mock.Mock(returncode=0, stdout='', stderr='') + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker') as locate, \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + files, provenance = prepare.prepare_ime('compiler-image') + inspect_command, command = commands + self.assertEqual(inspect_command, ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', 'compiler-image']) + self.assertEqual(command[0], 'docker') + self.assertIn('--rm', command) + self.assertIn('--platform', command) + self.assertIn('linux/amd64', command) + self.assertIn('sha256:image-id', command) + self.assertNotIn('sha256:image-id linux/amd64', command) + self.assertNotIn('compiler-image', command) + shell = command[-1] + self.assertNotIn('apt-get', shell) + self.assertIn('command -v "$tool"', shell) + self.assertIn('rpm2cpio cpio', shell) + self.assertIn('rebuild compiler image using tools/local-cross.Dockerfile', shell) + self.assertIn('exec python3 /src/tools/ime/prepare.py', shell) + self.assertIn('--packages /cache', shell) + self.assertIn('--download', shell) + self.assertIn('--output /out', shell) + locate.assert_called_once_with('docker') + self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime') + self.assertEqual(json.loads(files[prepare.IME_MANIFEST]), manifest) + self.assertEqual(provenance, manifest) + + def test_windows_ime_preparation_reuses_existing_default_image_without_building(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools/ime').mkdir(parents=True) + (root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8') + (root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8') + manifest = {'version': 1, 'files': { + 'usr/local/share/droiddeck/pinyin.so': { + 'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}} + commands = [] + + def run(command, check=True, capture_output=True, text=True, input=None): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return mock.Mock(returncode=0, stdout='sha256:existing-v5 linux/amd64\n', stderr='') + mounted = next(part for part in command if part.endswith(':/out')) + output = Path(mounted.removesuffix(':/out')) + target = output / 'usr/local/share/droiddeck/pinyin.so' + target.parent.mkdir(parents=True) + target.write_bytes(b'ime') + (output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8') + return mock.Mock(returncode=0, stdout='', stderr='') + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + files, provenance = prepare.prepare_ime(prepare.vr_build.IMAGE) + self.assertEqual(prepare.vr_build.IMAGE, 'droiddeck-local-cross:24.04-v5') + self.assertEqual([cmd[1] for cmd in commands], ['image', 'run']) + self.assertEqual(commands[0], ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', 'droiddeck-local-cross:24.04-v5']) + self.assertIn('sha256:existing-v5', commands[1]) + self.assertNotIn('sha256:existing-v5 linux/amd64', commands[1]) + self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime') + self.assertEqual(provenance, manifest) + + def test_windows_ime_preparation_builds_missing_or_incompatible_default_image_and_runs_by_id(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools/ime').mkdir(parents=True) + (root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8') + (root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8') + (root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\r\nRUN echo ok\r\n') + manifest = {'version': 1, 'files': { + 'usr/local/share/droiddeck/pinyin.so': { + 'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}} + for label, first_inspect in ( + ('missing', mock.Mock(returncode=1, stdout='', stderr='No such image')), + ('linux/arm64', mock.Mock(returncode=0, stdout='sha256:arm64-id linux/arm64\n', stderr='')), + ('windows/amd64', mock.Mock(returncode=0, stdout='sha256:win-id windows/amd64\n', stderr='')), + ): + with self.subTest(case=label): + calls = [] + inspected = 0 + + def run(command, check=True, capture_output=False, text=False, input=None): + nonlocal inspected + calls.append((command, input)) + if command[1:3] == ['image', 'inspect']: + inspected += 1 + if inspected == 1: + return first_inspect + return mock.Mock(returncode=0, stdout='sha256:built-v5-id linux/amd64\n', stderr='') + if command[1] == 'build': + return mock.Mock(returncode=0) + mounted = next(part for part in command if part.endswith(':/out')) + output = Path(mounted.removesuffix(':/out')) + target = output / 'usr/local/share/droiddeck/pinyin.so' + target.parent.mkdir(parents=True) + target.write_bytes(b'ime') + (output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8') + return mock.Mock(returncode=0) + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + files, provenance = prepare.prepare_ime(prepare.vr_build.IMAGE) + self.assertEqual([cmd[1] for cmd, _ in calls], ['image', 'build', 'image', 'run']) + self.assertEqual(calls[0][0], ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', + 'droiddeck-local-cross:24.04-v5']) + build_cmd, build_input = calls[1] + self.assertEqual(build_cmd[:8], ['docker', 'build', '--platform', 'linux/amd64', + '--tag', 'droiddeck-local-cross:24.04-v5', '--file', '-']) + self.assertEqual(build_input, b'FROM ubuntu:24.04\nRUN echo ok\n') + run_cmd = calls[3][0] + self.assertIn('sha256:built-v5-id', run_cmd) + self.assertNotIn('sha256:built-v5-id linux/amd64', run_cmd) + self.assertNotIn('sha256:arm64-id', run_cmd) + self.assertNotIn('sha256:win-id', run_cmd) + self.assertNotIn('droiddeck-local-cross:24.04-v5', run_cmd) + self.assertNotIn('apt-get', run_cmd[-1]) + self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime') + self.assertEqual(provenance, manifest) + + def test_windows_ime_preparation_reports_default_image_build_failure(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools').mkdir(parents=True) + (root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\n') + commands = [] + build_error = prepare.subprocess.CalledProcessError(17, ['docker', 'build']) + + def run(command, check=True, capture_output=False, text=False, input=None): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return mock.Mock(returncode=1, stdout='', stderr='No such image') + if command[1] == 'build': + raise build_error + self.fail('unexpected command: ' + repr(command)) + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + with self.assertRaises(ValueError) as context: + prepare.prepare_ime(prepare.vr_build.IMAGE) + message = str(context.exception) + self.assertIn(prepare.vr_build.IMAGE, message) + self.assertRegex(message, r'(?i)build.*default compiler') + self.assertRegex(message, r'(?i)output.*rerun') + self.assertIs(context.exception.__cause__, build_error) + self.assertEqual(context.exception.__cause__.returncode, 17) + self.assertEqual([cmd[1] for cmd in commands], ['image', 'build']) + + def test_windows_ime_preparation_stops_if_default_image_still_has_no_id_or_wrong_platform_after_build(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + (root / 'tools').mkdir(parents=True) + (root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\n') + for label, result, detail in ( + ('missing', mock.Mock(returncode=1, stdout='', stderr='still missing'), 'still missing'), + ('wrong-arch', mock.Mock(returncode=0, stdout='sha256:arm64-id linux/arm64\n', stderr=''), 'linux/arm64'), + ('malformed', mock.Mock(returncode=0, stdout='sha256:only-id\n', stderr=''), 'sha256:only-id'), + ): + with self.subTest(case=label): + commands = [] + + def run(command, check=True, capture_output=False, text=False, input=None): + commands.append(command) + if command[1:3] == ['image', 'inspect']: + return result + return mock.Mock(returncode=0) + + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', side_effect=run): + with self.assertRaisesRegex(ValueError, 'requires the existing Docker image') as context: + prepare.prepare_ime(prepare.vr_build.IMAGE) + self.assertIn('linux/amd64', str(context.exception)) + self.assertIn(prepare.vr_build.IMAGE, str(context.exception)) + self.assertIn(detail, str(context.exception)) + self.assertEqual([cmd[1] for cmd in commands], ['image', 'build', 'image']) + + def test_windows_ime_preparation_rejects_a_missing_or_incompatible_custom_image_before_running(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + for label, result, detail in ( + ('missing', mock.Mock(returncode=1, stdout='', stderr='No such image'), 'No such image'), + ('linux/arm64', mock.Mock(returncode=0, stdout='sha256:custom-arm linux/arm64\n', stderr=''), 'linux/arm64'), + ('windows/amd64', mock.Mock(returncode=0, stdout='sha256:custom-win windows/amd64\n', stderr=''), 'windows/amd64'), + ): + with self.subTest(case=label): + with mock.patch.object(prepare, 'ROOT', root), \ + mock.patch.object(prepare.sys, 'platform', 'win32'), \ + mock.patch.object(prepare.shutil, 'which', return_value='docker'), \ + mock.patch.object(prepare.subprocess, 'run', return_value=result) as run: + with self.assertRaisesRegex(ValueError, 'requires the existing Docker image') as context: + prepare.prepare_ime('custom-image') + self.assertIn('linux/amd64', str(context.exception)) + self.assertIn('custom-image', str(context.exception)) + self.assertIn(detail, str(context.exception)) + run.assert_called_once() + self.assertEqual(run.call_args.args[0], ['docker', 'image', 'inspect', '--format', + '{{.Id}} {{.Os}}/{{.Architecture}}', 'custom-image']) + + if __name__ == '__main__': unittest.main() diff --git a/tools/tests/test_session_dbus.py b/tools/tests/test_session_dbus.py new file mode 100644 index 0000000000..d602cab9e1 --- /dev/null +++ b/tools/tests/test_session_dbus.py @@ -0,0 +1,199 @@ +"""Real subprocess checks that droiddeck-session starts its bus before the compositor.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +SESSION = ROOT / "tools/linuxfs/overlay/usr/local/bin/droiddeck-session" + +FIXTURE = '''#!/usr/bin/env python3 +import ctypes, json, os, signal, subprocess, sys, time + + +def stat_ppid(pid): + try: + with open(f"/proc/{pid}/stat", "r", encoding="utf-8") as f: + data = f.read() + return int(data.rsplit(") ", 1)[1].split()[1]) + except (FileNotFoundError, IndexError, ProcessLookupError, ValueError): + return None + + +def wait_orphan(pid, timeout=2.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + wpid, status = os.waitpid(pid, os.WNOHANG) + if wpid == pid: + return status + except ChildProcessError: + return None + time.sleep(0.05) + return None + + +libc = ctypes.CDLL(None, use_errno=True) +if libc.prctl(36, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "prctl(PR_SET_CHILD_SUBREAPER) failed") + +harness = sys.argv[1] +fpid = os.getpid() +sib = subprocess.Popen(["sleep", "60"]) +orphan_pid = None +orphan_adopted = False +orphan_reaped = False +orphan_killed = False +out, rc = "", None +try: + helper = ( + "import subprocess; " + "p = subprocess.Popen(['sleep', '60'], start_new_session=True, " + "stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); " + "print(p.pid)" + ) + spawner = subprocess.run([sys.executable, "-c", helper], + capture_output=True, text=True, check=True, timeout=5) + orphan_pid = int(spawner.stdout.strip()) + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if stat_ppid(orphan_pid) == fpid: + orphan_adopted = True + break + time.sleep(0.05) + res = subprocess.run(["bash", harness, "steam"], + env=dict(os.environ, DD_INSIDE="1"), + capture_output=True, text=True, timeout=15) + out, rc = res.stdout, res.returncode + if orphan_adopted: + status = wait_orphan(orphan_pid) + orphan_reaped = status is not None + orphan_killed = ( + orphan_reaped + and os.WIFSIGNALED(status) + and os.WTERMSIG(status) == signal.SIGKILL + ) +except subprocess.TimeoutExpired as exc: + out = exc.stdout or "" + if isinstance(out, bytes): + out = out.decode() + rc = "timeout" +finally: + alive = sib.poll() is None + sib.kill() + try: + sib.wait(timeout=5) + except subprocess.TimeoutExpired: + pass + if orphan_pid is not None and not orphan_reaped: + try: + os.kill(orphan_pid, signal.SIGKILL) + except ProcessLookupError: + pass + wait_orphan(orphan_pid) + +ppid = bus = None +for line in out.splitlines(): + if line.startswith("PPID="): + ppid = int(line[5:]) + elif line.startswith("BUS="): + bus = line[4:] +print(json.dumps({ + "fixture_pid": fpid, + "inner_ppid": ppid, + "inner_bus": bus, + "fixture_bus": os.environ.get("DBUS_SESSION_BUS_ADDRESS", ""), + "sibling_killed": not alive, + "orphan_adopted": orphan_adopted, + "orphan_killed": orphan_killed, + "inner_rc": rc, +})) +''' + +HARNESS = r"""#!/bin/bash +set -u +export HOME=${{HOME:-/root}} +mode=${{1:-desktop}} +shift || true +{guard_before} +if [ -z "${{DD_INSIDE:-}}" ]; then + exec "$DD_FIXTURE" "$0" +fi +{guard_after} +printf 'PPID=%s\n' "$PPID" +printf 'BUS=%s\n' "${{DBUS_SESSION_BUS_ADDRESS:-}}" +{reap} +reap_orphans +""" + +SETUP = 'if [ -z "${DD_INSIDE:-}" ]; then\n /usr/local/bin/droiddeck-fonts' + + +def extract(): + src = SESSION.read_text(encoding="utf-8") + gstart = src.index("# Steam and its helpers share one session bus per session") + guard = src[gstart:src.index("\nfi\n", gstart) + 4] + rstart = src.index("reap_orphans() {") + reap = src[rstart:src.index("\n}\n", rstart) + 3] + return src, guard, reap + + +def build_harness(): + src, guard, reap = extract() + assert src.index("shift || true") < src.index(guard) + if src.index(guard) < src.index(SETUP): + before, after = guard, "" + else: + before, after = "", guard + return HARNESS.format(guard_before=before, guard_after=after, reap=reap) + + +@unittest.skipUnless( + sys.platform.startswith("linux") + and shutil.which("dbus-run-session") + and shutil.which("bash"), + "requires Linux and dbus-run-session and bash on PATH", +) +class SessionDBusTest(unittest.TestCase): + def _run(self, inherited): + with tempfile.TemporaryDirectory() as td: + td = Path(td) + harness = td / "harness.sh" + fixture = td / "fixture.py" + harness.write_text(build_harness(), encoding="utf-8") + harness.chmod(0o755) + fixture.write_text(FIXTURE, encoding="utf-8") + fixture.chmod(0o755) + env = {k: v for k, v in os.environ.items() + if k not in ("DBUS_SESSION_BUS_ADDRESS", "DD_INSIDE")} + env["DD_FIXTURE"] = str(fixture) + cmd = ["bash", str(harness), "steam"] + if inherited: + cmd = ["dbus-run-session", "--"] + cmd + res = subprocess.run(cmd, env=env, cwd=td, capture_output=True, + text=True, timeout=30) + self.assertEqual(res.returncode, 0, res.stderr) + return json.loads(res.stdout.strip().splitlines()[-1]) + + def _check(self, data): + self.assertEqual(data["inner_ppid"], data["fixture_pid"]) + self.assertTrue(data["fixture_bus"]) + self.assertEqual(data["inner_bus"], data["fixture_bus"]) + self.assertTrue(data["sibling_killed"]) + self.assertTrue(data["orphan_adopted"]) + self.assertTrue(data["orphan_killed"]) + self.assertEqual(data["inner_rc"], 0) + + def test_fresh_bus(self): + self._check(self._run(False)) + + def test_inherited_bus(self): + self._check(self._run(True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_steam_ime_runtime.py b/tools/tests/test_steam_ime_runtime.py new file mode 100644 index 0000000000..44c2e90aed --- /dev/null +++ b/tools/tests/test_steam_ime_runtime.py @@ -0,0 +1,65 @@ +"""Steam pinyin runtime requirements, without network access or a running Steam client.""" +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +TOOLS = Path(__file__).resolve().parents[1] +SESSION = TOOLS / 'linuxfs/overlay/usr/local/bin/droiddeck-session' +WRAPPER = '/usr/local/bin/droiddeck-steam-ime' +ENGINE = '/usr/local/lib/droiddeck-ime/ibus-engine-pinyin' +DAEMON = '/usr/bin/ibus-daemon' +CLIENT = '/usr/bin/ibus' + + +class SteamImeRuntimeTest(unittest.TestCase): + @unittest.skipUnless(shutil.which('bash') and shutil.which('timeout'), 'needs bash and timeout') + def test_steam_start_only_exports_address_after_success(self): + source = SESSION.read_text() + start = source.index(' unset IBUS_ADDRESS\n ime_ibus_pid=') + fragment = source[start:source.index(' while :; do', start)] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + commands = { + WRAPPER: ('wrapper', '#!/bin/bash\nprintf launched > "$XDG_RUNTIME_DIR/wrapper-started"\nexec sleep 5\n'), + ENGINE: ('engine', '#!/bin/bash\nexit 0\n'), + DAEMON: ('daemon', '#!/bin/bash\nexit 0\n'), + CLIENT: ('client', '#!/bin/bash\ntest -f "$XDG_RUNTIME_DIR/wrapper-started" || exit 1\nprintf "pinyin\\n"\n'), + } + for path, (basename, script) in commands.items(): + f = root / basename + if path != DAEMON: + f.write_text(script) + f.chmod(0o755) + fragment = fragment.replace(f'{path} ', f'"{f}" ').replace(f'{path} ]', f'"{f}" ]') + env = dict(os.environ, XDG_RUNTIME_DIR=directory, IBUS_ADDRESS='unrelated-address') + cleanup = '\nprintf "address=%s\\n" "${IBUS_ADDRESS-unset}"\n' + cleanup += 'printf "pid=%s\\n" "${ime_ibus_pid:-none}"; stop_steam_ime\n' + process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + fragment + cleanup], + text=True, capture_output=True, check=True, env=env, timeout=10) + self.assertIn('does not include IBus', process.stdout) + self.assertIn('address=unset', process.stdout) + self.assertFalse((root / 'wrapper-started').exists()) + (root / 'daemon').write_text(commands[DAEMON][1]) + (root / 'daemon').chmod(0o755) + (root / 'client').write_text('#!/bin/bash\nexit 1\n') + refused = fragment.replace('SECONDS + 5', 'SECONDS + 1') + process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + refused + cleanup], + text=True, capture_output=True, check=True, env=env, timeout=10) + self.assertIn('the pinyin engine did not start', process.stdout) + self.assertIn('address=unset', process.stdout) + self.assertIn('pid=none', process.stdout) + (root / 'wrapper-started').unlink() + (root / 'client').write_text(commands[CLIENT][1]) + process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + fragment + cleanup], + text=True, capture_output=True, check=True, env=env, timeout=10) + self.assertIn('pinyin engine ready', process.stdout) + self.assertIn('address=unix:path=', process.stdout) + self.assertEqual((root / 'wrapper-started').read_text(), 'launched') + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_text_input.py b/tools/tests/test_text_input.py new file mode 100644 index 0000000000..352bd35ad8 --- /dev/null +++ b/tools/tests/test_text_input.py @@ -0,0 +1,907 @@ +"""Exercise the text bridge through a real X11 client and Xutf8LookupString.""" +import ctypes +import ctypes.util +import locale +import os +import runpy +import select +import shutil +import signal +import socket +import stat +import struct +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from pathlib import Path +from types import SimpleNamespace + +HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-text-input" +XVFB = shutil.which("Xvfb") +FOCUS_PROPERTY = b"GAMESCOPE_KEYBOARD_FOCUS_DISPLAY" +SAMPLE = "中文ABC123,。é😀" +MAX_TEXT = 65536 +ACK_OK = b"\x01" +ACK_FAILED = b"\x00" + +KEY_PRESS_MASK = 1 << 0 +KEY_RELEASE_MASK = 1 << 1 +STRUCTURE_NOTIFY_MASK = 1 << 17 +KEY_PRESS = 2 +KEY_RELEASE = 3 +MAP_NOTIFY = 19 +MAPPING_NOTIFY = 34 +REVERT_TO_PARENT = 2 +PROPERTY_REPLACE = 0 +INPUT_STYLE = 0x0408 # XIMPreeditNothing | XIMStatusNothing +LC_ALL = 6 # glibc +CODESET = 14 # glibc +KEYSYM_BACKSPACE = 0xff08 +KEYSYM_RETURN = 0xff0d + +_X11 = None + + +class XKeyEvent(ctypes.Structure): + _fields_ = [ + ("type", ctypes.c_int), + ("serial", ctypes.c_ulong), + ("send_event", ctypes.c_int), + ("display", ctypes.c_void_p), + ("window", ctypes.c_ulong), + ("root", ctypes.c_ulong), + ("subwindow", ctypes.c_ulong), + ("time", ctypes.c_ulong), + ("x", ctypes.c_int), + ("y", ctypes.c_int), + ("x_root", ctypes.c_int), + ("y_root", ctypes.c_int), + ("state", ctypes.c_uint), + ("keycode", ctypes.c_uint), + ("same_screen", ctypes.c_int), + ] + + +class XModifierKeymap(ctypes.Structure): + _fields_ = [ + ("max_keypermod", ctypes.c_int), + ("modifiermap", ctypes.POINTER(ctypes.c_ubyte)), + ] + + +def _load_x11(): + lib = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6") + lib.XInitThreads.restype = ctypes.c_int + lib.XInitThreads() # the consumer reads events in its own thread + lib.XOpenDisplay.argtypes = [ctypes.c_char_p] + lib.XOpenDisplay.restype = ctypes.c_void_p + lib.XCloseDisplay.argtypes = [ctypes.c_void_p] + lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + lib.XDefaultRootWindow.restype = ctypes.c_ulong + lib.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, + ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong, + ctypes.c_ulong] + lib.XCreateSimpleWindow.restype = ctypes.c_ulong + lib.XDestroyWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + lib.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long] + lib.XMapWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + lib.XSetInputFocus.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong] + lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] + lib.XPending.argtypes = [ctypes.c_void_p] + lib.XPending.restype = ctypes.c_int + lib.XNextEvent.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + lib.XConnectionNumber.argtypes = [ctypes.c_void_p] + lib.XConnectionNumber.restype = ctypes.c_int + lib.XSetLocaleModifiers.argtypes = [ctypes.c_char_p] + lib.XOpenIM.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] + lib.XOpenIM.restype = ctypes.c_void_p + lib.XCreateIC.restype = ctypes.c_void_p + lib.XDestroyIC.argtypes = [ctypes.c_void_p] + lib.XCloseIM.argtypes = [ctypes.c_void_p] + lib.Xutf8LookupString.argtypes = [ctypes.c_void_p, ctypes.POINTER(XKeyEvent), + ctypes.POINTER(ctypes.c_char), ctypes.c_int, + ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.c_int)] + lib.Xutf8LookupString.restype = ctypes.c_int + lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), + ctypes.POINTER(ctypes.c_int)] + lib.XRefreshKeyboardMapping.argtypes = [ctypes.c_void_p] + lib.XGetKeyboardMapping.argtypes = [ctypes.c_void_p, ctypes.c_ubyte, ctypes.c_int, + ctypes.POINTER(ctypes.c_int)] + lib.XGetKeyboardMapping.restype = ctypes.POINTER(ctypes.c_ulong) + lib.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + lib.XFree.argtypes = [ctypes.c_void_p] + lib.XGetModifierMapping.argtypes = [ctypes.c_void_p] + lib.XGetModifierMapping.restype = ctypes.POINTER(XModifierKeymap) + lib.XFreeModifiermap.argtypes = [ctypes.POINTER(XModifierKeymap)] + lib.XFreeModifiermap.restype = ctypes.c_int + lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int] + lib.XInternAtom.restype = ctypes.c_ulong + lib.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, + ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int] + return lib + + +def libx11(): + global _X11 + if _X11 is None: + _X11 = _load_x11() + return _X11 + + +class XTextConsumer: + """An ordinary X11 client: it owns a focused window and keeps reading the key events the + bridge injects, converting each one through its own input context.""" + + def __init__(self, lib, display): + self.lib = lib + self.lock = threading.Lock() + self._text = b"" + self._presses = [] + self._releases = [] + self._keysyms = [] + self._stopped = threading.Event() + self._thread = None + self._im = None + self._ic = None + self._dpy = lib.XOpenDisplay(display.encode()) + if not self._dpy: + raise RuntimeError("the test client cannot open X display " + display) + try: + self._window = lib.XCreateSimpleWindow(self._dpy, lib.XDefaultRootWindow(self._dpy), + 0, 0, 200, 100, 0, 0, 0) + lib.XSelectInput(self._dpy, self._window, + KEY_PRESS_MASK | KEY_RELEASE_MASK | STRUCTURE_NOTIFY_MASK) + lib.XMapWindow(self._dpy, self._window) + self._wait_for_map(display) + lib.XSetInputFocus(self._dpy, self._window, REVERT_TO_PARENT, 0) + lib.XSync(self._dpy, False) + self.snapshot = self.keymap() + self._open_input_context() + except Exception: + self.close() + raise + + def _wait_for_map(self, display): + event = ctypes.create_string_buffer(192) + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if self.lib.XPending(self._dpy): + self.lib.XNextEvent(self._dpy, ctypes.cast(event, ctypes.c_void_p)) + if ctypes.cast(event, ctypes.POINTER(XKeyEvent)).contents.type == MAP_NOTIFY: + return + else: + select.select([self.lib.XConnectionNumber(self._dpy)], [], [], 0.05) + raise RuntimeError("the test client window never became viewable on " + display) + + def _open_input_context(self): + locale.setlocale(locale.LC_CTYPE, "C.UTF-8") + self.lib.XSetLocaleModifiers(b"@im=none") + self._im = self.lib.XOpenIM(self._dpy, None, None, None) + if not self._im: + raise RuntimeError("Xlib has no input method here, so Xutf8LookupString cannot run") + self._ic = self.lib.XCreateIC(ctypes.c_void_p(self._im), + ctypes.c_char_p(b"inputStyle"), ctypes.c_ulong(INPUT_STYLE), + ctypes.c_char_p(b"clientWindow"), ctypes.c_ulong(self._window), + ctypes.c_char_p(b"focusWindow"), ctypes.c_ulong(self._window), + ctypes.c_void_p(0)) + if not self._ic: + raise RuntimeError("Xlib refused an input context for Xutf8LookupString") + self.lib.XSync(self._dpy, False) + + def start(self): + self._thread = threading.Thread(target=self._pump, daemon=True) + self._thread.start() + + def _pump(self): + event = ctypes.create_string_buffer(192) + raw = ctypes.cast(event, ctypes.c_void_p) + fd = self.lib.XConnectionNumber(self._dpy) + while not self._stopped.is_set(): + try: + pending = self.lib.XPending(self._dpy) + except (OSError, ValueError): + return + if not pending: + try: + readable, _, _ = select.select([fd], [], [], 0.05) + except (OSError, ValueError): + return + if not readable: + continue + while self.lib.XPending(self._dpy): + self.lib.XNextEvent(self._dpy, raw) + if ctypes.cast(event, ctypes.POINTER(ctypes.c_int)).contents.value == MAPPING_NOTIFY: + self.lib.XRefreshKeyboardMapping(raw) + continue + key = ctypes.cast(event, ctypes.POINTER(XKeyEvent)) + if key.contents.type == KEY_PRESS: + self._press(key) + elif key.contents.type == KEY_RELEASE: + with self.lock: + self._releases.append(key.contents.keycode) + + def _press(self, key): + buffer = ctypes.create_string_buffer(64) + keysym = ctypes.c_ulong(0) + status = ctypes.c_int(0) + count = self.lib.Xutf8LookupString(ctypes.c_void_p(self._ic), key, buffer, len(buffer), + ctypes.byref(keysym), ctypes.byref(status)) + with self.lock: + self._presses.append(key.contents.keycode) + self._keysyms.append(keysym.value) + if count > 0: + self._text += buffer.raw[:count] + + def wait_for(self, count, timeout=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + with self.lock: + if len(self._presses) >= count and len(self._releases) >= count: + return True + time.sleep(0.01) + with self.lock: + return len(self._presses) >= count and len(self._releases) >= count + + def counts(self): + with self.lock: + return len(self._presses), len(self._releases) + + def press_count(self): + with self.lock: + return len(self._presses) + + def press_keycodes(self): + with self.lock: + return sorted(self._presses) + + def release_keycodes(self): + with self.lock: + return sorted(self._releases) + + def keysyms(self): + with self.lock: + return list(self._keysyms) + + def text(self): + with self.lock: + raw = self._text + try: + return raw.decode("utf-8") + except UnicodeDecodeError as error: + raise AssertionError("the X11 client derived %r, which is not UTF-8: %s" % (raw, error)) + + def keymap(self): + first = ctypes.c_int(0) + maximum = ctypes.c_int(0) + self.lib.XDisplayKeycodes(self._dpy, ctypes.byref(first), ctypes.byref(maximum)) + count = maximum.value - first.value + 1 + per = ctypes.c_int(0) + symbols = self.lib.XGetKeyboardMapping(self._dpy, first.value, count, ctypes.byref(per)) + if not symbols: + raise RuntimeError("XGetKeyboardMapping returned nothing") + values = [symbols[index] for index in range(count * per.value)] + self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p)) + return (first.value, per.value, values) + + def modifier_codes(self): + """Keycodes the server treats as modifiers; they are never replaceable.""" + mapping = self.lib.XGetModifierMapping(self._dpy) + if not mapping: + return set() + try: + width = mapping.contents.max_keypermod + keys = mapping.contents.modifiermap + return {keys[index] for index in range(8 * width) if keys[index]} + finally: + self.lib.XFreeModifiermap(mapping) + + def pressed_keys(self): + keys = ctypes.create_string_buffer(32) + self.lib.XQueryKeymap(self._dpy, ctypes.cast(keys, ctypes.c_void_p)) + return [index * 8 + bit for index in range(32) for bit in range(8) + if keys.raw[index] >> bit & 1] + + def close(self): + self._stopped.set() + if self._thread is not None: + self._thread.join(5) + self._thread = None + if self._ic: + self.lib.XDestroyIC(ctypes.c_void_p(self._ic)) + self._ic = None + if self._im: + self.lib.XCloseIM(ctypes.c_void_p(self._im)) + self._im = None + if self._dpy: + if getattr(self, "_window", None): + self.lib.XDestroyWindow(self._dpy, self._window) + self.lib.XCloseDisplay(self._dpy) + self._dpy = None + + +class XRoot: + """Publishes the session properties the bridge reads from the main display's root window.""" + + def __init__(self, lib, display): + self.lib = lib + self._dpy = lib.XOpenDisplay(display.encode()) + if not self._dpy: + raise RuntimeError("the test client cannot open X display " + display) + self.root = lib.XDefaultRootWindow(self._dpy) + + def set_string(self, name, value): + data = ctypes.create_string_buffer(value, len(value)) + self.lib.XChangeProperty(self._dpy, self.root, self._atom(name), self._atom(b"STRING"), + 8, PROPERTY_REPLACE, ctypes.cast(data, ctypes.c_void_p), len(value)) + self.lib.XSync(self._dpy, False) + + def set_packed_cardinals(self, name, value): + # gamescope 3.16.29 stores the display string's bytes packed into CARDINALs, little endian. + padded = value + b"\0" * (-len(value) % 4) + words = [int.from_bytes(padded[start:start + 4], "little") for start in range(0, len(padded), 4)] + data = (ctypes.c_ulong * len(words))(*words) + self.lib.XChangeProperty(self._dpy, self.root, self._atom(name), self._atom(b"CARDINAL"), + 32, PROPERTY_REPLACE, ctypes.cast(data, ctypes.c_void_p), len(words)) + self.lib.XSync(self._dpy, False) + + def _atom(self, name): + return self.lib.XInternAtom(self._dpy, name, 0) + + def close(self): + if self._dpy: + self.lib.XCloseDisplay(self._dpy) + self._dpy = None + + +LAUNCHER = ( + "import subprocess, sys, time\n" + "child = subprocess.Popen([sys.executable, sys.argv[1], sys.argv[2]])\n" + "open(sys.argv[3], 'w').write(str(child.pid))\n" + "time.sleep(120)\n" +) + + +@unittest.skipUnless(XVFB, "Xvfb is not installed") +class TextInputTest(unittest.TestCase): + maxDiff = 8000 + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + self.log = self.dir / "helper.log" + try: + self.lib = libx11() + except OSError as error: + self.fail("libX11 is missing, so no X11 client can check the bridge: %s" % error) + + def start_display(self): + for number in range(90, 140): + path = Path("/tmp/.X11-unix/X%d" % number) + if path.exists(): + continue + process = subprocess.Popen( + [XVFB, ":%d" % number, "-screen", "0", "320x240x24", "-nolisten", "tcp"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(self.stop_display, process) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if path.exists(): + return ":%d" % number + if process.poll() is not None: + break + time.sleep(0.02) + self.fail("no Xvfb display could be started") + + @staticmethod + def stop_display(process): + if process.poll() is not None: + return + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + def consume(self, display): + try: + consumer = XTextConsumer(self.lib, display) + except RuntimeError as error: + self.fail(str(error)) + self.addCleanup(consumer.close) + consumer.start() + return consumer + + def start_helper(self, socket_path, display, game_display=None): + self.assertTrue(HELPER.is_file(), + "the text bridge %s does not exist; the helper never started" % HELPER) + env = dict(os.environ) + env["DISPLAY"] = display + env.pop("STEAM_GAME_DISPLAY_0", None) + if game_display is not None: + env["STEAM_GAME_DISPLAY_0"] = game_display + stream = open(self.log, "wb") + self.addCleanup(stream.close) + process = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], env=env, + stdin=subprocess.DEVNULL, stdout=stream, stderr=subprocess.STDOUT) + self.addCleanup(self.stop_helper, process) + self.wait_for_socket(process, socket_path) + return process + + @staticmethod + def stop_helper(process): + if process.poll() is not None: + return + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + def wait_for_socket(self, process, socket_path, timeout=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if process.poll() is not None: + self.fail("the text bridge exited with %s before serving %s; output: %r" + % (process.returncode, socket_path.name, self.output())) + if self.listening(socket_path): + return + time.sleep(0.02) + self.fail("the text bridge never listened on %s; output: %r" + % (socket_path.name, self.output())) + + @staticmethod + def listening(socket_path): + try: + info = socket_path.lstat() + except OSError: + return False + if not stat.S_ISSOCK(info.st_mode): + return False + probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + probe.settimeout(0.5) + probe.connect(str(socket_path)) + except OSError: + return False + finally: + probe.close() + return True + + def output(self): + try: + return self.log.read_text(errors="replace")[-2000:] + except OSError: + return "" + + def output_bytes(self): + try: + return self.log.read_bytes() + except OSError: + return b"" + + def frame(self, socket_path, payload, timeout=15, shutdown=False): + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.addCleanup(client.close) + client.settimeout(timeout) + client.connect(str(socket_path)) + client.sendall(payload) + if shutdown: + client.shutdown(socket.SHUT_WR) + ack = b"" + while len(ack) < 1: + try: + chunk = client.recv(1) + except socket.timeout: + self.fail("the bridge did not answer within %s seconds" % timeout) + if not chunk: + break + ack += chunk + try: + tail = client.recv(1) + except socket.timeout: + self.fail("the bridge kept the connection open after answering %r" % ack) + self.assertEqual(b"", tail, "the bridge sent more than its one answer") + return ack + + def commit(self, socket_path, text, timeout=15): + payload = text if isinstance(text, bytes) else text.encode() + return self.frame(socket_path, struct.pack(">I", len(payload)) + payload, timeout) + + def test_exact_unicode_reaches_a_real_x11_client(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE), "the bridge did not accept the text") + self.assertTrue(consumer.wait_for(len(SAMPLE)), + "the X11 client saw %d presses and %d releases of the %d key pairs the text needs" + % (consumer.counts() + (len(SAMPLE),))) + self.assertEqual(SAMPLE, consumer.text()) + self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(), + "a key was pressed without its release") + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + self.assertNotIn(SAMPLE.encode(), self.output_bytes(), "the bridge logged the text it typed") + + def test_adjacent_commits_reach_the_client_in_order(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + for text in ("中文", " ", "abc"): + self.assertEqual(ACK_OK, self.commit(socket_path, text), + "the bridge did not accept %r" % text) + expected = "中文 abc" + self.assertTrue(consumer.wait_for(len(expected)), + "the X11 client saw %d presses and %d releases of the %d key pairs the text needs" + % (consumer.counts() + (len(expected),))) + self.assertEqual(expected, consumer.text()) + self.stop_helper(process) + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + + def test_chinese_then_backspace_then_return_are_real_keysyms(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + for text in ("中文", "\b", "\r"): + self.assertEqual(ACK_OK, self.commit(socket_path, text), + "the bridge did not accept %r" % text) + self.assertTrue(consumer.wait_for(4), + "the X11 client saw %d presses and %d releases of the 4 key pairs the text needs" + % consumer.counts()) + self.assertEqual([0x01000000|ord("中"),0x01000000|ord("文"),KEYSYM_BACKSPACE,KEYSYM_RETURN], + consumer.keysyms(), + "the soft controls must reach the client as real keysyms after the text") + self.assertEqual("中文\b\r", consumer.text(), + "Xutf8LookupString is a raw lookup, not an editor; the controls stay literal") + self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(), + "a key was pressed without its release") + self.stop_helper(process) + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + + def test_malformed_frames_are_refused_and_the_next_text_still_works(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + frames = { + "invalid utf8": (struct.pack(">I", 2) + b"\xff\xfe", False), + "surrogate": (struct.pack(">I", 3) + b"\xed\xa0\x80", False), + "nul": (struct.pack(">I", 3) + b"a\x00b", False), + "empty text": (struct.pack(">I", 0), False), + "over the size limit": (struct.pack(">I", MAX_TEXT + 1), False), + "little endian length": (struct.pack("I", 10) + b"abc", True), + } + for name, (payload, shutdown) in frames.items(): + with self.subTest(name): + self.assertEqual(ACK_FAILED, self.frame(socket_path, payload, shutdown=shutdown), + "%s must be refused with ACK 0" % name) + time.sleep(0.3) + self.assertEqual(0, consumer.press_count(), "a refused request still injected keys") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "a refused request changed the keyboard map") + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE)) + self.assertTrue(consumer.wait_for(len(SAMPLE)), + "the bridge stopped serving after refusing a request") + self.assertEqual(SAMPLE, consumer.text()) + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys()) + self.assertEqual(consumer.snapshot, consumer.keymap()) + + def test_stable_mappings_survive_a_delayed_consumer(self): + display = self.start_display() + try: + consumer = XTextConsumer(self.lib, display) + except RuntimeError as error: + self.fail(str(error)) + self.addCleanup(consumer.close) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + later = "更多" + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE), + "the bridge did not accept the first frame") + self.assertEqual(ACK_OK, self.commit(socket_path, later), + "the bridge did not accept the second frame") + # Delay event lookup until both commits have been acknowledged. + consumer.start() + expected = SAMPLE + later + self.assertTrue(consumer.wait_for(len(expected)), + "the X11 client saw %d presses and %d releases of the %d key pairs the text needs" + % (consumer.counts() + (len(expected),))) + self.assertEqual(expected, consumer.text(), + "a delayed consumer must read every character exactly once, in order") + self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(), + "a key was pressed without its release") + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "the bridge did not restore the keyboard map") + + def test_a_frame_larger_than_the_empty_keymap_is_refused(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + lowest, width, values = consumer.snapshot + modifiers = consumer.modifier_codes() + empty = 0 + for index in range(len(values) // width): + keycode = lowest + index + if keycode < 8 or keycode > 255 or keycode in modifiers: + continue + if not any(values[index * width:(index + 1) * width]): + empty += 1 + self.assertLessEqual(empty, 248, + "the keycodes 8..255 alone cap every session at 248 slots") + flood = "".join(chr(0x4E00 + offset) for offset in range(empty + 1)) + self.assertEqual(ACK_FAILED, self.commit(socket_path, flood), + "a frame needing more distinct keysyms than empty rows must be refused") + time.sleep(0.5) + self.assertEqual(0, consumer.press_count(), "a refused frame still injected keys") + self.assertEqual(consumer.snapshot, consumer.keymap(), + "a refused frame changed the keyboard map") + self.assertEqual(ACK_OK, self.commit(socket_path, "中文"), + "the refusal consumed the slots it merely measured") + self.assertTrue(consumer.wait_for(2), "the next short text was never typed") + self.assertEqual("中文", consumer.text()) + self.stop_helper(process) + self.assertEqual([], consumer.pressed_keys()) + self.assertEqual(consumer.snapshot, consumer.keymap()) + + def assert_routing(self, publish): + main = self.start_display() + game = self.start_display() + main_consumer = self.consume(main) + game_consumer = self.consume(game) + root = XRoot(self.lib, main) + self.addCleanup(root.close) + publish(root, game.encode()) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, main, game_display=game) + self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE)) + self.assertTrue(game_consumer.wait_for(len(SAMPLE)), + "the display named by %s received no text" % FOCUS_PROPERTY.decode()) + self.assertEqual(SAMPLE, game_consumer.text()) + time.sleep(0.3) + self.assertEqual(0, main_consumer.press_count(), "the text went to both displays") + + def test_two_displays_route_to_the_format8_property(self): + self.assert_routing(lambda root, display: root.set_string(FOCUS_PROPERTY, display)) + + def test_two_displays_route_to_the_gamescope_format32_property(self): + self.assert_routing(lambda root, display: root.set_packed_cardinals(FOCUS_PROPERTY, display)) + + def test_ambiguous_routing_injects_nothing(self): + main = self.start_display() + game = self.start_display() + main_consumer = self.consume(main) + game_consumer = self.consume(game) + root = XRoot(self.lib, main) + self.addCleanup(root.close) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, main, game_display=game) + self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE), + "a missing focus property must not be guessed") + root.set_string(FOCUS_PROPERTY, b":177") + self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE), + "an unknown display must not be used") + root.set_string(FOCUS_PROPERTY, b"\xff\xfe") + self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE), + "unparseable property bytes must not be used") + time.sleep(0.3) + self.assertEqual((0, 0), (main_consumer.press_count(), game_consumer.press_count()), + "a refused route still injected keys") + + def test_sigterm_exits_and_removes_only_its_own_socket(self): + display = self.start_display() + socket_path = self.dir / "text-input.sock" + process = self.start_helper(socket_path, display) + foreign = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.addCleanup(foreign.close) + foreign_path = self.dir / "someone-else.sock" + foreign.bind(str(foreign_path)) + process.send_signal(signal.SIGTERM) + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + self.fail("the text bridge ignored SIGTERM") + self.assertFalse(socket_path.exists(), "the bridge left its own socket behind") + self.assertTrue(foreign_path.exists(), "the bridge removed a socket it does not own") + + def test_exits_when_the_session_that_started_it_dies(self): + display = self.start_display() + socket_path = self.dir / "text-input.sock" + self.assertTrue(HELPER.is_file(), + "the text bridge %s does not exist; the helper never started" % HELPER) + pid_file = self.dir / "bridge.pid" + launcher = subprocess.Popen([sys.executable, "-c", LAUNCHER, str(HELPER), str(socket_path), + str(pid_file)], + env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(self.stop_helper, launcher) + pid = 0 + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + text = pid_file.read_text() if pid_file.exists() else "" + if text.strip().isdigit(): + pid = int(text) + break + time.sleep(0.02) + self.assertTrue(pid, "the launching session never reported the bridge pid") + self.addCleanup(self.kill_pid, pid) + self.wait_for_socket(launcher, socket_path) + launcher.kill() + launcher.wait(timeout=10) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline and self.pid_alive(pid): + time.sleep(0.05) + self.assertFalse(self.pid_alive(pid), "the bridge outlived the session that started it") + self.assertFalse(socket_path.exists(), "the bridge left its socket behind") + + def test_a_shutdown_client_during_a_blocked_tap_gets_no_ack(self): + helper = runpy.run_path(str(HELPER)) + bridge_type = helper["XBridge"] + begun = threading.Event() + release = threading.Event() + taps = [] + + class FakeBridge: + type_text = bridge_type.type_text + + def target_display(self): + return ":fake" + + def state(self, name): + return SimpleNamespace(handle=None, codes={ord("a"): 1, ord("b"): 2}) + + def _tap(self, handle, keycode): + taps.append(keycode) + if len(taps) == 1: + begun.set() + release.wait(10) + return True + + server, client = socket.socketpair() + self.addCleanup(server.close) + self.addCleanup(client.close) + worker = threading.Thread(target=helper["serve_connection"], + args=(server, FakeBridge()), daemon=True) + worker.start() + try: + client.sendall(struct.pack(">I", (1 << 31) | 2) + b"ab") + self.assertTrue(begun.wait(10), "the bridge never began the first tap") + client.shutdown(socket.SHUT_WR) + readable, _, _ = select.select([client], [], [], 0.05) + self.assertEqual([], readable, "the bridge answered a client that went away mid-tap") + finally: + release.set() + client.settimeout(10) + self.assertEqual(ACK_FAILED, client.recv(1), + "a client that stopped reading must be told the tap failed") + worker.join(10) + self.assertFalse(worker.is_alive(), "the connection thread did not finish") + self.assertEqual([1], taps, "the bridge kept tapping after the client went away") + + def test_a_stalled_client_does_not_block_the_service(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, display) + stalled = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.addCleanup(stalled.close) + stalled.settimeout(5) + stalled.connect(str(socket_path)) + stalled.sendall(struct.pack(">I", 40)) + started = time.monotonic() + self.assertEqual(ACK_OK, self.commit(socket_path, "中文", timeout=20)) + self.assertLess(time.monotonic() - started, 20) + self.assertTrue(consumer.wait_for(2), "the later request was never typed") + self.assertEqual("中文", consumer.text()) + + def test_sigkill_restart_on_the_same_path_serves_again(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + first = self.start_helper(socket_path, display) + first.send_signal(signal.SIGKILL) + first.wait(timeout=10) + self.start_helper(socket_path, display) + self.assertEqual(ACK_OK, self.commit(socket_path, "重启", timeout=20)) + self.assertTrue(consumer.wait_for(2), "text after a SIGKILL restart was never typed") + self.assertEqual("重启", consumer.text()) + + def test_a_second_helper_leaves_the_live_listener_alone(self): + display = self.start_display() + consumer = self.consume(display) + socket_path = self.dir / "text-input.sock" + self.start_helper(socket_path, display) + before = socket_path.lstat() + stream = open(self.log, "ab") + self.addCleanup(stream.close) + second = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], + env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL, + stdout=stream, stderr=subprocess.STDOUT) + self.addCleanup(self.stop_helper, second) + try: + code = second.wait(timeout=15) + except subprocess.TimeoutExpired: + self.fail("a second text bridge kept running next to the live one") + self.assertNotEqual(0, code, "a second text bridge accepted an occupied path") + after = socket_path.lstat() + self.assertEqual((before.st_dev, before.st_ino), (after.st_dev, after.st_ino), + "a second text bridge replaced the live socket") + self.assertEqual(ACK_OK, self.commit(socket_path, "还在", timeout=20)) + self.assertTrue(consumer.wait_for(2), "the live listener stopped typing after a second launch") + self.assertEqual("还在", consumer.text()) + + def test_a_regular_file_at_the_socket_path_is_preserved(self): + display = self.start_display() + socket_path = self.dir / "occupied.sock" + socket_path.write_text("not a socket") + code = self.launch_expecting_failure(socket_path, display) + self.assertNotEqual(0, code, "the text bridge accepted a regular file as its socket") + self.assertEqual("not a socket", socket_path.read_text(), + "the text bridge overwrote a regular file") + + def test_a_symlink_at_the_socket_path_is_preserved(self): + display = self.start_display() + target = self.dir / "target" + target.write_text("keep") + socket_path = self.dir / "link.sock" + socket_path.symlink_to(target) + code = self.launch_expecting_failure(socket_path, display) + self.assertNotEqual(0, code, "the text bridge accepted a symlink as its socket") + self.assertTrue(socket_path.is_symlink(), "the text bridge removed a symlink") + self.assertEqual("keep", target.read_text()) + + def launch_expecting_failure(self, socket_path, display): + stream = open(self.log, "wb") + self.addCleanup(stream.close) + process = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], + env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL, + stdout=stream, stderr=subprocess.STDOUT) + self.addCleanup(self.stop_helper, process) + try: + return process.wait(timeout=15) + except subprocess.TimeoutExpired: + self.fail("the text bridge kept running on an occupied path") + + @staticmethod + def kill_pid(pid): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + + @staticmethod + def pid_alive(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + try: + state = Path("/proc/%d/stat" % pid).read_text().rsplit(")", 1)[1].split()[0] + except (OSError, IndexError): + return False + return state != "Z" + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_wayland_host_order.py b/tools/tests/test_wayland_host_order.py new file mode 100644 index 0000000000..44dc7f3088 --- /dev/null +++ b/tools/tests/test_wayland_host_order.py @@ -0,0 +1,487 @@ +"""Compiled FIFO regression for the native host queue in droiddeck_ext.c.""" + +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +CC = shutil.which("cc") +ROOT = Path(__file__).resolve().parents[2] +SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/droiddeck_ext.c" +HEADER = SOURCE.with_name("droiddeck_ext.h") + +WAYLAND_H = """ +#ifndef STUB_WAYLAND_SERVER_H +#define STUB_WAYLAND_SERVER_H +#include +struct wl_display; +struct wl_event_loop; +struct wl_resource; +struct wl_client; +struct wl_event_source; +#define WL_EVENT_READABLE 1u +struct wl_event_loop *wl_display_get_event_loop(struct wl_display *); +void wl_display_flush_clients(struct wl_display *); +struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *, int, uint32_t, + int (*)(int, uint32_t, void *), void *); +#endif +""" + +ANDROID_H = """ +#ifndef STUB_ANDROID_LOG_H +#define STUB_ANDROID_LOG_H +#define ANDROID_LOG_ERROR 6 +int __android_log_print(int, const char *, const char *, ...); +#endif +""" + +AHB_H = """ +#ifndef STUB_AHB_SWAPCHAIN_H +#define STUB_AHB_SWAPCHAIN_H +void ahb_swapchain_set_mode(int, int); +#endif +""" + +COLOR_H = """ +#ifndef STUB_DROIDDECK_COLOR_H +#define STUB_DROIDDECK_COLOR_H +void droiddeck_color_set_output(int); +#endif +""" + +PROGRAM = """ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#include "android/log.h" +#include "droiddeck_ext.h" +#include "ahb_swapchain.h" +#include "droiddeck_color.h" +#include "droiddeck_ext.c" + +#define CHECK(c) do { if (!(c)) { fprintf(stderr, "check failed at line %d", __LINE__); return 1; } } while (0) + +struct ev { int kind; uint32_t a; int b; char text[64]; }; +static struct ev g_ev[32]; +static int g_n; +static int g_native_key_down[KEY_CNT]; +static uint32_t g_pending_raw_release; +static int g_display_stub; +static int g_loop_stub; +static int g_fallback_accept; +static int g_fallback_token; +static int g_hdr_count; + +int text_input_host_commit(const char *u, size_t n) +{ + struct ev *e; + if (n == 3 && memcmp(u, "x11", 3) == 0) + return 0; + if (g_n >= 32 || n >= sizeof(g_ev[0].text)) + return 0; + e = &g_ev[g_n++]; + e->kind = 1; + e->a = (uint32_t)n; + memcpy(e->text, u, n); + e->text[n] = 0; + return 1; +} + +void text_input_host_preedit(const char *u, size_t n, int a, int b) +{ + (void)u; (void)n; (void)a; (void)b; +} + +void text_input_host_delete(int a, int b) { (void)a; (void)b; } +void clipboard_host_text(char *u, size_t n) { (void)n; free(u); } +int droiddeck_on_text_input_fallback(const char *u, int n, int token) +{ + if (!g_fallback_accept) return 0; + if (n == 3 && memcmp(u, "x11", 3) == 0) { + g_fallback_token = token; + return 1; + } + g_fallback_token = token; + return 1; +} + +int droiddeck_key_is_down(uint32_t k) +{ + return k < KEY_CNT && g_native_key_down[k]; +} + +void droiddeck_inject_key(uint32_t k, int s) +{ + if (k < KEY_CNT) + g_native_key_down[k] = s; + if (g_n < 32) { + g_ev[g_n].kind = 2; + g_ev[g_n].a = k; + g_ev[g_n].b = s; + g_ev[g_n].text[0] = 0; + g_n++; + } +} + +void droiddeck_dispatch_pending_input(void) +{ + if (!g_pending_raw_release) return; + droiddeck_inject_key(g_pending_raw_release, 0); + g_pending_raw_release = 0; +} + +void clipboard_init(struct wl_display *d) { (void)d; } +void text_input_init(struct wl_display *d) { (void)d; } +void toplevel_icon_init(struct wl_display *d) { (void)d; } +void single_pixel_init(struct wl_display *d) { (void)d; } +void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; } +void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; } + +struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; } +void wl_display_flush_clients(struct wl_display *d) { (void)d; } + +struct wl_event_loop *wl_display_get_event_loop(struct wl_display *d) +{ + (void)d; + return (struct wl_event_loop *)&g_loop_stub; +} + +struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, + uint32_t m, int (*f)(int, uint32_t, void *), void *d) +{ + (void)l; (void)fd; (void)m; (void)f; (void)d; + return NULL; +} + +void droiddeck_log(const char *t, const char *f, ...) { (void)t; (void)f; } + +int __android_log_print(int p, const char *t, const char *f, ...) +{ + (void)p; (void)t; (void)f; + return 0; +} + +int main(void) +{ + int saved; + CHECK(pipe2(g_wake, O_CLOEXEC | O_NONBLOCK) == 0); + droiddeck_host_text_commit("中文", (int)strlen("中文")); + droiddeck_host_key(28, 1); + droiddeck_host_key(28, 0); + droiddeck_host_text_commit("日本語", (int)strlen("日本語")); + droiddeck_host_key(14, 1); + droiddeck_host_key(14, 0); + droiddeck_host_key(111, 1); + droiddeck_host_key(111, 0); + droiddeck_host_key(15, 1); + droiddeck_host_key(15, 0); + CHECK(g_n == 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 10); + CHECK(g_ev[0].kind == 1 && strcmp(g_ev[0].text, "中文") == 0); + CHECK(g_ev[1].kind == 2 && g_ev[1].a == 28u && g_ev[1].b == 1); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == 28u && g_ev[2].b == 0); + CHECK(g_ev[3].kind == 1 && strcmp(g_ev[3].text, "日本語") == 0); + CHECK(g_ev[4].kind == 2 && g_ev[4].a == 14u && g_ev[4].b == 1); + CHECK(g_ev[5].kind == 2 && g_ev[5].a == 14u && g_ev[5].b == 0); + CHECK(g_ev[6].kind == 2 && g_ev[6].a == 111u && g_ev[6].b == 1); + CHECK(g_ev[7].kind == 2 && g_ev[7].a == 111u && g_ev[7].b == 0); + CHECK(g_ev[8].kind == 2 && g_ev[8].a == 15u && g_ev[8].b == 1); + CHECK(g_ev[9].kind == 2 && g_ev[9].a == 15u && g_ev[9].b == 0); + saved = g_n; + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved); + droiddeck_host_text_commit("尾", (int)strlen("尾")); + droiddeck_host_key(16, 1); + droiddeck_host_key(16, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 3); + CHECK(g_ev[saved].kind == 1 && strcmp(g_ev[saved].text, "尾") == 0); + CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 16u && g_ev[saved + 1].b == 1); + CHECK(g_ev[saved + 2].kind == 2 && g_ev[saved + 2].a == 16u && g_ev[saved + 2].b == 0); + CHECK(g_head == NULL && g_tail == NULL); + saved = g_n; + g_fallback_accept = 1; + droiddeck_host_text_commit("x11", 3); + droiddeck_host_key(29, 1); + droiddeck_host_key(28, 1); + droiddeck_host_key(28, 0); + droiddeck_host_key(29, 0); + droiddeck_host_text_commit("later", 5); + droiddeck_host_hdr_output(1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved); + CHECK(g_hdr_count == 1); + CHECK(g_fallback_token > 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token + 1, DROIDDECK_TEXT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved); + droiddeck_host_key(30, 1); + droiddeck_host_key(30, 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 7); + CHECK(g_ev[saved].kind == 2 && g_ev[saved].a == 29u && g_ev[saved].b == 1); + CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 28u && g_ev[saved + 1].b == 1); + CHECK(g_ev[saved + 2].kind == 2 && g_ev[saved + 2].a == 28u && g_ev[saved + 2].b == 0); + CHECK(g_ev[saved + 3].kind == 2 && g_ev[saved + 3].a == 29u && g_ev[saved + 3].b == 0); + CHECK(g_ev[saved + 4].kind == 1 && strcmp(g_ev[saved + 4].text, "later") == 0); + CHECK(g_ev[saved + 5].kind == 2 && g_ev[saved + 5].a == 30u && g_ev[saved + 5].b == 1); + CHECK(g_ev[saved + 6].kind == 2 && g_ev[saved + 6].a == 30u && g_ev[saved + 6].b == 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 7); + g_fallback_accept = 0; + droiddeck_host_text_commit("x11", 3); + droiddeck_host_key(31, 1); + droiddeck_host_key(31, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 9); + CHECK(g_ev[saved + 7].kind == 2 && g_ev[saved + 7].a == 31u && g_ev[saved + 7].b == 1); + CHECK(g_ev[saved + 8].kind == 2 && g_ev[saved + 8].a == 31u && g_ev[saved + 8].b == 0); + CHECK(g_head == NULL && g_tail == NULL); + g_n = saved = 0; + g_fallback_accept = 1; + droiddeck_host_key(29, 1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 1); + CHECK(g_ev[saved].kind == 2 && g_ev[saved].a == 29u && g_ev[saved].b == 1); + droiddeck_host_text_commit("x11", 3); + droiddeck_host_select_game_field(0); + droiddeck_host_text_commit("discard", 7); + droiddeck_host_key(29, 0); + droiddeck_host_key(32, 1); + droiddeck_host_key(32, 0); + droiddeck_host_hdr_output(0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 1); + CHECK(g_hdr_count == 2); + CHECK(g_fallback_token > 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 2); + CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 29u && g_ev[saved + 1].b == 0); + droiddeck_host_text_commit("held", 4); + droiddeck_host_key(33, 1); + droiddeck_host_key(33, 0); + droiddeck_host_key(34, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 2); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + droiddeck_host_text_commit("resume", 6); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == saved + 14); + CHECK(g_ev[saved + 2].a == KEY_LEFTCTRL && g_ev[saved + 2].b == 1); + CHECK(g_ev[saved + 3].a == KEY_A && g_ev[saved + 3].b == 1); + CHECK(g_ev[saved + 5].a == KEY_LEFTCTRL && g_ev[saved + 5].b == 0); + CHECK(g_ev[saved + 6].kind == 1 && strcmp(g_ev[saved + 6].text, "discard") == 0); + CHECK(g_ev[saved + 7].a == 32u && g_ev[saved + 7].b == 1); + CHECK(g_ev[saved + 9].kind == 1 && strcmp(g_ev[saved + 9].text, "held") == 0); + CHECK(g_ev[saved + 13].kind == 1 && strcmp(g_ev[saved + 13].text, "resume") == 0); + CHECK(g_head == NULL && g_tail == NULL); + for (int pending = 0; pending <= 1; ++pending) { + g_n = 0; + droiddeck_inject_key(KEY_LEFTCTRL, 1); + if (pending) + droiddeck_host_text_commit("x11", 3); + droiddeck_host_select_game_field(0); + droiddeck_host_text_commit("body", 4); + if (pending) { + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 1); + } + droiddeck_inject_key(KEY_LEFTCTRL, 0); + if (pending) + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 7); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_LEFTCTRL && g_ev[2].b == 1); + CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_A && g_ev[3].b == 1); + CHECK(g_ev[4].kind == 2 && g_ev[4].a == KEY_A && g_ev[4].b == 0); + CHECK(g_ev[5].kind == 2 && g_ev[5].a == KEY_LEFTCTRL && g_ev[5].b == 0); + CHECK(g_ev[6].kind == 1 && strcmp(g_ev[6].text, "body") == 0); + CHECK(!droiddeck_key_is_down(KEY_LEFTCTRL)); + CHECK(g_head == NULL && g_tail == NULL); + } + + g_n = 0; + droiddeck_inject_key(KEY_RIGHTCTRL, 1); + droiddeck_host_select_game_field(1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 5); + CHECK(g_ev[1].kind == 2 && g_ev[1].a == KEY_A && g_ev[1].b == 1); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_A && g_ev[2].b == 0); + CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_C && g_ev[3].b == 1); + CHECK(g_ev[4].kind == 2 && g_ev[4].a == KEY_C && g_ev[4].b == 0); + CHECK(droiddeck_key_is_down(KEY_RIGHTCTRL)); + droiddeck_inject_key(KEY_RIGHTCTRL, 0); + CHECK(g_head == NULL && g_tail == NULL); + + for (int copy = 0; copy <= 1; ++copy) { + uint32_t key = copy ? KEY_C : KEY_A; + g_n = 0; + droiddeck_inject_key(key, 1); + g_pending_raw_release = key; + droiddeck_host_select_game_field(copy); + droiddeck_host_text_commit("body", 4); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_pending_raw_release == 0); + CHECK(g_n == (copy ? 9 : 7)); + CHECK(g_ev[1].kind == 2 && g_ev[1].a == key && g_ev[1].b == 0); + CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_LEFTCTRL && g_ev[2].b == 1); + CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_A && g_ev[3].b == 1); + if (copy) CHECK(g_ev[5].kind == 2 && g_ev[5].a == KEY_C && g_ev[5].b == 1); + CHECK(g_ev[g_n - 1].kind == 1 && strcmp(g_ev[g_n - 1].text, "body") == 0); + CHECK(!droiddeck_key_is_down(key)); + } + + for (int held = 0; held <= 1; ++held) { + g_n = 0; + if (held) { + droiddeck_host_key(KEY_ENTER, 1); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(droiddeck_key_is_down(KEY_ENTER)); + g_n = 0; + } + droiddeck_host_text_commit("x11", 3); + droiddeck_host_key(KEY_LEFTCTRL, 1); + if (!held) droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + droiddeck_host_key(KEY_KPENTER, 1); + droiddeck_host_key(KEY_KPENTER, 0); + droiddeck_host_text_commit("\\r", 1); + droiddeck_host_key(KEY_LEFTCTRL, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 0); + droiddeck_host_text_commit("later", 5); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == (held ? 6 : 5)); + CHECK(g_ev[0].a == KEY_LEFTCTRL && g_ev[0].b == 1); + if (held) CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 0); + CHECK(g_ev[g_n - 4].a == KEY_LEFTCTRL && g_ev[g_n - 4].b == 0); + CHECK(g_ev[g_n - 3].kind == 1 && strcmp(g_ev[g_n - 3].text, "later") == 0); + CHECK(g_ev[g_n - 2].a == KEY_ENTER && g_ev[g_n - 2].b == 1); + CHECK(g_ev[g_n - 1].a == KEY_ENTER && g_ev[g_n - 1].b == 0); + CHECK(!droiddeck_key_is_down(KEY_ENTER) && !droiddeck_key_is_down(KEY_LEFTCTRL)); + } + + g_n = 0; + droiddeck_host_text_commit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 2 && g_ev[0].a == KEY_ENTER && g_ev[0].b == 1 && g_ev[1].b == 0); + + g_n = 0; + droiddeck_host_text_commit_and_submit("wayland", 7); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 3 && g_ev[0].kind == 1 && strcmp(g_ev[0].text, "wayland") == 0); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1); + CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0); + + for (int result = DROIDDECK_TEXT_NOT_DELIVERED; result <= DROIDDECK_TEXT_DELIVERED; ++result) { + g_n = 0; + droiddeck_host_text_commit_and_submit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 0); + droiddeck_host_text_commit("later", 5); + droiddeck_host_text_input_fallback_complete(g_fallback_token, result); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == (result == DROIDDECK_TEXT_DELIVERED ? 3 : 1)); + if (result == DROIDDECK_TEXT_DELIVERED) { + CHECK(g_ev[0].a == KEY_ENTER && g_ev[0].b == 1); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 0); + } + CHECK(g_ev[g_n - 1].kind == 1 && strcmp(g_ev[g_n - 1].text, "later") == 0); + } + + g_n = 0; + g_fallback_accept = 0; + droiddeck_host_text_commit_and_submit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 0); + droiddeck_host_text_commit("next", 4); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 3 && g_ev[0].kind == 1 && strcmp(g_ev[0].text, "next") == 0); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1); + CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0); + + g_n = 0; + g_fallback_accept = 1; + droiddeck_host_key(KEY_LEFTCTRL, 1); + droiddeck_host_text_commit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED); + droiddeck_host_key(KEY_LEFTCTRL, 0); + droiddeck_host_key(KEY_ENTER, 1); + for (int i = 0; i <= DROIDDECK_TEXT_DEFERRED_LIMIT; i++) + droiddeck_host_text_commit("queued", 6); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 2 && !droiddeck_key_is_down(KEY_LEFTCTRL)); + CHECK(g_deferred_overflow && !g_deferred_head && !g_deferred_count && !g_deferred_bytes); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_n == 4 && !droiddeck_key_is_down(KEY_ENTER)); + + g_n = 0; + droiddeck_host_text_commit("x11", 3); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0); + droiddeck_host_text_commit("\\r", 1); + droiddeck_host_text_commit("next", 4); + droiddeck_host_key(KEY_ENTER, 1); + droiddeck_host_key(KEY_ENTER, 0); + CHECK(on_wake(g_wake[0], 0, NULL) == 0 && g_n == 0); + droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED); + CHECK(on_wake(g_wake[0], 0, NULL) == 0 && g_n == 3); + CHECK(g_ev[0].kind == 1 && strcmp(g_ev[0].text, "next") == 0); + CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1); + CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0); + + close(g_wake[0]); + close(g_wake[1]); + return 0; +} +""" + +@unittest.skipUnless(sys.platform.startswith("linux"), "requires Linux pipe2") +@unittest.skipUnless(CC, "requires cc") +class WaylandHostOrderTest(unittest.TestCase): + def test_fifo_order(self): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / "android").mkdir() + (tmp / "android/log.h").write_text(ANDROID_H) + (tmp / "wayland-server.h").write_text(WAYLAND_H) + (tmp / "ahb_swapchain.h").write_text(AHB_H) + (tmp / "droiddeck_color.h").write_text(COLOR_H) + shutil.copyfile(SOURCE, tmp / "droiddeck_ext.c") + shutil.copyfile(HEADER, tmp / "droiddeck_ext.h") + (tmp / "program.c").write_text(PROGRAM, encoding="utf-8") + subprocess.run([CC, "-std=c11", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", "-pthread", "-I", str(tmp), + "-o", str(tmp / "probe"), str(tmp / "program.c")], + cwd=tmp, check=True, timeout=30) + subprocess.run([str(tmp / "probe")], cwd=tmp, check=True, timeout=10) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_windows_vr_build.py b/tools/tests/test_windows_vr_build.py index fa51a169ac..56da16b422 100644 --- a/tools/tests/test_windows_vr_build.py +++ b/tools/tests/test_windows_vr_build.py @@ -122,6 +122,60 @@ class WindowsVrBuildTest(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'configuration differs'): self.validate() + def test_build_image_selection_and_platform_validation(self): + outputs = vr.read_outputs(self.out, self.root) + cases = [ + ('cached_amd64', vr.IMAGE, [(0, 'sha256:cached linux/amd64\n')], False, 'sha256:cached', None), + ('missing_default', vr.IMAGE, [(1, ''), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None), + ('default_arm64', vr.IMAGE, [(0, 'sha256:old linux/arm64\n'), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None), + ('default_windows', vr.IMAGE, [(0, 'sha256:old windows/amd64\n'), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None), + ('custom_arm64', 'custom:vr', [(0, 'sha256:custom linux/arm64\n')], False, None, r'linux/amd64.*custom:vr'), + ('rebuild_still_arm64', vr.IMAGE, [(0, 'sha256:old linux/arm64\n'), (0, 'sha256:bad linux/arm64\n')], True, None, r'linux/amd64'), + ] + for name, image, inspects, expect_build, expected_id, err in cases: + with self.subTest(name=name): + calls, queue = [], list(inspects) + def fake_run(cmd, **kw): + calls.append(cmd) + if cmd[1:3] == ['image', 'inspect']: + rc, out = queue.pop(0) + return vr.subprocess.CompletedProcess(cmd, rc, stdout=out, stderr='') + return vr.subprocess.CompletedProcess(cmd, 0, stdout='linux\n', stderr='') + with mock.patch.object(vr.shutil, 'which', return_value='docker'), \ + mock.patch.object(vr.subprocess, 'run', side_effect=fake_run), \ + mock.patch.object(vr.subprocess, 'check_output', return_value=b'sha256:legacy\n'), \ + mock.patch.object(vr, 'read_outputs', return_value=outputs) as m_read, \ + mock.patch.object(vr, 'validate', return_value=(outputs, self.manifest)) as m_val: + if err: + with self.assertRaisesRegex(ValueError, err): + vr.build(self.out, self.include, self.root, image=image) + m_read.assert_not_called() + m_val.assert_not_called() + else: + self.assertEqual(vr.build(self.out, self.include, self.root, image=image), (outputs, self.manifest)) + m_read.assert_called_once() + m_val.assert_called_once_with(self.out, self.include, self.root) + inspect_cmds = [c for c in calls if c[1:3] == ['image', 'inspect']] + build_cmds = [c for c in calls if c[1] == 'build'] + run_cmds = [c for c in calls if c[1] == 'run'] + self.assertEqual(len(inspect_cmds), len(inspects)) + for c in inspect_cmds: + self.assertEqual(c[:5], ['docker', 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}']) + if expect_build: + self.assertEqual(len(build_cmds), 1) + self.assertEqual(build_cmds[0][:6], ['docker', 'build', '--platform', 'linux/amd64', '--tag', image]) + else: + self.assertEqual(build_cmds, []) + if expected_id: + self.assertEqual(len(run_cmds), 1) + self.assertIn(expected_id, run_cmds[0]) + self.assertNotIn(image, run_cmds[0]) + self.assertTrue(all('linux/amd64' not in a or a == 'linux/amd64' for a in run_cmds[0])) + manifest = json.loads((self.out / vr.MANIFEST).read_text(encoding='utf-8')) + self.assertEqual(manifest['compiler_image'], expected_id) + else: + self.assertEqual(run_cmds, []) + if __name__ == '__main__': unittest.main() diff --git a/tools/vr/build_windows.py b/tools/vr/build_windows.py index af8fa4d465..d5cd2e6d35 100644 --- a/tools/vr/build_windows.py +++ b/tools/vr/build_windows.py @@ -10,7 +10,7 @@ import subprocess import tempfile ROOT = Path(__file__).resolve().parents[2] -IMAGE = 'droiddeck-local-cross:24.04-v3' +IMAGE = 'droiddeck-local-cross:24.04-v5' MANIFEST = 'vr-build.json' SOURCE_TREES = ('tools/vr/src', 'tools/vr/tests', 'tools/vr/third_party', 'tools/vr/driver_droiddeck', 'tools/vr/layer') @@ -131,14 +131,22 @@ def build(folder, include, root=ROOT, image=IMAGE): snapshot = Path(temp).resolve() if not snapshot.is_relative_to(workspace): raise ValueError('Temporary VR workspace escapes the checkout') - inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}}', image], + inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image], capture_output=True, text=True) - if inspect.returncode: + parts = inspect.stdout.strip().split() if inspect.returncode == 0 else [] + if len(parts) == 2 and parts[1] == 'linux/amd64' and parts[0]: + image_id = parts[0] + else: if image != IMAGE: - raise ValueError('VR compiler image is not available locally: ' + image) - subprocess.run([docker, 'build', '--tag', image, '--file', '-', str(snapshot)], + raise ValueError(f'VR compiler image is not available locally for linux/amd64: {image} (got {inspect.stdout.strip() or "missing"})') + subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image, '--file', '-', str(snapshot)], input=input_files['tools/local-cross.Dockerfile'], check=True) - image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', image]).decode().strip() + inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image], + capture_output=True, text=True, check=True) + parts = inspect.stdout.strip().split() + if len(parts) != 2 or parts[1] != 'linux/amd64' or not parts[0]: + raise ValueError(f'VR compiler image {image} expected id and linux/amd64, got {inspect.stdout.strip()!r}') + image_id = parts[0] for name, data in input_files.items(): target = snapshot / name target.parent.mkdir(parents=True, exist_ok=True) From f9eeef44ed277b1378be855f2d476f404183750c Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 07:39:12 -0500 Subject: [PATCH 19/80] Keep the last frame visible on manual pause (#3626) Use the effective zero-copy profile to capture and restore presentation across manual pause and resume, without overriding a disabled preference. --- .../com/droiddeck/launcher/SessionActivity.kt | 2 +- .../launcher/session/SessionPrefs.kt | 4 +-- .../session/SessionPrefsZeroCopyTest.kt | 36 +++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index cd96432a0c..3f11e0b979 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -6281,7 +6281,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val back = { if (restore.compareAndSet(false, true)) { pauseCaptures-- - if (!isDestroyed) WaylandCompositor.nativeSetZeroCopy(composedOutputFree()) + if (!isDestroyed && zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree()) } } uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS) 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 4785f06909..3a33e47be3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1874,10 +1874,10 @@ object SessionPrefs { prefs(context).edit().putBoolean(hdrKey(mode), on).apply() } - fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.$mode", true) + fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true) fun setZeroCopy(context: Context, mode: String, on: Boolean) { - prefs(context).edit().putBoolean("zeroCopy.$mode", on).apply() + prefs(context).edit().putBoolean("zeroCopy.${prefMode(mode)}", on).apply() } const val FPS_UNPACED = -1 diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt new file mode 100644 index 0000000000..8f34aef2e8 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsZeroCopyTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class SessionPrefsZeroCopyTest { + private val app get() = RuntimeEnvironment.getApplication() + + @Test fun standaloneGamesUseTheSteamPresentationSetting() { + SessionPrefs.setZeroCopy(app, SessionService.MODE_STEAM, false) + + assertFalse(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN)) + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_DESKTOP)) + + SessionPrefs.setZeroCopy(app, SessionService.MODE_RUN, true) + + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_STEAM)) + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN)) + } + + @Test fun aRawRunKeyCannotDisagreeWithTheSteamSetting() { + app.getSharedPreferences("session", Context.MODE_PRIVATE) + .edit().putBoolean("zeroCopy.run", false).commit() + SessionPrefs.setZeroCopy(app, SessionService.MODE_STEAM, true) + + assertTrue(SessionPrefs.zeroCopy(app, SessionService.MODE_RUN)) + } +} From 8b3cc7eb152f08a43309ac89c799219917b1af21 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:54:26 -0500 Subject: [PATCH 20/80] Wire XR keyboard text into the session input queue (#3631) Initialize KeyboardHost with the updated key and text callbacks. Keep XR physical-key routing and use the regular ordered compositor queue for text. --- .../java/com/droiddeck/launcher/SessionActivity.kt | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 3f11e0b979..2c8f179349 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -1605,10 +1605,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde /** The VR keyboard's keys go straight to the game, past the menu and pad handling a real key passes through. */ private val xrKeys by lazy { - com.droiddeck.launcher.input.KeyboardHost(this) { event -> - CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) && - com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) } - } + KeyboardHost( + this, + sendKeyEvent = { event -> + CompositorHost.isStarted && (event.action != KeyEvent.ACTION_DOWN || event.repeatCount == 0) && + com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, 16) } + }, + sendText = { text -> if (CompositorHost.isStarted) WaylandCompositor.textInputCommit(text) }, + ) } @androidx.compose.runtime.Composable From 7138f95c909731d5482daaa4da16f161c8e7e41a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:45:41 -0500 Subject: [PATCH 21/80] fix(onboarding): no wireless-debugging step on first run when the session runs outside the child-process count (#3639) Before the runtime is installed, the rootfs has no native hook yet, so the child-process check assumed the next session would be counted and showed "Finish setup" for wireless debugging. The session stages the hook from the APK before it starts, so predict the next session from the setting and the rootfs loader instead; a runtime still to be installed will have one. --- .../com/droiddeck/launcher/runtime/GuestWorkers.kt | 9 +++++---- .../java/com/droiddeck/launcher/runtime/NativeGuest.kt | 10 ++++++++++ .../com/droiddeck/launcher/runtime/NativeGuestTest.kt | 8 ++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) 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 4d6a1de6fb..b4843fc6df 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestWorkers.kt @@ -395,9 +395,10 @@ object GuestWorkers { private set /** Whether the session runs its programs in workers: the native userland, and not turned off. */ - fun enabled(context: Context): Boolean = - android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) && - NativeGuest.enabled(context) + fun enabled(context: Context): Boolean = handoffAllowed(context) && NativeGuest.enabled(context) + + private fun handoffAllowed(context: Context): Boolean = + android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.session.SessionPrefs.childProcessHandoff(context) /** How the running session's root was started: in a worker (true) or counted (false); null with none running. */ @Volatile var sessionRootUncounted: Boolean? = null @@ -408,7 +409,7 @@ object GuestWorkers { * the next one would start. */ fun limitHandled(context: Context): Boolean = - sessionRootUncounted ?: (NativeGuest.sessionMode != false && enabled(context)) + sessionRootUncounted ?: (NativeGuest.sessionMode != false && handoffAllowed(context) && NativeGuest.nextSession(context)) /** Whether pid is a program running in one of the workers. */ fun runsInWorker(pid: Int): Boolean = pid > 0 && synchronized(slots) { slots.any { it != null && it.started && it.pid == pid } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt index babaae550a..95a660eaf4 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/NativeGuest.kt @@ -24,6 +24,16 @@ object NativeGuest { fun enabled(context: Context): Boolean = SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context)) + /** + * Whether the next session will start natively. The session stages the hook from the APK before + * it starts, so only the setting and the rootfs's loader decide, and a runtime still to be + * installed will have one. + */ + fun nextSession(context: Context): Boolean = + SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context)) + + internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null + /** The mode the running session started in; null between sessions. */ @Volatile var sessionMode: Boolean? = null diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt index d8ea5ee185..563b09dd36 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/NativeGuestTest.kt @@ -12,6 +12,14 @@ class NativeGuestTest { File(it, "usr/lib/ld-linux-aarch64.so.1").writeText("") } + @Test + fun aRuntimeStillToBeInstalledRunsTheNextSessionNatively() { + val empty = Files.createTempDirectory("native-root").toFile() + assertTrue(NativeGuest.willRun(empty, installed = false)) + assertEquals(false, NativeGuest.willRun(empty, installed = true)) + assertTrue(NativeGuest.willRun(rootWithLoader(), installed = true)) + } + @Test fun theSeccompSwitchNamesAHelperAndItsArgumentsInTheRootfs() { val root = Files.createTempDirectory("rootfs").toFile() From 18d735b4c4fdff56f53f61eb6d26129296bbfee6 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:49:09 -0500 Subject: [PATCH 22/80] feat(ui): tabs that do not fit a narrow page open as a dropdown (#3640) * feat(ui): tabs that do not fit a narrow page open as a dropdown In portrait or on a narrow page, a row of section pills that would scroll sideways becomes one chip naming the shown section, which opens the list of sections, as the second screen's picker does. Covers the sheets' pills (Steam, desktop, glasses, Settings and the others on SheetChips), TabStrip, the game page's tabs and the Stores chips. * fix(stores): the compact store picker takes controller focus, survives a hidden store and keeps the signed-out status * fix(ui): picking the shown tab from the tab menu still activates it --- .../com/droiddeck/launcher/ui/GameDetail.kt | 4 + .../com/droiddeck/launcher/ui/LiftSheet.kt | 4 + .../droiddeck/launcher/ui/SettingsWidgets.kt | 5 +- .../com/droiddeck/launcher/ui/StoresPage.kt | 17 ++- .../java/com/droiddeck/launcher/ui/TabMenu.kt | 102 ++++++++++++++++++ 5 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index 36075081e6..e4dcb6c4d2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -415,6 +415,10 @@ private fun GameTabBar( if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) } androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f).clip(if (bumpers) RoundedCornerShape(BumperFlat) else CircleShape).onSizeChanged { viewport = it.width }) { val share = maxWidth / tabs.size.coerceAtLeast(1) + if (tabsAsMenu(maxWidth, tabs.size)) { + TabMenu(tabs, selected, onSelect, focus = focusRequesters) + return@BoxWithConstraints + } Box(Modifier.horizontalScroll(scroll)) { spans.getOrNull(selected)?.takeIf { tabHeight > 0 }?.let { span -> TabHighlight(span, tabHeight, flatStart = bumpers && selected == 0, flatEnd = bumpers && selected == tabs.lastIndex) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 66f6ea110a..6769798ad9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -711,6 +711,10 @@ internal fun SheetChips( Modifier.fillMaxWidth().onFocusChanged { within = it.hasFocus }, contentAlignment = Alignment.CenterStart, ) { + if (tabsAsMenu(maxWidth, labels.size)) { + TabMenu(labels, selected, onPick, focus = chips) + return@BoxWithConstraints + } val equal = !width.isSpecified && maxWidth / labels.size.coerceAtLeast(1) >= 96.dp val least = if (width.isSpecified) maxOf(width, 64.dp) else 64.dp val scroll = rememberScrollState() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 2c51442cd1..5d09490e39 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -212,7 +212,8 @@ internal fun TabStrip( Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) { if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) } // Centred, the bumpers sit at the edges and the tabs in the middle, as in the bottom bar. - Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { Row( + Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { androidx.compose.foundation.layout.BoxWithConstraints { + if (tabsAsMenu(maxWidth, tabs.size)) TabMenu(tabs, selected, onSelect, focus = focusRequesters) else Row( modifier = Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape) .horizontalScroll(scroll).selectableGroup().padding(3.dp), ) { @@ -239,7 +240,7 @@ internal fun TabStrip( .padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp), ) } - } } + } } } if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 963c2f9c99..bb6bbbc271 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -470,7 +470,21 @@ private fun StoreChips( val tabScroll = rememberScrollState() Box(Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - Box(Modifier.weight(1f).edgeFade(tabScroll).horizontalScroll(tabScroll)) { + val shown = tabs.filter { it.shown }.map { it.store } + androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f)) { + if (tabsAsMenu(maxWidth, shown.size)) TabMenu( + shown.map { it.shortLabel }, shown.indexOfFirst { it.id == selected }, { onStore(shown[it]) }, + chipModifier = shown.fold(Modifier as Modifier) { m, st -> key(st) { m.paneItem("storechip:${st.id}") } }, + descriptions = shown.map { st -> + val signedIn = StoresState.isSignedIn(st) && StoresState.expired[st] != true + st.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out) + }, + leading = { i, inList -> + val signedIn = StoresState.isSignedIn(shown[i]) && StoresState.expired[shown[i]] != true + if (inList) Box(Modifier.size(12.dp).background(sourceColours(shown[i].id).dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape)) + else StoreDot(shown[i], signedIn) + }, + ) else Box(Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll)) { Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { for (tab in tabs) { val store = tab.store @@ -492,6 +506,7 @@ private fun StoreChips( } ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } + } var cogAt by remember { mutableStateOf(null) } Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt new file mode 100644 index 0000000000..cf2d235999 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsFocusedAsState +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.ExpandLess +import androidx.compose.material.icons.outlined.ExpandMore +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +private val TAB_MENU_BELOW = 600.dp +private val TAB_MIN_WIDTH = 96.dp + +/** Whether [count] tabs in [width] become a [TabMenu]: on a narrow page, when they would not fit side by side. */ +internal fun tabsAsMenu(width: Dp, count: Int): Boolean = + count > 2 && width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH + +/** + * Tabs as one chip naming the shown tab, which opens the list of them, as the second screen's + * picker does. Each of [focus] lands on the chip, so callers that focus a tab still reach it. + */ +@Composable +internal fun TabMenu( + labels: List, selected: Int, onPick: (Int) -> Unit, + modifier: Modifier = Modifier, focus: List? = null, + chipModifier: Modifier = Modifier, descriptions: List? = null, + leading: (@Composable (index: Int, inList: Boolean) -> Unit)? = null, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember { mutableStateOf(false) } + val source = remember { MutableInteractionSource() } + val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value + val shape = RoundedCornerShape(22.dp) + val label = labels.getOrNull(selected).orEmpty() + val description = descriptions?.getOrNull(selected) ?: label + val toggle = { open = !open } + Box(modifier) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = focus.orEmpty().fold(chipModifier.height(44.dp)) { m, r -> m.focusRequester(r) } + .testTag("tab-menu") + .semantics { contentDescription = description } + .clip(shape).background(if (hot || open) pal.signal.copy(alpha = 0.14f) else colors.surfaceVariant) + .glideBorder(hot || open, shape, pal.signal, pal.line2) + .hoverable(source) + .clickable(role = Role.Button, interactionSource = source, indication = LocalIndication.current, onClick = toggle) + .controllerConfirm(onClick = toggle) + .padding(start = 14.dp, end = 10.dp), + ) { + if (selected in labels.indices) leading?.invoke(selected, false) + Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1, + overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) + Icon(if (open) Icons.Outlined.ExpandLess else Icons.Outlined.ExpandMore, contentDescription = null, + tint = colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) + } + AnchoredMenu(open, { open = false }, compact = true, minWidth = 200.dp) { first -> + labels.forEachIndexed { i, item -> + MenuItem( + item, checked = i == selected, + leading = leading?.let { { it(i, true) } }, + focusRequester = first.takeIf { i == selected || (i == 0 && selected !in labels.indices) }, + modifier = Modifier.testTag("tab-menu:$i") + .then(descriptions?.getOrNull(i)?.let { d -> Modifier.semantics { contentDescription = d } } ?: Modifier), + ) { open = false; onPick(i) } + } + } + } +} 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 23/80] 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 24/80] 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 25/80] 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 26/80] 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 27/80] 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 28/80] 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 29/80] 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 30/80] 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) } } From 00b354a40a4e941a50e1dedd27fb461c1811f3a0 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:38:15 -0500 Subject: [PATCH 31/80] Fix portrait game tabs and compact Library and Store filters (#3658) Keep About, Launch, and Install in the game detail strip. Use dropdowns for top-level sources in portrait and narrow panes. Default Library title and size overlays to off without overriding saved choices. --- .../launcher/session/SessionPrefs.kt | 4 +- .../com/droiddeck/launcher/ui/GameDetail.kt | 6 +- .../com/droiddeck/launcher/ui/LibraryPage.kt | 73 ++++++++++------- .../com/droiddeck/launcher/ui/StoresPage.kt | 64 +++++++-------- .../java/com/droiddeck/launcher/ui/TabMenu.kt | 7 ++ .../droiddeck/launcher/ui/GameTabBarTest.kt | 40 ++++++++++ .../launcher/ui/LibraryDisplayTest.kt | 35 ++++++++ .../launcher/ui/LibraryVisibilityTest.kt | 2 + .../launcher/ui/SourceTabMenuTest.kt | 79 +++++++++++++++++++ 9 files changed, 241 insertions(+), 69 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt 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 19ad40b695..38fca4ec19 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -364,13 +364,13 @@ object SessionPrefs { prefs(context).edit().putInt("libraryCardLevel", level).apply() } - fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", true) + fun libraryShowTitle(context: Context): Boolean = prefs(context).getBoolean("libraryShowTitle", false) fun setLibraryShowTitle(context: Context, show: Boolean) { prefs(context).edit().putBoolean("libraryShowTitle", show).apply() } - fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", true) + fun libraryShowSize(context: Context): Boolean = prefs(context).getBoolean("libraryShowSize", false) fun setLibraryShowSize(context: Context, show: Boolean) { prefs(context).edit().putBoolean("libraryShowSize", show).apply() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index e4dcb6c4d2..5415293cfb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -396,7 +396,7 @@ private fun GameCapsule(scores: GameScores?, actions: @Composable () -> Unit) { } @Composable -private fun GameTabBar( +internal fun GameTabBar( tabs: List, selected: Int, onSelect: (Int) -> Unit, modifier: Modifier = Modifier, focusRequesters: List? = null, bumpers: Boolean = true, compact: Boolean = false, @@ -415,10 +415,6 @@ private fun GameTabBar( if (bumpers) TabBarBumper("LB", stringResource(R.string.widgets_prev_tab), leading = true) { onSelect((selected + tabs.size - 1) % tabs.size) } androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f).clip(if (bumpers) RoundedCornerShape(BumperFlat) else CircleShape).onSizeChanged { viewport = it.width }) { val share = maxWidth / tabs.size.coerceAtLeast(1) - if (tabsAsMenu(maxWidth, tabs.size)) { - TabMenu(tabs, selected, onSelect, focus = focusRequesters) - return@BoxWithConstraints - } Box(Modifier.horizontalScroll(scroll)) { spans.getOrNull(selected)?.takeIf { tabHeight > 0 }?.let { span -> TabHighlight(span, tabHeight, flatStart = bumpers && selected == 0, flatEnd = bumpers && selected == tabs.lastIndex) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index 0b9d0b399e..20e61f1d1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -17,6 +17,7 @@ import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row @@ -204,9 +205,9 @@ internal object LibraryDisplay { val scales = listOf(0.75f, 0.875f, 1f, 1.2f, 1.45f) var level by mutableIntStateOf(DEFAULT_LEVEL) private set - var title by mutableStateOf(true) + var title by mutableStateOf(false) private set - var size by mutableStateOf(true) + var size by mutableStateOf(false) private set fun load(context: android.content.Context) { @@ -914,7 +915,7 @@ private fun sourceChipsShown(sources: List, manage: Boolean): Boolean = @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable -private fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit, manage: Boolean) { +internal fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit, manage: Boolean) { val chips = sourceChipsShown(sources, manage) if (!chips && !manage) return val pal = LocalPalette.current @@ -931,42 +932,54 @@ private fun LibraryFilters(sources: List, source: String, onSource: (Str horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp), ) { - Box(Modifier.weight(1f).edgeFade(scroll).horizontalScroll(scroll)) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { - for (id in keys) { - val store = Store.byId(id) - val dot = sourceDot(id) - val label = when (id) { - LIBRARY_ALL -> stringResource(R.string.stores_tab_all) - Library.ADDED -> stringResource(R.string.library_custom_games) - LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites) - LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden) - else -> store?.shortLabel ?: sourceLabel(id) - } - androidx.compose.runtime.key(id) { - val reveal = remember { BringIntoViewRequester() } - LaunchedEffect(source) { if (source == id) reveal.bringIntoView() } - StoreChip( - label = label, on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal, - modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id") - .onGloballyPositioned { bounds[id] = it.boundsInParent() }, - lead = { - if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape)) - else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp)) - }, - onFocused = { focused = it }, - paneKey = "libchip:$id", - ) { onSource(id) } + BoxWithConstraints(Modifier.weight(1f)) { + if (sourceTabsAsMenu(maxWidth, keys.size)) { + TabMenu( + keys.map { librarySourceChipLabel(it) }, keys.indexOf(source), { onSource(keys[it]) }, + chipModifier = Modifier.paneItem("libchip:$source"), + leading = { i, _ -> LibrarySourceMark(sourceDot(keys[i])) }, + ) + } else Box(Modifier.edgeFade(scroll).horizontalScroll(scroll)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { + for (id in keys) { + val dot = sourceDot(id) + androidx.compose.runtime.key(id) { + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(source) { if (source == id) reveal.bringIntoView() } + StoreChip( + label = librarySourceChipLabel(id), on = source == id, under = fillShown && highlighted == id, key = id, mark = dot ?: pal.signal, + modifier = Modifier.bringIntoViewRequester(reveal).testTag("library-source-$id") + .onGloballyPositioned { bounds[id] = it.boundsInParent() }, + lead = { LibrarySourceMark(dot) }, + onFocused = { focused = it }, + paneKey = "libchip:$id", + ) { onSource(id) } + } } } + if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } - if (highlighted in keys) ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } if (manage) ManageStoresChip() } } } +@Composable +private fun librarySourceChipLabel(id: String): String = when (id) { + LIBRARY_ALL -> stringResource(R.string.stores_tab_all) + Library.ADDED -> stringResource(R.string.library_custom_games) + LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites) + LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden) + else -> Store.byId(id)?.shortLabel ?: sourceLabel(id) +} + +@Composable +private fun LibrarySourceMark(dot: Color?) { + if (dot != null) Box(Modifier.size(9.dp).background(dot, CircleShape)) + else Icon(Icons.Filled.GridView, null, modifier = Modifier.size(14.dp)) +} + @Composable private fun sourceTitle(src: String): String = when (src) { LIBRARY_ALL -> stringResource(R.string.library_all_games) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index bb6bbbc271..33963e2d34 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -453,7 +453,7 @@ private fun StoreDot(store: Store, signedIn: Boolean) { @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable -private fun StoreChips( +internal fun StoreChips( selected: String, focused: String?, tabs: List, onStore: (Store) -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit, ) { @@ -471,41 +471,41 @@ private fun StoreChips( Box(Modifier.fillMaxWidth()) { Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { val shown = tabs.filter { it.shown }.map { it.store } - androidx.compose.foundation.layout.BoxWithConstraints(Modifier.weight(1f)) { - if (tabsAsMenu(maxWidth, shown.size)) TabMenu( - shown.map { it.shortLabel }, shown.indexOfFirst { it.id == selected }, { onStore(shown[it]) }, - chipModifier = shown.fold(Modifier as Modifier) { m, st -> key(st) { m.paneItem("storechip:${st.id}") } }, - descriptions = shown.map { st -> - val signedIn = StoresState.isSignedIn(st) && StoresState.expired[st] != true - st.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out) - }, - leading = { i, inList -> - val signedIn = StoresState.isSignedIn(shown[i]) && StoresState.expired[shown[i]] != true - if (inList) Box(Modifier.size(12.dp).background(sourceColours(shown[i].id).dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape)) - else StoreDot(shown[i], signedIn) - }, - ) else Box(Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll)) { - Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { - for (tab in tabs) { - val store = tab.store - if (tab.shown) { - val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true - key(store) { - val reveal = remember { BringIntoViewRequester() } - LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() } - StoreChip( - label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, - modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() }, - lead = { StoreDot(store, signedIn) }, - description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), - onFocused = onFocusChip, - ) { onStore(store) } + BoxWithConstraints(Modifier.weight(1f)) { + if (sourceTabsAsMenu(maxWidth, shown.size)) TabMenu( + shown.map { it.shortLabel }, shown.indexOfFirst { it.id == selected }, { onStore(shown[it]) }, + chipModifier = shown.fold(Modifier as Modifier) { m, st -> key(st) { m.paneItem("storechip:${st.id}") } }, + descriptions = shown.map { st -> + val signedIn = StoresState.isSignedIn(st) && StoresState.expired[st] != true + st.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out) + }, + leading = { i, inList -> + val signedIn = StoresState.isSignedIn(shown[i]) && StoresState.expired[shown[i]] != true + if (inList) Box(Modifier.size(12.dp).background(sourceColours(shown[i].id).dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape)) + else StoreDot(shown[i], signedIn) + }, + ) else Box(Modifier.edgeFade(tabScroll).horizontalScroll(tabScroll)) { + Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.focusGroup()) { + for (tab in tabs) { + val store = tab.store + if (tab.shown) { + val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true + key(store) { + val reveal = remember { BringIntoViewRequester() } + LaunchedEffect(selected) { if (selected == store.id) reveal.bringIntoView() } + StoreChip( + label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, + modifier = Modifier.bringIntoViewRequester(reveal).onGloballyPositioned { bounds[store.id] = it.boundsInParent() }, + lead = { StoreDot(store, signedIn) }, + description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), + onFocused = onFocusChip, + ) { onStore(store) } + } } } } + ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } - ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) - } } var cogAt by remember { mutableStateOf(null) } Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt index cf2d235999..c5c31a203c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabMenu.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import android.content.res.Configuration import androidx.compose.foundation.LocalIndication import androidx.compose.foundation.background import androidx.compose.foundation.clickable @@ -30,6 +31,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription @@ -47,6 +49,11 @@ private val TAB_MIN_WIDTH = 96.dp internal fun tabsAsMenu(width: Dp, count: Int): Boolean = count > 2 && width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH +@Composable +internal fun sourceTabsAsMenu(width: Dp, count: Int): Boolean = + count > 1 && (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT || + (width < TAB_MENU_BELOW && width / count < TAB_MIN_WIDTH)) + /** * Tabs as one chip naming the shown tab, which opens the list of them, as the second screen's * picker does. Each of [focus] lands on the chip, so callers that focus a tab still reach it. diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt new file mode 100644 index 0000000000..8b7d15e1b7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/GameTabBarTest.kt @@ -0,0 +1,40 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +class GameTabBarTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun narrowGameDetailsKeepEachTabInTheStrip() { + compose.setContent { + DroidDeckTheme { + Box(Modifier.width(320.dp)) { + var selected by remember { mutableIntStateOf(0) } + GameTabBar(listOf("About", "Launch", "Install"), selected, { selected = it }, compact = true) + } + } + } + compose.onNodeWithTag("tab-menu").assertDoesNotExist() + for (index in 0..2) { + compose.onNodeWithTag("tab-$index").assertIsDisplayed().performClick().assertIsSelected() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt new file mode 100644 index 0000000000..90f44b6c98 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryDisplayTest.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class LibraryDisplayTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + LibraryDisplay.load(context) + } + + @Test fun titleAndSizeDefaultOff() { + assertFalse(LibraryDisplay.title) + assertFalse(LibraryDisplay.size) + } + + @Test fun savedChoicesStillLoad() { + LibraryDisplay.toggleTitle(context) + LibraryDisplay.toggleSize(context) + LibraryDisplay.load(context) + assertTrue(LibraryDisplay.title) + assertTrue(LibraryDisplay.size) + } +} 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 3ed1e0763c..c82f031233 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryVisibilityTest.kt @@ -51,6 +51,7 @@ class LibraryVisibilityTest { StoreAccounts.keys = CredentialCipher.KeyProvider { SecretKeySpec(ByteArray(32) { 7 }, "AES") } StoreAccounts.keystoreFailed = false ctx.getSharedPreferences("session", 0).edit().clear().commit() + SessionPrefs.setLibraryShowTitle(ctx, true) LibraryView.source = LIBRARY_ALL LibraryView.query = "" LibraryView.focusFirst = false @@ -72,6 +73,7 @@ class LibraryVisibilityTest { StoresState.library.clear() StoresState.accounts.clear() ctx.getSharedPreferences("session", 0).edit().clear().commit() + SessionPrefs.setLibraryShowTitle(ctx, true) LibraryView.source = LIBRARY_ALL LibraryView.query = "" LibraryView.focusFirst = false diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt new file mode 100644 index 0000000000..62d3463b7f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SourceTabMenuTest.kt @@ -0,0 +1,79 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assert +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreTab +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +class SourceTabMenuTest { + @get:Rule val compose = createRobolectricComposeRule() + + private fun showLibrary(width: Int = 360) { + compose.setContent { + DroidDeckTheme { + var source by remember { mutableStateOf(LIBRARY_ALL) } + Box(Modifier.width(width.dp)) { + LibraryFilters(listOf(Library.SOURCE_STEAM, Store.EPIC.id), source, { source = it }, manage = true) + } + } + } + } + + @Test fun portraitLibraryPicksASourceAndKeepsManageVisible() { + showLibrary() + compose.onNodeWithTag("library-manage-stores").assertIsDisplayed() + val menu = compose.onNodeWithTag("tab-menu") + menu.assert(hasText("All")).performClick() + compose.onNodeWithTag("tab-menu:2").assertIsDisplayed().performClick() + menu.assert(hasText(Store.EPIC.shortLabel)) + } + + @Test @Config(qualifiers = "w900dp-h500dp-land") + fun wideLandscapeLibraryKeepsTheChips() { + showLibrary(width = 740) + compose.onNodeWithTag("tab-menu").assertDoesNotExist() + compose.onNodeWithTag("library-source-epic").assertIsDisplayed() + } + + @Test @Config(qualifiers = "w900dp-h500dp-land") + fun narrowLibraryPaneUsesTheMenuEvenInLandscape() { + showLibrary(width = 270) + compose.onNodeWithTag("tab-menu").assertIsDisplayed() + } + + @Test fun portraitStoreUsesTheMenuEvenWithOnlyTwoVisibleStores() { + compose.setContent { + DroidDeckTheme { + var selected by remember { mutableStateOf(Store.EPIC.id) } + StoreChips( + selected, null, listOf(StoreTab(Store.EPIC, true), StoreTab(Store.GOG, true), StoreTab(Store.EA, false)), + onStore = { selected = it.id }, onSettings = {}, onFocusChip = {}, + ) + } + } + val menu = compose.onNodeWithTag("tab-menu") + menu.assert(hasText(Store.EPIC.shortLabel)).performClick() + compose.onNodeWithTag("tab-menu:2").assertDoesNotExist() + compose.onNodeWithTag("tab-menu:1").assertIsDisplayed().performClick() + menu.assert(hasText(Store.GOG.shortLabel)) + } +} From 10d3b801fabc0d605f1e6cb0f9bad01f61887b3b Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:57:43 +0800 Subject: [PATCH 32/80] Run original Xbox games from the Xbox store (#3638) Original Xbox games sold for PC through the Xbox store (Xbox360BackwardCompatibil.* packages: Fuzion Frenzy, BLiNX, Conker, Crimson Skies, Grabbed by the Ghoulies, Morrowind, Red Faction II, ...) now start and play on DroidDeck-Bionic. - droiddeck-xbox: keep the GameInput redistributable, remove its service class; run install actions with FEX's safe settings; find MicrosoftGame.config in any case and skip one that does not parse. - droiddeck-game-env: fix rule for these games turns on the emulator fixes in the Wine, FEX and VKD3D-Proton builds made for them. - Components: each installed game gets the Xbox FEX, VKD3D-Proton and DXVK builds, never over a player's choice (also not one made during the download). - Xbox store: these games show the size of their console package. - DroidDeck-Bionic launch.sh keeps the Wine and VKD3D-Proton switches; bionic pack uses the v18 layer with the fixes (released as DroidDeck-Bionic 14.1 r104). - Xbox backend: purchases that name a legacy marketplace offer reach the library. --- .../launcher/session/ComponentsManager.kt | 29 ++++++- .../launcher/session/SessionPrefs.kt | 3 + .../launcher/session/SessionService.kt | 3 + .../session/XboxBackCompatComponents.kt | 78 +++++++++++++++++++ .../launcher/stores/xbox/XboxCatalog.kt | 13 +++- .../launcher/stores/xbox/XboxManifest.kt | 4 + .../session/ComponentsBionicFexTest.kt | 10 +++ .../session/XboxBackCompatAssignTest.kt | 71 +++++++++++++++++ .../session/XboxBackCompatComponentsTest.kt | 33 ++++++++ .../launcher/stores/xbox/XboxCatalogTest.kt | 16 ++++ tools/bionic-runtime/build.sh | 8 +- tools/bionic-runtime/tool/launch.sh | 3 + .../overlay/usr/local/bin/droiddeck-game-env | 58 +++++++++++++- .../overlay/usr/local/bin/droiddeck-xbox | 71 ++++++++++++++++- tools/tests/test_bionic_paths.py | 13 ++++ tools/tests/test_game_environment.py | 42 ++++++++++ tools/tests/test_xbox_launch.py | 66 ++++++++++++++++ tools/xbox/README.md | 6 ++ .../xbox/droiddeck-legacy-offer-parent.patch | 45 +++++++++++ tools/xbox/prepare.py | 2 +- 20 files changed, 564 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt create mode 100644 tools/xbox/droiddeck-legacy-offer-parent.patch diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt index 146509bba7..b9be461b01 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt @@ -30,6 +30,8 @@ object ComponentsManager { private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components" internal const val DD_NIGHTLY = "linux-nightly" internal const val DD_BIONIC = "bionic-stable" + /** FEX for original Xbox games on DroidDeck-Bionic: kept apart from [DD_BIONIC] so automatic FEX updates never pick it. */ + internal const val DD_XBOX = "bionic-xbox" private val RELEASES = linkedMapOf( "FexCore-Linux" to "fex", "Dxvk-Linux" to "dxvk", @@ -38,7 +40,8 @@ object ComponentsManager { "Vkd3d-proton-Linux" to "vkd3d", ) private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex") - private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) + private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC) + + (DD_COMPONENTS to DD_XBOX) private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS) private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d") private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux") @@ -253,6 +256,28 @@ object ComponentsManager { saveState(context, state) } + internal enum class Assigned { SET, NOT_LISTED, CHANGED } + + /** + * Sets a game's component to a listed package, fetching it first when it is not stored. [expected] is the component + * the caller read when it decided: if the game's component is something else once the package is ready (the player + * chose one during the download), nothing is written. [onSet] runs under the same lock as the write. + */ + internal fun assignGameComponent(context: Context, scope: String, comp: String, file: String, release: String, + expected: String?, onSet: () -> Unit = {}): Assigned { + val wcp = File(packagesDir(context), safeName(file)) + if (!wcp.isFile || runCatching { packageInfo(context, wcp) }.isFailure) { + wcp.delete() + download(context, catalogItem(context, file, release) ?: return Assigned.NOT_LISTED) {} + } + synchronized(lock) { + if (gameComponents(context, scope)[comp] != expected) return Assigned.CHANGED + setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) } + onSet() + } + return Assigned.SET + } + fun clearGameComponents(context: Context, scope: String) = synchronized(lock) { require(GameEnvironment.validScope(scope)) val state = loadState(context) @@ -1124,7 +1149,7 @@ object ComponentsManager { internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) { DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value - DD_BIONIC -> "fex" + DD_BIONIC, DD_XBOX -> "fex" else -> null } 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 38fca4ec19..a050da5789 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1778,6 +1778,9 @@ object SessionPrefs { name.removeSuffix(from) + to to moved } + fun storedAddedGameAppId(context: Context, folderPath: String): Long? = + prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L } + fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) { val p = prefs(context) p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L } 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 16b9fd84e7..88a92efe1b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -617,6 +617,9 @@ class SessionService : Service() { val size = SessionState.outputSize val guest = ArrayList() val steamHere = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP + runCatching { SessionEvents.step("components-xbox") { XboxBackCompatComponents.ensure(this) } } + .onSuccess { if (it != null) Log.i(TAG, it) } + .onFailure { Log.w(TAG, "original Xbox components", it) } runCatching { SessionEvents.step("components-republish") { ComponentsManager.republish(this) } } .onSuccess { if (it) Log.i(TAG, "component selections published for the installed Proton builds") } .onFailure { Log.w(TAG, "component selections", it) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt b/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt new file mode 100644 index 0000000000..e547cd8963 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/XboxBackCompatComponents.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.gpu.GpuInfo +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstallRoot +import com.droiddeck.launcher.stores.xbox.XboxManifest + +/** + * Microsoft's original Xbox releases for PC run its emulator, which needs FEX and VKD3D-Proton builds with fixes of + * their own (each off unless droiddeck-game-env turns it on for these games) and a newer DXVK than some Protons carry. + * Each installed one gets them as its game components. A component the player chose for the game is never replaced; + * one set here follows this list, so a newer build replaces it, and one the player cleared stays cleared. + */ +internal object XboxBackCompatComponents { + private const val TAG = "XboxBackCompat" + private const val PREFS = "xbox-backcompat-components" + + internal data class Wanted(val comp: String, val file: String, val release: String) + + internal fun wanted(family: GpuInfo.Family?): List = listOf( + Wanted("fex", "FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX), + Wanted("vkd3d", "vkd3d-proton-arm64ec-3.1-xbox-linux.wcp", "Vkd3d-proton-Linux"), + Wanted("dxvk", if (family == GpuInfo.Family.A6XX) "dxvk-gplasync-3.2-a6xx-1-linux.wcp" else "dxvk-gplasync-3.2-1-linux.wcp", + "Dxvk-gplasync-Linux"), + ) + + /** The file to set for one component of a game, or null to leave it as it is. */ + internal fun decide(current: String?, assigned: String?, wanted: String): String? = when { + current == null && assigned == null -> wanted + current != null && current == assigned && current != wanted -> wanted + else -> null + } + + internal class Game(val scope: String, val title: String) + + internal fun installed(context: Context): List = StoreInstallRoot.gameFolders(context).mapNotNull { folder -> + val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.store == Store.XBOX && it.isInstalled } ?: return@mapNotNull null + if (!XboxManifest.backCompat(folder)) return@mapNotNull null + val appId = SessionPrefs.storedAddedGameAppId(context, folder.path) ?: return@mapNotNull null + Game(appId.toString(), sidecar.title) + } + + fun ensure(context: Context): String? { + val games = installed(context) + if (games.isEmpty()) return null + val marks = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val wanted = wanted(runCatching { GpuInfo.detect().family }.getOrNull()) + val lines = mutableListOf() + for (game in games) { + val current = ComponentsManager.gameComponents(context, game.scope) + for (w in wanted) { + val key = "${game.scope}/${w.comp}" + val file = decide(current[w.comp], marks.getString(key, null), w.file) ?: continue + val label = ComponentsManager.LABEL[w.comp] + runCatching { + ComponentsManager.assignGameComponent(context, game.scope, w.comp, file, w.release, expected = current[w.comp]) { + marks.edit().putString(key, file).apply() + } + } + .onSuccess { result -> + lines += when (result) { + ComponentsManager.Assigned.SET -> "${game.title}: $label ${file.removeSuffix(".wcp")}" + ComponentsManager.Assigned.NOT_LISTED -> "${game.title}: $file is not listed; $label unchanged" + ComponentsManager.Assigned.CHANGED -> "${game.title}: $label was chosen during the download; kept" + } + } + .onFailure { e -> + Log.w(TAG, "${game.title}: $file", e) + lines += "${game.title}: $label unchanged (${e.message ?: e.javaClass.simpleName})" + } + } + } + return lines.joinToString("; ").ifEmpty { null } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt index 7afcaeb321..405b0b955d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt @@ -8,6 +8,9 @@ import org.json.JSONObject import java.time.Instant internal object XboxCatalog { + /** Package identity prefix of Microsoft's original Xbox releases for PC. */ + internal const val BACK_COMPAT_IDENTITY = "Xbox360BackwardCompatibil" + private val productId = Regex("[A-Z0-9]{12}") private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD") private val pcPlans = mapOf( @@ -148,6 +151,13 @@ internal object XboxCatalog { .flatMap { objects(it.optJSONArray("Packages")) } val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } } val installable = pc.any { installableFormat(it.optString("PackageFormat")) } + // An original Xbox game: its PC package is only Microsoft's emulator and an + // index; the game data comes from the console package, so that is its size. + val backCompat = pc.any { it.optString("PackageFamilyName").startsWith(BACK_COMPAT_IDENTITY, ignoreCase = true) } + val console = packages.filter { pkg -> + pkg.optString("PackageFormat").equals("XVC", true) || + objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Xbox" } + } // The installer needs the format, not just the fact that one exists: a // legacy container takes a different subcommand from a streamed package. val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty() @@ -172,7 +182,8 @@ internal object XboxCatalog { storeUrl = "https://www.xbox.com/games/store/$id", publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"), description = localized.optString("ProductDescription"), - sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L, + sizeBytes = if (!installable) 0L else (if (backCompat) console.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } else null) + ?.takeIf { it > 0 } ?: pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L, extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams), "format" to format), ) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index 1f6cb7851d..1c88e48655 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -80,6 +80,10 @@ internal object XboxManifest { dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty()) } + /** Microsoft's original Xbox releases for PC, which run its emulator. */ + fun backCompat(folder: File): Boolean = + runCatching { read(folder).name.startsWith(XboxCatalog.BACK_COMPAT_IDENTITY, ignoreCase = true) }.getOrDefault(false) + /** * A full trust package starts its executable directly. Anything else is activated * through the Windows app model, which this runtime has no host for, so starting diff --git a/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt index 99bd6ef90e..d0e3c22361 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ComponentsBionicFexTest.kt @@ -77,6 +77,16 @@ class ComponentsBionicFexTest { assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp")) } + @Test fun originalXboxFexIsListedButNeverAnAutomaticUpdate() { + assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_XBOX, "FEXCore-2611.1-xbox-bionic.wcp")) + fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1L, "sha256:00") + val items = listOf(item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC), + item("FEXCore-2611.1-xbox-bionic.wcp", ComponentsManager.DD_XBOX), item("FEXCore-2611.1-PPA-bionic.wcp", ComponentsManager.DD_BIONIC)) + val line = ComponentUpdates.fexLine(proton(bionicTool)) + assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(items, line, emptySet())?.file) + assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-xbox-bionic.wcp")) + } + @Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() { val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp"))) assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool)))) diff --git a/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt new file mode 100644 index 0000000000..cc6b4c2d07 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatAssignTest.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.github.luben.zstd.ZstdOutputStream +import org.apache.commons.compress.archivers.tar.TarArchiveEntry +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.BufferedOutputStream +import java.io.File +import java.io.FileOutputStream + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class XboxBackCompatAssignTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + File(context.filesDir, "components").deleteRecursively() + LinuxRuntime.rootDir(context).deleteRecursively() + ComponentsManager.importPackage(context, wcp("a.src", "A"), "dxvk-a.wcp") + ComponentsManager.importPackage(context, wcp("b.src", "B"), "dxvk-b.wcp") + } + + @Test fun aChoiceMadeDuringTheDownloadIsKept() { + ComponentsManager.setGameComponent(context, "10", "dxvk", "dxvk-b.wcp") + var marked = false + val result = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-a.wcp", "unused", expected = null) { marked = true } + assertEquals(ComponentsManager.Assigned.CHANGED, result) + assertEquals("dxvk-b.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + assertFalse(marked) + } + + @Test fun anUnchangedComponentIsSetAndMarked() { + var marked = false + val result = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-a.wcp", "unused", expected = null) { marked = true } + assertEquals(ComponentsManager.Assigned.SET, result) + assertEquals("dxvk-a.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + assertTrue(marked) + val newer = ComponentsManager.assignGameComponent(context, "10", "dxvk", "dxvk-b.wcp", "unused", expected = "dxvk-a.wcp") + assertEquals(ComponentsManager.Assigned.SET, newer) + assertEquals("dxvk-b.wcp", ComponentsManager.gameComponents(context, "10")["dxvk"]) + } + + private fun wcp(fileName: String, version: String): File { + val out = File(context.cacheDir, fileName) + val profile = JSONObject().put("type", "DXVK-Linux").put("versionName", version).put("description", "DXVK $version") + .toString().toByteArray(Charsets.UTF_8) + val dll = "dxvk-dll-$version".toByteArray(Charsets.UTF_8) + TarArchiveOutputStream(ZstdOutputStream(BufferedOutputStream(FileOutputStream(out)))).use { tar -> + tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX) + tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() }) + tar.write(profile) + tar.closeArchiveEntry() + tar.putArchiveEntry(TarArchiveEntry("files/lib/wine/dxvk/aarch64-windows/d3d11.dll").apply { size = dll.size.toLong() }) + tar.write(dll) + tar.closeArchiveEntry() + } + return out + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt new file mode 100644 index 0000000000..b52a2cc085 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/XboxBackCompatComponentsTest.kt @@ -0,0 +1,33 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.gpu.GpuInfo +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class XboxBackCompatComponentsTest { + private val fex = "FEXCore-2611.1-xbox-bionic.wcp" + + @Test fun aComponentIsSetOnceAndNeverOverAPlayersChoice() { + assertEquals(fex, XboxBackCompatComponents.decide(current = null, assigned = null, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = "FEXCore-2611.1-bionic.wcp", assigned = null, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = null, assigned = fex, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = fex, assigned = fex, wanted = fex)) + assertNull(XboxBackCompatComponents.decide(current = "DD-FEXCore-2611+76-nightly.wcp", assigned = fex, wanted = "FEXCore-2612-xbox-bionic.wcp")) + } + + @Test fun aComponentSetHereFollowsANewerBuild() { + assertEquals("FEXCore-2612-xbox-bionic.wcp", XboxBackCompatComponents.decide(current = fex, assigned = fex, wanted = "FEXCore-2612-xbox-bionic.wcp")) + } + + @Test fun eachComponentComesFromTheReleaseThatListsIt() { + val wanted = XboxBackCompatComponents.wanted(GpuInfo.Family.A7XX) + assertEquals(listOf("fex", "vkd3d", "dxvk"), wanted.map { it.comp }) + assertEquals(ComponentsManager.DD_XBOX, wanted[0].release) + assertEquals("vkd3d-proton-arm64ec-3.1-xbox-linux.wcp" to "Vkd3d-proton-Linux", wanted[1].file to wanted[1].release) + assertEquals("dxvk-gplasync-3.2-1-linux.wcp" to "Dxvk-gplasync-Linux", wanted[2].file to wanted[2].release) + for (w in wanted) assertEquals(w.comp, ComponentsManager.assetComp(w.release, w.file)) + assertEquals("dxvk-gplasync-3.2-a6xx-1-linux.wcp", XboxBackCompatComponents.wanted(GpuInfo.Family.A6XX)[2].file) + assertEquals("dxvk-gplasync-3.2-1-linux.wcp", XboxBackCompatComponents.wanted(null)[2].file) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt index 810c2f8642..fcb2e77286 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt @@ -201,6 +201,22 @@ class XboxCatalogTest { assertTrue(retail.xboxPc); assertEquals("EAPPX", retail.extra["format"]); assertEquals(7L, retail.sizeBytes) } + @Test fun anOriginalXboxGameShowsTheSizeOfItsConsolePackage() { + fun pkg(family: String?, format: String, platform: String, size: Long) = JSONObject().put("PackageFormat", format) + .put("MaxDownloadSizeInBytes", size).apply { if (family != null) put("PackageFamilyName", family) } + .put("PlatformDependencies", JSONArray().put(JSONObject().put("PlatformName", platform))) + fun offer(vararg packages: JSONObject) = JSONObject().put("ProductId", game).put("ProductType", "Game") + .put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "Fuzion Frenzy"))) + .put("DisplaySkuAvailabilities", JSONArray().put(JSONObject().put("Sku", JSONObject().put("Properties", + JSONObject().put("Packages", JSONArray(packages.toList())))))) + val console = pkg(null, "XVC", "Windows.Xbox", 2_670_796_800L) + val emulator = pkg("Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio_ksqcvrsvwz2jp", "MSIXVC", "Windows.Desktop", 753_313L) + assertEquals(2_670_796_800L, XboxCatalog.product(offer(console, emulator), mapOf(game to "gamepass"))!!.sizeBytes) + assertEquals(753_313L, XboxCatalog.product(offer(emulator), mapOf(game to "gamepass"))!!.sizeBytes) + val native = pkg("Microsoft.SomeGame_8wekyb3d8bbwe", "MSIXVC", "Windows.Desktop", 40_000_000L) + assertEquals(40_000_000L, XboxCatalog.product(offer(console, native), mapOf(game to "owned"))!!.sizeBytes) + } + @Test fun aCloudOnlyEditionFoldsIntoThePcCardWithTheSameTitle() { val cloud = XboxCloudCatalog(gamePass = setOf(parent), all = emptySet()) val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!! diff --git a/tools/bionic-runtime/build.sh b/tools/bionic-runtime/build.sh index 91314db4fd..11f496d62e 100755 --- a/tools/bionic-runtime/build.sh +++ b/tools/bionic-runtime/build.sh @@ -36,9 +36,11 @@ GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-im VULKAN_HEADERS_TAG=v1.4.341 # The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed. # Layer v18: DroidDeck-Proton 11-14.1 (Valve Wine a47c73f52fd7, as GE-Proton11-14), the build Bannerlator ships; it -# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). -LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261124-v18/DroidDeck-proton-11.0-14.1-arm64ec.wcp -LAYER_SHA256=bf94176180e96584185835f9e80b168666f9fa752aa9583cfedb8fe493134ff6 # proton-wine 1a5735e7 (run 45926928349) +# carries the ARM64EC code-map and unwind fixes the 12.8 layer had (5ebfaa6f, 2515a989, e88fab40). This build adds the +# original Xbox fixes on top of v18 (special APC delivery, boot video aperture, 0 timer resolution: each off unless +# droiddeck-game-env sets its variable; FileAllocationInfo, MFCreateWaveFormatEx NULL size). +LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261203-ogxbox/DroidDeck-proton-11.0-14.1-arm64ec.wcp +LAYER_SHA256=a779747c880c64bacc0171cf26822f3398eaf32f0b214bca3448a95bf4127a90 # proton-wine ee646200 (run 47122517177) LAYER_VERSION=14.1 # Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default # DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later). diff --git a/tools/bionic-runtime/tool/launch.sh b/tools/bionic-runtime/tool/launch.sh index b3b9bd25c1..be9cc347b7 100644 --- a/tools/bionic-runtime/tool/launch.sh +++ b/tools/bionic-runtime/tool/launch.sh @@ -52,6 +52,9 @@ for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;; DROIDDECK_GUEST_ROOT) ;; VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;; + # droiddeck-game-env's original Xbox switches for this layer's Wine and the Xbox VKD3D-Proton build + WINE_SPECIAL_APC_INTERRUPT|WINE_MF_DISPLAY_APERTURE|WINE_PRECISE_SLEEP) ;; + VKD3D_INTEROP_PRESENT|VKD3D_PACKED_422|VKD3D_PACKED_422_SWIZZLE) ;; # The exec handoff (../handoff.c): the app's spawn socket and list (the app starts a handed-off program from the # glibc root's shell, so its path too), and what a worker hands the program it runs (this script, when it runs # in one): the first Wine process's hook knows the worker's binder fds are not its own. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 4e56c7b17c..04992da01b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -13,6 +13,7 @@ import subprocess import sys import tempfile from pathlib import Path +import xml.etree.ElementTree as ElementTree GAME_PREFIX = "DROIDDECK_GAME_" GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE") @@ -67,6 +68,29 @@ DOTNET_FEX = { "FEX_X87REDUCEDPRECISION": "0", } STABILITY_FEX = dict(DOTNET_FEX, FEX_MULTIBLOCK="0") +# Microsoft's original Xbox releases for PC run its emulator (Emu.exe). The switches turn on fixes in the builds of +# DroidDeck-Bionic's Wine, FEX and VKD3D-Proton made for it, each off by default: Wine delivers the Windows 11 special +# APCs the emulator interrupts its CPU threads with; FEX keeps the x87 state across those interrupts, checks for one in +# a loop that branches back into its own block, and maps an image without a lock order that deadlocks; Wine gives the +# boot video's types a display aperture and reports a 0 timer resolution (DXVK's vblank wait otherwise spins a core); +# VKD3D-Proton presents frames DXVK drew through D3D11On12 and maps the packed 4:2:2 video formats. FEX keeps +# DOTNET_FEX (the emulator's menu is .NET) without vector and memcpy TSO and with reduced x87 precision: on an +# Adreno 750 the emulator's menus ran at ~58 fps instead of ~35. +XBOX_BACK_COMPAT_IDENTITY = "xbox360backwardcompatibil" +XBOX_BACK_COMPAT_ENV = dict( + DOTNET_FEX, + FEX_VECTORTSOENABLED="0", + FEX_MEMCPYSETTSOENABLED="0", + FEX_X87REDUCEDPRECISION="1", + WINE_SPECIAL_APC_INTERRUPT="1", + FEX_SYNCX87CONTEXT="1", + FEX_LOOPSUSPENDCHECK="1", + FEX_SAFEIMAGEMAP="1", + WINE_MF_DISPLAY_APERTURE="1", + WINE_PRECISE_SLEEP="1", + VKD3D_INTEROP_PRESENT="1", + VKD3D_PACKED_422="1", +) # Setup loader offset-table IDs, as innoextract's known_setup_loader_versions lists them. Loaders # from 5.1.5 keep the table in a resource; older ones also put "Inno" at file offset 0x30. INNO_LOADER_IDS = (b"rDlPtS", b"nS5W7dT\x83\xaa\x1b\x0fj") @@ -149,6 +173,31 @@ def game_files(exe): return names +def xbox_identity(exe): + """The identity name in the MicrosoftGame.config of the Xbox package the executable is in, or "".""" + folder = os.path.dirname(exe) + for _ in range(4): + # The Xbox store accepts the file name in any case (XboxManifest.read). + name = "MicrosoftGame.config" + if not os.path.isfile(os.path.join(folder, name)): + try: + name = next((entry for entry in sorted(os.listdir(folder)) if entry.lower() == "microsoftgame.config"), name) + except OSError: + pass + try: + with open(os.path.join(folder, name), "rb") as source: + root = ElementTree.fromstring(source.read(1 << 20)) + except (OSError, ElementTree.ParseError): + root = None + if root is not None: + return next((node.get("Name", "") for node in root.iter() if node.tag.rsplit("}", 1)[-1] == "Identity"), "") + parent = os.path.dirname(folder) + if parent == folder: + break + folder = parent + return "" + + class Game: def __init__(self, exe, args, app_id=""): @@ -158,6 +207,7 @@ class Game: self.app_id = app_id self.stem = os.path.splitext(os.path.basename(exe))[0].lower() self.files = game_files(exe) + self.xbox_back_compat = os.path.isabs(exe) and xbox_identity(exe).lower().startswith(XBOX_BACK_COMPAT_IDENTITY) def has_arg(self, name): return any(a == name or a.startswith(name + "=") for a in self.args) @@ -177,10 +227,16 @@ def is_godot(game): @fix def dotnet_memory_ordering(game): - if "coreclr.dll" in game.files: + if "coreclr.dll" in game.files and not game.xbox_back_compat: return DOTNET_FEX, [], ".NET runtime: FEX with full TSO" +@fix +def xbox_back_compat(game): + if game.xbox_back_compat: + return XBOX_BACK_COMPAT_ENV, [], "Original Xbox game: emulator fixes on, FEX with load/store TSO and reduced x87 precision" + + @fix def unity_memory_ordering(game): if {"unityplayer.so", "gameassembly.so", "unityplayer.dll"} & game.files: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox index 143aa07c27..231dba2f0c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox @@ -28,6 +28,19 @@ CLASSES = { 'Windows.Storage.Streams.DataWriter'), } CLASS_KEY = 'Software\\Microsoft\\WindowsRuntime\\ActivatableClassId\\' +# Microsoft's original Xbox releases for PC install GameInputRedist.msi. The emulator needs the GameInput it installs +# (Wine's builtin one lacks the interface it asks for), but through the GameInputService class it registers that +# GameInput starts a service needing Windows notification calls Wine lacks, and the emulator then stops with "Gaming +# Services must be installed". Without the class it runs the redistributable's GameInput in process. +BACK_COMPAT_IDENTITY = 'xbox360backwardcompatibil' +# droiddeck-game-env gives these games the emulator's switches and faster FEX settings. Their install actions run +# without the switches and with FEX's full memory ordering and x87 precision: under the faster settings +# GameInputRedist.msi's 32-bit msiexec spun a core and never finished. +EMULATOR_SWITCHES = ('WINE_SPECIAL_APC_INTERRUPT', 'WINE_MF_DISPLAY_APERTURE', 'WINE_PRECISE_SLEEP', 'FEX_SYNCX87CONTEXT', + 'FEX_LOOPSUSPENDCHECK', 'FEX_SAFEIMAGEMAP', 'VKD3D_INTEROP_PRESENT', 'VKD3D_PACKED_422') +INSTALLER_FEX = {'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1', + 'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'} +GAMEINPUT_SERVICE = 'Software\\Classes\\CLSID\\{B773D0F8-01F8-41E7-9F23-6871DA0AACFF}' VIEW_DRIVES = 'xwvutsrqponmlkjihgfe' @@ -145,8 +158,21 @@ def game_config(exe): return None for folder in list(path.parents)[:4]: config = folder / 'MicrosoftGame.config' - if config.is_file(): - return config + if not config.is_file(): + # The Xbox store accepts the file name in any case (XboxManifest.read). + try: + config = next((entry for entry in sorted(folder.iterdir()) + if entry.name.lower() == 'microsoftgame.config' and entry.is_file()), None) + except OSError: + config = None + if config is None: + continue + # As in droiddeck-game-env, a manifest that does not parse gives way to one in a parent folder. + try: + ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + continue + return config return None @@ -186,6 +212,40 @@ def windows_arguments(text): return arguments +def back_compat(config): + try: + root = ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + return False + return any(node.tag.rsplit('}', 1)[-1] == 'Identity' and node.get('Name', '').lower().startswith(BACK_COMPAT_IDENTITY) + for node in root.iter()) + + +def remove_gameinput_service(proton, prefix, env, installed=False): + # Just after an install action Wine may not have written system.reg yet; reg.exe sees its registry either way. + if not installed: + try: + registry = (prefix / 'system.reg').read_text(encoding='utf-8', errors='replace') + except OSError: + return + if '[%s]' % GAMEINPUT_SERVICE.replace('\\', '\\\\').lower() not in registry.lower(): + return + try: + code = subprocess.run([proton, 'run', 'reg.exe', 'delete', 'HKLM\\' + GAMEINPUT_SERVICE, '/f'], + stdout=sys.stderr, env=env, timeout=90).returncode + except subprocess.TimeoutExpired: + print('droiddeck-xbox: GameInput service class could not be removed (reg.exe timed out); launching with it', + file=sys.stderr) + return + except OSError as e: + print('droiddeck-xbox: GameInput service class could not be removed (%s); launching with it' % (e.strerror or e), + file=sys.stderr) + return + # reg.exe fails when the key is absent, which after an install action only means the action registered no class. + if code != 0 and not installed: + print('droiddeck-xbox: GameInput service class could not be removed; launching with it', file=sys.stderr) + + def install_actions(config): try: root = ElementTree.fromstring(config.read_bytes()) @@ -218,6 +278,10 @@ def run_install_actions(proton, prefix, exe, env): if config is None: return done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions' + original_xbox = back_compat(config) + if original_xbox: + env = dict({k: v for k, v in env.items() if k not in EMULATOR_SWITCHES}, **INSTALLER_FEX) + installed = False for name, target, arguments in install_actions(config): try: content = hashlib.sha256() @@ -243,11 +307,14 @@ def run_install_actions(proton, prefix, exe, env): if code != 0: print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr) continue + installed = True try: done.mkdir(parents=True, exist_ok=True) marker.touch() except OSError as error: print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr) + if original_xbox: + remove_gameinput_service(proton, prefix, env, installed) def view_drive(prefix, exe): diff --git a/tools/tests/test_bionic_paths.py b/tools/tests/test_bionic_paths.py index 55c371b303..e4931b48ae 100644 --- a/tools/tests/test_bionic_paths.py +++ b/tools/tests/test_bionic_paths.py @@ -2,6 +2,7 @@ import importlib.machinery import importlib.util import os import re +import runpy import shutil import subprocess import tempfile @@ -74,6 +75,18 @@ class ToolArguments(unittest.TestCase): self.assertEqual(['BANNER_AUDIO_DIRECT_MIC=1', 'BANNER_AUDIO_DIRECT_MS=60'], result.stdout.split()) + def test_original_xbox_switches_reach_wine(self): + game_env = runpy.run_path(str(BIN / 'droiddeck-game-env')) + switches = dict(game_env['XBOX_BACK_COMPAT_ENV'], VKD3D_PACKED_422_SWIZZLE='rbg1') + text = LAUNCH.read_text() + block = text[text.index('KEEP="'):text.index('export PATH=/system/bin')] + env = dict(switches, PATH=os.environ['PATH'], DROIDDECK_BIONIC_KEEP='PATH', OTHER='x') + result = subprocess.run(['sh', '-c', block + 'env\n'], env=env, text=True, capture_output=True, check=True) + kept = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line) + self.assertEqual(switches, {name: kept.get(name) for name in switches}) + self.assertNotIn('OTHER', kept) + + class SessionLogs(unittest.TestCase): SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam' diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index b927d18694..55cf9d29da 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -1592,6 +1592,48 @@ class GameEnvironmentTest(unittest.TestCase): (other / "Other.exe").touch() self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], [])) + def test_original_xbox_games_get_the_emulator_fixes_instead_of_the_dotnet_preset(self): + expected = {"FEX_TSOENABLED": "1", "FEX_VECTORTSOENABLED": "0", "FEX_MEMCPYSETTSOENABLED": "0", + "FEX_HALFBARRIERTSOENABLED": "1", "FEX_X87REDUCEDPRECISION": "1", "WINE_SPECIAL_APC_INTERRUPT": "1", + "FEX_SYNCX87CONTEXT": "1", "FEX_LOOPSUSPENDCHECK": "1", "FEX_SAFEIMAGEMAP": "1", + "WINE_MF_DISPLAY_APERTURE": "1", "WINE_PRECISE_SLEEP": "1", "VKD3D_INTEROP_PRESENT": "1", + "VKD3D_PACKED_422": "1"} + + def package(folder, identity): + (folder / "EmuMenu").mkdir(parents=True) + for name in ("Emu.exe", "EmuMenu/EmuMenu.exe", "EmuMenu/coreclr.dll"): + (folder / name).touch() + (folder / "MicrosoftGame.config").write_text( + '' + '' % identity) + + with tempfile.TemporaryDirectory() as tmp: + game = Path(tmp) / "Fuzion Frenzy" + package(game, "Xbox360BackwardCompatibil.PrimaryFuzionFrenzyFuzio") + for exe in (game / "Emu.exe", game / "EmuMenu/EmuMenu.exe"): + env, extra, notes = MODULE["engine_fixes"](str(exe), [], "2773102903") + self.assertEqual((env, extra), (expected, [])) + self.assertEqual(len(notes), 1) + self.assertTrue(notes[0].startswith("Original Xbox game")) + config = {"version": 1, "games": {"2773102903": {"FEX_X87REDUCEDPRECISION": "0", "VKD3D_PACKED_422": None}}} + result = MODULE["apply_config"]({}, config, "2773102903", env) + self.assertEqual(result["FEX_X87REDUCEDPRECISION"], "0") + self.assertNotIn("VKD3D_PACKED_422", result) + self.assertEqual(result["WINE_SPECIAL_APC_INTERRUPT"], "1") + store = Path(tmp) / "Psychonauts" + package(store, "Microsoft.PsychonautsforWindows10") + env, extra, notes = MODULE["engine_fixes"](str(store / "Emu.exe"), []) + self.assertEqual(env, MODULE["DOTNET_FEX"]) + self.assertEqual(notes, [".NET runtime: FEX with full TSO"]) + (store / "MicrosoftGame.config").write_text("Installers' + '' + '') + (game / 'MicrosoftGame.config').write_text( + '' + '%s' % actions) + # A fresh prefix: the redistributable installs, and its class goes even before Wine writes system.reg. + (prefix / 'system.reg').write_text('WINE REGISTRY Version 2\n') + # The installers run without the emulator's switches and with FEX's full ordering and precision. + game_env = {'A': '1', 'WINE_SPECIAL_APC_INTERRUPT': '1', 'VKD3D_PACKED_422': '1', 'FEX_LOOPSUSPENDCHECK': '1', + 'FEX_VECTORTSOENABLED': '0', 'FEX_X87REDUCEDPRECISION': '1'} + installer_env = {'A': '1', 'FEX_TSOENABLED': '1', 'FEX_VECTORTSOENABLED': '1', 'FEX_MEMCPYSETTSOENABLED': '1', + 'FEX_HALFBARRIERTSOENABLED': '1', 'FEX_X87REDUCEDPRECISION': '0'} + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), game_env) + self.assertEqual([call.args[0][:3] for call in child.call_args_list], + [['/p', 'run', 'msiexec'], ['/p', 'run', 'msiexec'], ['/p', 'run', 'reg.exe']]) + self.assertTrue(child.call_args_list[0].args[0][4].endswith('GameInputRedist.msi')) + self.assertEqual(child.call_args_list[2].args[0][3:], delete) + self.assertEqual([call.kwargs['env'] for call in child.call_args_list], [installer_env] * 3) + self.assertEqual(game_env['FEX_X87REDUCEDPRECISION'], '1') + # After the install action: a key reg.exe does not find stays quiet, a reg.exe that never answers is reported. + for outcome, reported in (({'return_value': subprocess.CompletedProcess([], 1)}, False), + ({'side_effect': subprocess.TimeoutExpired('reg.exe', 90)}, True), + ({'side_effect': FileNotFoundError(2, 'No such file or directory')}, True)): + with patch('subprocess.run', **outcome), patch('sys.stderr', new_callable=io.StringIO) as err: + xbox['remove_gameinput_service']('/p', prefix, {}, installed=True) + self.assertEqual('could not be removed' in err.getvalue(), reported, outcome) + # Installed earlier and the class is gone: nothing runs. + with patch('subprocess.run') as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + child.assert_not_called() + # A prefix where the redistributable ran before: only the class is removed. + (prefix / 'system.reg').write_text('WINE REGISTRY Version 2\n\n' + key + '@="GameInputService"\n\n') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + self.assertEqual([call.args[0][2:] for call in child.call_args_list], [['reg.exe'] + delete]) + with patch('subprocess.run', side_effect=subprocess.TimeoutExpired('reg.exe', 90)), \ + patch('sys.stderr', new_callable=io.StringIO) as err: + xbox['run_install_actions']('/p', prefix, str(game / 'Emu.exe'), {}) + self.assertIn('could not be removed', err.getvalue()) + # Other packages keep the class. + (game / 'MicrosoftGame.config').write_text( + '%s' % actions) + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix / 'other', str(game / 'Emu.exe'), {'FEX_X87REDUCEDPRECISION': '1'}) + self.assertEqual([call.args[0][2] for call in child.call_args_list], ['msiexec', 'msiexec']) + self.assertEqual(child.call_args.kwargs['env'], {'FEX_X87REDUCEDPRECISION': '1'}) def test_a_failed_install_action_is_retried_on_the_next_launch(self): with tempfile.TemporaryDirectory() as root: diff --git a/tools/xbox/README.md b/tools/xbox/README.md index c0a6636aba..2411b7a777 100644 --- a/tools/xbox/README.md +++ b/tools/xbox/README.md @@ -125,6 +125,12 @@ download plus two copies of the largest container, and each container is deleted The download has no control channel: cancelling kills it and the next attempt starts that container from zero. +`droiddeck-legacy-offer-parent.patch` keeps an entitlement whose `satisfiedByProductId` is a GUID. +A purchased original Xbox or Xbox 360 title names its marketplace offer there (Red Faction II did), +not a Store product, so it is not a subscription plan; the backend dropped the whole row as malformed +and the game never reached the library. The row keeps its own status, trial, sharing and expiry +checks, and any other parent that is not a product id is still rejected. + `droiddeck-msixvc2.patch` installs MSIXVC2 packages, the format Xbox 360 backward-compatible titles ship in. The package Windows Update serves is only an index (`XboxPackage.cbor`, chunk and file tables); the files are encrypted, Brotli-compressed segments inside `.box` blobs on the Xbox diff --git a/tools/xbox/droiddeck-legacy-offer-parent.patch b/tools/xbox/droiddeck-legacy-offer-parent.patch new file mode 100644 index 0000000000..3efd79c277 --- /dev/null +++ b/tools/xbox/droiddeck-legacy-offer-parent.patch @@ -0,0 +1,45 @@ +diff --git a/crates/xodus-cli/src/commands/library.rs b/crates/xodus-cli/src/commands/library.rs +index 36191bf..43bf718 100644 +--- a/crates/xodus-cli/src/commands/library.rs ++++ b/crates/xodus-cli/src/commands/library.rs +@@ -11,6 +11,10 @@ fn product_id(id: &str) -> bool { + .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()) + } + ++fn legacy_offer(id: &str) -> bool { ++ id.len() == 36 && uuid::Uuid::try_parse(id).is_ok() ++} ++ + fn entry(id: &str, item: &Value) -> Result { + if !product_id(id) || !item.is_object() { return Err("entitlement-product"); } + let status = item["status"].as_str().filter(|s|s.len()<40).ok_or("entitlement-status")?; +@@ -21,6 +25,9 @@ fn entry(id: &str, item: &Value) -> Result { + let parent = match item.get("satisfiedByProductId") { + None | Some(Value::Null) => None, + Some(Value::String(id)) if product_id(id) => Some(id.as_str()), ++ // An original Xbox or Xbox 360 purchase names its marketplace offer, a GUID: not a Store product, so not a ++ // subscription plan either. The row stands on its own status, trial, sharing and expiry checks. ++ Some(Value::String(id)) if legacy_offer(id) => None, + _ => return Err("entitlement-parent"), + }; + // Preserve typed Positron provenance for conditional library access. +@@ -271,6 +278,19 @@ mod tests { + json!({"status":"Active","isTrial":false,"sharingSource":"None","endDate":"2099-01-01T00:00:00Z"}) + } + ++ #[test] ++ fn a_purchase_naming_its_legacy_marketplace_offer_is_owned_on_its_own_checks() { ++ let mut raw = valid(); raw["satisfiedByProductId"] = json!("66acd000-77fe-1000-9115-d80258410896"); ++ assert!(entry(A, &raw).unwrap()["satisfiedByProductId"].is_null()); ++ raw["isTrial"] = json!(true); ++ assert_eq!(entry(A, &raw).unwrap()["isTrial"], json!(true)); ++ for parent in ["{66acd000-77fe-1000-9115-d80258410896}", "66acd00077fe10009115d80258410896", ++ "urn:uuid:66acd000-77fe-1000-9115-d80258410896", "9aaaaaaaaaaa", ""] { ++ let mut raw = valid(); raw["satisfiedByProductId"] = json!(parent); ++ assert_eq!(entry(A, &raw), Err("entitlement-parent"), "{parent}"); ++ } ++ } ++ + #[test] + fn positron_provenance_is_explicit_boolean_and_never_copied_from_untrusted_fields() { + for flag in [None, Some(json!(false)), Some(json!(true)), Some(Value::Null), diff --git a/tools/xbox/prepare.py b/tools/xbox/prepare.py index 5ff45b9c64..c74e3b7937 100755 --- a/tools/xbox/prepare.py +++ b/tools/xbox/prepare.py @@ -12,7 +12,7 @@ local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', ' 'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', 'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch', 'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch', - 'droiddeck-msixvc2.patch'] + 'droiddeck-msixvc2.patch', 'droiddeck-legacy-offer-parent.patch'] identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest() source = cache / ('source-' + identity[:16]) if not (source / '.prepared').is_file(): From 54e1dcb5a42f722972e106648a5e5ff01365d3a3 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:38:11 -0500 Subject: [PATCH 33/80] Trim own file page cache during sessions under memory pressure (#3439) --- app/src/main/cpp/sdnative/sdnative.c | 14 ++++ .../launcher/session/PageCacheTrim.kt | 70 +++++++++++++++++++ .../launcher/session/SessionService.kt | 5 ++ .../launcher/session/PageCacheTrimTest.kt | 18 +++++ 4 files changed, 107 insertions(+) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt diff --git a/app/src/main/cpp/sdnative/sdnative.c b/app/src/main/cpp/sdnative/sdnative.c index 3e4ef71b41..8482f38d33 100644 --- a/app/src/main/cpp/sdnative/sdnative.c +++ b/app/src/main/cpp/sdnative/sdnative.c @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -27,3 +28,16 @@ Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass cla (void)clazz; return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno; } + +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(JNIEnv *env, jclass clazz, jstring path) { + (void)clazz; + const char *chars = (*env)->GetStringUTFChars(env, path, NULL); + if (!chars) return ENOMEM; + int fd = open(chars, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + (*env)->ReleaseStringUTFChars(env, path, chars); + if (fd < 0) return errno; + int rc = posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); + close(fd); + return rc; +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt b/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt new file mode 100644 index 0000000000..8dc2079e1c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.session + +import android.util.Log +import java.io.File + +internal object PageCacheTrim { + private const val TAG = "PageCacheTrim" + private const val MIN_FILE_BYTES = 8L shl 20 + private const val POLL_MS = 3000L + private const val RESCAN_MS = 120_000L + + data class Mem(val freeKb: Long, val fileKb: Long) + + fun parse(meminfo: String): Mem? { + fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(meminfo)?.groupValues?.get(1)?.toLongOrNull() + val free = field("MemFree") ?: return null + val file = (field("Active\\(file\\)") ?: return null) + (field("Inactive\\(file\\)") ?: return null) + return Mem(free, file) + } + + fun shouldTrim(mem: Mem, baselineFileKb: Long): Boolean { + val built = mem.fileKb - baselineFileKb + return (mem.freeKb < 2560 * 1024 && built >= 768 * 1024) || + (mem.freeKb < 1024 * 1024 && built >= 128 * 1024) + } + + fun start(roots: () -> List, alive: () -> Boolean) { + Thread({ + var baseline = 0L + var files = emptyList() + var scanned = 0L + var trims = 0 + var failureLogged = false + while (alive()) { + runCatching { + val mem = parse(File("/proc/meminfo").readText()) + if (mem != null && shouldTrim(mem, baseline)) { + val now = System.currentTimeMillis() + if (now - scanned > RESCAN_MS) { + files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() } + scanned = now + } + val began = System.nanoTime() + files.forEach(::drop) + val after = parse(File("/proc/meminfo").readText()) + baseline = after?.fileKb ?: mem.fileKb + trims++ + Log.i(TAG, "trim #$trims: free ${mem.freeKb / 1024} -> ${after?.freeKb?.div(1024)} MB, file cache ${mem.fileKb / 1024} -> ${after?.fileKb?.div(1024)} MB, ${files.size} files, ${(System.nanoTime() - began) / 1_000_000} ms") + } + }.onFailure { + if (!failureLogged) Log.w(TAG, "trim failed: $it") + failureLogged = true + } + Thread.sleep(POLL_MS) + } + }, "page-cache-trim").apply { isDaemon = true }.start() + } + + private fun drop(file: File) { + PageCacheNative.fadviseDontNeed(file.path) + } +} + +internal object PageCacheNative { + init { + System.loadLibrary("sdnative") + } + + @JvmStatic external fun fadviseDontNeed(path: String): Int +} 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 88a92efe1b..9ef1456616 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -428,6 +428,11 @@ class SessionService : Service() { ++sessionGen } } + val trimGen = gen + PageCacheTrim.start( + roots = { listOfNotNull(File(filesDir, "linuxfs"), GameStorage.effective(applicationContext)?.let { File(it.path) }).filter(File::isDirectory) }, + alive = { SessionState.running && sessionGen == trimGen }, + ) if (SessionState.stopRequested) { stopSession(0) return START_NOT_STICKY diff --git a/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt new file mode 100644 index 0000000000..1eed5c83ac --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt @@ -0,0 +1,18 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class PageCacheTrimTest { + private val meminfo = "MemFree: 1048576 kB\nActive(file): 2097152 kB\nInactive(file): 1048576 kB\n" + + @Test fun parsesFreeAndFileLru() = assertEquals(PageCacheTrim.Mem(1048576, 3145728), PageCacheTrim.parse(meminfo)) + @Test fun rejectsMissingFields() = assertNull(PageCacheTrim.parse("MemFree: 1 kB\n")) + @Test fun trimsWhenCacheBuiltUpAndFreeIsLow() = assertTrue(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(2000 * 1024, 2000 * 1024), 1000 * 1024)) + @Test fun skipsSmallBuildUp() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(2000 * 1024, 1200 * 1024), 1000 * 1024)) + @Test fun skipsWhenPlentyFree() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(6000 * 1024, 5000 * 1024), 1000 * 1024)) + @Test fun lowFreeAcceptsSmallerBuildUp() = assertTrue(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(500 * 1024, 1200 * 1024), 1000 * 1024)) +} From b81d7d796f0a83a19ec69e2315f98e220bba2075 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:51:53 -0500 Subject: [PATCH 34/80] Default the DroidDeck HUD to FPS and 1% low (#3660) Keep 0.1% and 0.01% lows opt-in without changing saved choices. --- .../launcher/hud/DroidDeckHudConfig.kt | 2 +- .../launcher/hud/DroidDeckHudView.kt | 4 ++-- .../launcher/hud/DroidDeckHudPanelTest.kt | 22 ++++++++++++++++++- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt index fbd14aea93..b7d95c4872 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudConfig.kt @@ -11,7 +11,7 @@ internal object DroidDeckHudConfig { "showPerCore" to "1", "showTemp" to "1", "showBatteryTemp" to "1", "showGpuTemp" to "0", "showVram" to "1", "showRAM" to "1", "showSwap" to "1", "showBattery" to "0", "showBatteryTime" to "0", "showPower" to "1", "showFPS" to "1", "showFPSGraph" to "1", "fpsDecimal" to "1", - "showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "1", "showLow001" to "1", + "showLatency" to "1", "showAvg" to "1", "showLow1" to "1", "showLow01" to "0", "showLow001" to "0", "showEngine" to "1", "showRenderer" to "1", "showDisplay" to "1", "showHdr" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1", "showClock" to "1", "hudOrder" to "", diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt index f58320bc8e..e1984fb7f2 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt @@ -92,8 +92,8 @@ class DroidDeckHudView(context: Context) : View(context) { private var showBatteryTemp = false private var showGraph = false private var showLow1 = true - private var showLow01 = true - private var showLow001 = true + private var showLow01 = false + private var showLow001 = false private var fpsDecimal = true private var showClockTime = true private var showLatency = true diff --git a/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt index 54d3e5584e..e39a1b2ee7 100644 --- a/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudPanelTest.kt @@ -204,6 +204,24 @@ class DroidDeckHudPanelTest { assertEquals(ramFirst.toString(), listOf("RAM", "FPS", "PWR"), ramFirst.map { it.take(3) }) } + @Test fun optionalLowsCanBeSavedAndResetToOff() { + val app = RuntimeEnvironment.getApplication() + val defaults = DroidDeckHudConfig.load(app) + assertEquals("1", defaults["showFPS"]) + assertEquals("1", defaults["showLow1"]) + assertEquals("0", defaults["showLow01"]) + assertEquals("0", defaults["showLow001"]) + + val switches = mapOf("showLow01" to true, "showLow001" to true) + DroidDeckHudConfig.choose(app, switches, emptyList()) + val saved = DroidDeckHudConfig.load(app) + for (key in switches.keys) assertEquals("1", saved[key]) + + DroidDeckHudConfig.reset(app) + val reset = DroidDeckHudConfig.load(app) + for (key in switches.keys) assertEquals("0", reset[key]) + } + @Test fun aSaveKeepsTheLegacyOrderForTheOtherSizes() { val app = RuntimeEnvironment.getApplication() SessionPrefs.setDroidDeckHudConfig(app, "hudSize=strip,hudOrder=showRAM|showFPS") @@ -251,7 +269,9 @@ class DroidDeckHudPanelTest { val lines = view.linesForTest() assertEquals(lines.toString(), 1, lines.size) val line = lines.single() - listOf("DXVK", "fps", "GPU", "CPU", "RAM", "BAT 79%").forEach { assertTrue(line, it in line) } + listOf("DXVK", "fps", "1%", "GPU", "CPU", "RAM", "BAT 79%").forEach { assertTrue(line, it in line) } + assertFalse(line, "0.1%" in line) + assertFalse(line, "0.01%" in line) assertTrue(line, line.indexOf("DXVK") < line.indexOf("GPU") && line.indexOf("GPU") < line.indexOf("BAT")) val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888) From 2aad4fbb1be7537aab988400f11d07739be6531a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:52:15 -0500 Subject: [PATCH 35/80] Keep oversized floating HUD panels from clipping (#3663) Fit the entire floating panel to its viewport without changing saved HUD scale. --- .../launcher/hud/DroidDeckHudView.kt | 33 ++++++-- .../launcher/hud/DroidDeckHudClippingTest.kt | 81 +++++++++++++++++++ 2 files changed, 106 insertions(+), 8 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt index e1984fb7f2..8bb59ad8e6 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckHudView.kt @@ -187,6 +187,12 @@ class DroidDeckHudView(context: Context) : View(context) { private var graphRect: RectF? = null private var contentW = 0f private var contentH = 0f + private var viewportW = Float.POSITIVE_INFINITY + private var viewportH = Float.POSITIVE_INFINITY + + private val panelFit: Float + get() = if (dPanel == null || contentW <= 0f || contentH <= 0f) 1f + else minOf(1f, viewportW / contentW, viewportH / contentH) private var onMovedListener: BiConsumer? = null private var onSizeCycledListener: Consumer? = null @@ -993,13 +999,20 @@ class DroidDeckHudView(context: Context) : View(context) { } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + viewportW = viewportLimit(widthMeasureSpec) + viewportH = viewportLimit(heightMeasureSpec) if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return } + val fit = panelFit setMeasuredDimension( - resolveSize(contentW.roundToInt(), widthMeasureSpec), - resolveSize(contentH.roundToInt(), heightMeasureSpec), + resolveSize((contentW * fit).roundToInt(), widthMeasureSpec), + resolveSize((contentH * fit).roundToInt(), heightMeasureSpec), ) } + private fun viewportLimit(spec: Int): Float = + if (MeasureSpec.getMode(spec) == MeasureSpec.UNSPECIFIED) Float.POSITIVE_INFINITY + else MeasureSpec.getSize(spec).toFloat() + override fun onDraw(canvas: Canvas) { if (contentW <= 0f || contentH <= 0f) { lockController.drawBadge(canvas); return } val blend = if (dock == DroidDeckHudDock.NONE && previewEdge != DroidDeckHudDock.NONE) previewBlend else 0f @@ -1034,8 +1047,10 @@ class DroidDeckHudView(context: Context) : View(context) { } private fun drawContent(canvas: Canvas) { - - dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } } + val fit = panelFit + dPanel?.let { panel -> panelFrame(panel, fit)?.let { canvas.drawBitmap(it, 0f, 0f, null) } } + val saved = canvas.save() + if (fit != 1f) canvas.scale(fit, fit) if (tileRects.isNotEmpty()) { tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255) @@ -1065,6 +1080,7 @@ class DroidDeckHudView(context: Context) : View(context) { if (stripRect != null && layerType != LAYER_TYPE_SOFTWARE) drawCachedGraph(canvas, it) else drawGraph(canvas, it) } + canvas.restoreToCount(saved) lockController.drawBadge(canvas) } @@ -1177,13 +1193,14 @@ class DroidDeckHudView(context: Context) : View(context) { return if (dy <= 0f) p.right - stroke else if (dy >= r) cx else cx + sqrt(r * r - dy * dy) } - private fun panelFrame(panel: RectF): Bitmap? { + private fun panelFrame(panel: RectF, fit: Float): Bitmap? { if (width <= 0 || height <= 0) return null val stroke = outlineWidth() - val key = "$width,$height,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}" + val key = "$width,$height,$fit,$panel,$dRadius,$dDividerTop,$stroke,$accent,$surfaceRgb,$bgOpacity,${outlineColor()}" if (key == dFrameKey) dFrame?.let { return it } val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val c = Canvas(bmp) + c.scale(fit, fit) val corner = sp(6f) val body = dShape(panel.left, panel.top, panel.right, panel.bottom, dRadius, corner) bgPaint.color = panelColor() @@ -1256,8 +1273,8 @@ class DroidDeckHudView(context: Context) : View(context) { internal val isStrip: Boolean get() = stripRect != null - internal val contentWidth: Float get() = contentW - internal val contentHeight: Float get() = contentH + internal val contentWidth: Float get() = contentW * panelFit + internal val contentHeight: Float get() = contentH * panelFit internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging diff --git a/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt new file mode 100644 index 0000000000..00ece3479d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/hud/DroidDeckHudClippingTest.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.hud + +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.view.View +import android.view.ViewGroup.LayoutParams.WRAP_CONTENT +import android.widget.FrameLayout +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "xhdpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class DroidDeckHudClippingTest { + @Test fun aLargerLayoutDrawsItsWholePanelAfterBeingMovedBackOnScreen() { + val app = RuntimeEnvironment.getApplication() + val root = FrameLayout(app) + val hud = DroidDeckHudView(app) + root.addView(hud, FrameLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)) + val config = DroidDeckHudConfig.DEFAULTS + ("hudScale" to "200") + fun select(size: String) { + hud.applyConfig(DroidDeckHudConfig.encode(config + ("hudSize" to size))) + hud.showForTest(DroidDeckHudPanelTest.SNAPSHOT, "DXVK", 0L) + } + fun layout(w: Int, h: Int) { + root.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY)) + root.layout(0, 0, w, h) + } + fun frame() = Bitmap.createBitmap(root.width, root.height, Bitmap.Config.ARGB_8888) + .also { root.draw(Canvas(it)) } + + select("tiles") + layout(3000, 2000) + val naturalWidth = hud.width + val naturalHeight = hud.height + val viewportWidth = naturalWidth + 30 + val viewportHeight = naturalHeight / 2 + + select("pill") + layout(viewportWidth, viewportHeight) + hud.y = viewportHeight - 10f + select("tiles") + layout(viewportWidth, viewportHeight) + hud.x = 10f + hud.y = 0f + + val afterMove = frame() + val middle = hud.x.toInt() + hud.width / 2 + assertTrue("the HUD is drawn", Color.alpha(afterMove.getPixel(middle, hud.height / 2)) > 0) + val lastDrawnRow = (hud.height - 1 downTo 0).first { Color.alpha(afterMove.getPixel(middle, it)) > 0 } + assertTrue("the bottom edge and its outer inset are visible after the move; cutoff row $lastDrawnRow", + lastDrawnRow < hud.height - 1) + assertTrue("vertical fitting preserves the panel aspect instead of clipping it", hud.width < naturalWidth) + + layout(3000, 2000) + assertEquals(naturalWidth, hud.width) + assertEquals(naturalHeight, hud.height) + } + + @Test fun aNarrowViewportFitsBothDimensionsAndKeepsThePanelAspect() { + val hud = DroidDeckHudView(RuntimeEnvironment.getApplication()) + hud.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.DEFAULTS + ("hudSize" to "tiles"))) + hud.showForTest(DroidDeckHudPanelTest.SNAPSHOT, "DXVK", 0L) + val unlimited = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) + hud.measure(unlimited, unlimited) + val naturalWidth = hud.measuredWidth + val naturalHeight = hud.measuredHeight + val narrow = View.MeasureSpec.makeMeasureSpec(naturalWidth / 2, View.MeasureSpec.AT_MOST) + hud.measure(narrow, unlimited) + assertEquals(naturalWidth / 2, hud.measuredWidth) + assertEquals(naturalHeight / 2f, hud.measuredHeight.toFloat(), 2f) + } +} From ebb3bb6373f12b9450e983260096bbb46c0ee54f Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:52:28 -0500 Subject: [PATCH 36/80] Default to visible sticks and add live on-screen controls opacity (#3662) Keep existing settings and touch targets unchanged. Let users dim the touch controls from 100 to 10 percent. --- .../com/droiddeck/launcher/SessionActivity.kt | 32 ++++++++++- .../launcher/input/ControllerPrefs.kt | 12 +++- .../launcher/ui/SecondScreenPresentation.kt | 2 + .../droiddeck/launcher/ui/SessionOverlay.kt | 5 ++ .../launcher/input/InputLibraryTest.kt | 55 +++++++++++++++---- .../launcher/ui/SessionSecondScreenTest.kt | 19 +++++++ 6 files changed, 110 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index f7624434b1..ef4e874e1e 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -993,6 +993,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde openDeckRing("activity created") bridge.setOnPlayerInput(::onPadInput) onScreenControls = OnScreenControls(this, bridge).also { controls -> + controls.alpha = onScreenOpacityAlpha() controls.updateLayout(primaryInputLayout) controls.onTouchMiss = miss@{ event -> if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss @@ -1907,6 +1908,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onWowChat = wowChat::choose, controller = controllerSettings, onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } }, + onControllerOpacity = { percent -> + ControllerPrefs.setOnScreenOpacity(this@SessionActivity, percent) + controllerSettings = ControllerPrefs.read(this@SessionActivity) + applyOnScreenOpacity() + }, onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null, @@ -2265,6 +2271,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (fieldKeyboardOnPrimary) hidePrimaryKeyboard() } + private fun onScreenOpacityAlpha() = ControllerPrefs.onScreenOpacity(this) / 100f + + private fun applyOnScreenOpacity() { + val alpha = onScreenOpacityAlpha() + onScreenControls?.alpha = alpha + bottomInputControls?.alpha = alpha + unfoldedColumn?.alpha = alpha + swappedInputSurface?.alpha = alpha + secondScreenPresentation?.controlsView?.alpha = alpha + steamTouchControls?.let { it.alpha = if (it.isEditing) 1f else alpha } + } + private fun updateControllerPrefs(change: () -> Unit) { change() controllerSettings = ControllerPrefs.read(this) @@ -5135,6 +5153,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (panel == null) { panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) } val column = android.widget.LinearLayout(this).apply { + alpha = onScreenOpacityAlpha() orientation = android.widget.LinearLayout.VERTICAL addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f)) unfoldedKeys = com.droiddeck.launcher.ui.padKeysView( @@ -5980,7 +5999,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val view = com.droiddeck.launcher.input.SteamTouchControls(this, device, onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard) view.visibility = View.GONE - view.onEditingChanged = { touchEditorChanged() } + view.alpha = onScreenOpacityAlpha() + view.onEditingChanged = { editing -> + view.alpha = if (editing) 1f else onScreenOpacityAlpha() + touchEditorChanged() + } view.onOptions = { options -> steamTouchOptions = options applyTouchRouting() @@ -6085,6 +6108,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (bottom?.parent !== bottomRoot) { (bottom?.parent as? android.view.ViewGroup)?.removeView(bottom) bottom = OnScreenControls(bottomRoot.context, padBridge).also { view -> + view.alpha = onScreenOpacityAlpha() view.onTouchMiss = { event -> onBottomGameTouch(event) } bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1)) } @@ -6528,6 +6552,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde joyConVr?.refresh() onScreenControls?.reload() controllerSettings = ControllerPrefs.read(this) + applyOnScreenOpacity() resumed = true boostGpuClock(panelOverGame) updateKeyboardRoute() @@ -7036,7 +7061,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde androidx.compose.runtime.key(profileLayout) { androidx.compose.ui.viewinterop.AndroidView( factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(), - surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } }, + surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { + it.alpha = onScreenOpacityAlpha() + swappedInputSurface = it + } }, modifier = Modifier.fillMaxWidth().weight(1f), onRelease = { if (swappedInputSurface === it) swappedInputSurface = null }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt index 83ae4abc47..73782d7e63 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt @@ -19,6 +19,7 @@ object ControllerPrefs { ) val opacities = listOf(40, 60, 80, 100) + val onScreenOpacityRange = 10..100 val sizes = listOf(80, 85, 90, 95, 100, 105, 110, 115, 120, 125) @@ -45,6 +46,7 @@ object ControllerPrefs { val size: Int, val stickClick: Boolean, val adaptiveSticks: Boolean, + val onScreenOpacity: Int, val rumble: Boolean, val steamButton: Boolean, val qamButton: Boolean, @@ -66,7 +68,8 @@ object ControllerPrefs { opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100, size = p.getInt("size", 100).takeIf { it in sizes } ?: 100, stickClick = p.getBoolean("stickClick", true), - adaptiveSticks = p.getBoolean("adaptiveSticks", true), + adaptiveSticks = p.getBoolean("adaptiveSticks", false), + onScreenOpacity = onScreenOpacity(context), rumble = rumbleEnabled(context), steamButton = p.getBoolean("steamButton", true), qamButton = p.getBoolean("qamButton", true), @@ -103,6 +106,13 @@ object ControllerPrefs { prefs(context).edit().putBoolean("stickClick", on).apply() } + fun onScreenOpacity(context: Context): Int = + prefs(context).getInt("onScreenOpacity", 100).coerceIn(onScreenOpacityRange) + + fun setOnScreenOpacity(context: Context, percent: Int) { + prefs(context).edit().putInt("onScreenOpacity", percent.coerceIn(onScreenOpacityRange)).apply() + } + fun setAdaptiveSticks(context: Context, on: Boolean) { prefs(context).edit().putBoolean("adaptiveSticks", on).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index c9609c311d..508c0f4ea9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -22,6 +22,7 @@ import androidx.compose.material.icons.outlined.Tune import androidx.lifecycle.setViewTreeLifecycleOwner import androidx.lifecycle.setViewTreeViewModelStoreOwner import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.DeckPanel import com.droiddeck.launcher.input.KeyboardHost import com.droiddeck.launcher.input.PadBridge @@ -397,6 +398,7 @@ class SecondScreenPresentation( val layout = panelLayout(mode) val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(), surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) + controls.alpha = ControllerPrefs.onScreenOpacity(context) / 100f controlsView = controls root.addView(controls, weightParams()) attachKeyboard() 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 9402e8396b..b149bc2c72 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -109,6 +109,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.ControllerPrefs import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring @@ -331,6 +332,7 @@ class DrawerActions( val onEditSteamTouch: (() -> Unit)? = null, val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null, val onControllerSize: (Int) -> Unit = {}, + val onControllerOpacity: (Int) -> Unit = {}, val onRumble: (Boolean) -> Unit = {}, val onSuspendPolicy: (String) -> Unit, val onSteamDownloadsInBackground: (Boolean) -> Unit = {}, @@ -747,6 +749,9 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: c?.let { SliderRow(stringResource(R.string.ctrl_size), null, it.size, 80..125, step = 5, format = { v -> "$v%" }, modifier = track("controller-size"), onChange = a.onControllerSize) + SliderRow(stringResource(R.string.ctrl_opacity), null, it.onScreenOpacity, ControllerPrefs.onScreenOpacityRange, step = 5, + format = { v -> "$v%" }, modifier = track("controller-opacity").testTag("controller-opacity"), + onChange = a.onControllerOpacity) } a.adaptiveSticks?.let { adaptive -> ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, adaptive, diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 1f669d1567..0b8d28a23b 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.input import android.content.Context import android.content.ContextWrapper import android.content.SharedPreferences +import android.graphics.Rect import org.json.JSONObject import org.junit.Assert.* import org.junit.Before @@ -428,23 +429,53 @@ class InputLibraryTest { assertTrue(left.width > left.height * 800f / 1200f && right.width > right.height * 800f / 1200f) } + @Test fun theFreshOverlayShowsBothSticksAtRestInEitherOrientation() { + val overlay = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! + assertFalse(ControllerPrefs.read(context).adaptiveSticks) + assertEquals(false, overlay.adaptiveSticks) + for ((width, height) in listOf(1080 to 1920, 1920 to 1080)) { + val sticks = OnScreenLayout.elements(context, overlay, width, height, Rect()) + .filter { it.kind == InputElementKind.STICK } + assertEquals(setOf(InputControl.LS, InputControl.RS), sticks.map { it.control }.toSet()) + assertTrue(sticks.none { it.floating || it.hideWhenIdle }) + } + } + + @Test fun anExistingAdaptivePreferenceStillAppliesWhenImportingAnOverlay() { + ControllerPrefs.setAdaptiveSticks(context, true) + val overlay = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! + assertEquals(true, overlay.adaptiveSticks) + } + + @Test fun onScreenOpacityDefaultsToFullAndClampsWithoutChangingLayoutStyle() { + ControllerPrefs.setOpacity(context, 60) + val layout = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! + assertEquals(100, ControllerPrefs.read(context).onScreenOpacity) + for ((requested, expected) in listOf(0 to 10, 45 to 45, 101 to 100)) { + ControllerPrefs.setOnScreenOpacity(context, requested) + assertEquals(expected, ControllerPrefs.read(context).onScreenOpacity) + assertEquals(60, ControllerPrefs.read(context).opacity) + assertEquals(layout, InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)) + } + } + @Test fun adaptiveSticksToggleChangesOnlyTheSticksOfThatLayout() { val library = InputLibraries.read(context) val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY } - assertEquals(true, overlay.adaptiveSticks) - InputLibraries.setAdaptiveSticks(context, overlay.id, false) - val off = InputLibraries.read(context) - val changed = off.layouts.single { it.id == overlay.id } - assertEquals(false, changed.adaptiveSticks) - assertFalse(ControllerPrefs.read(context).adaptiveSticks) - assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK }) - assertEquals(library.layouts.filter { it.id != overlay.id }, off.layouts.filter { it.id != overlay.id }) - assertNull(off.layouts.single { it.id == InputLibraries.DECK }.adaptiveSticks) + assertEquals(false, overlay.adaptiveSticks) assertTrue(InputLibraries.setAdaptiveSticks(context, overlay.id, true)) - assertEquals(true, InputLibraries.read(context).layouts.single { it.id == overlay.id }.adaptiveSticks) - prefs.edit().putString("library", JSONObject().put("version", 99).toString()).commit() - assertFalse(InputLibraries.setAdaptiveSticks(context, overlay.id, false)) + val enabled = InputLibraries.read(context) + val changed = enabled.layouts.single { it.id == overlay.id } + assertEquals(true, changed.adaptiveSticks) assertTrue(ControllerPrefs.read(context).adaptiveSticks) + assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK }) + assertEquals(library.layouts.filter { it.id != overlay.id }, enabled.layouts.filter { it.id != overlay.id }) + assertNull(enabled.layouts.single { it.id == InputLibraries.DECK }.adaptiveSticks) + assertTrue(InputLibraries.setAdaptiveSticks(context, overlay.id, false)) + assertEquals(false, InputLibraries.read(context).layouts.single { it.id == overlay.id }.adaptiveSticks) + prefs.edit().putString("library", JSONObject().put("version", 99).toString()).commit() + assertFalse(InputLibraries.setAdaptiveSticks(context, overlay.id, true)) + assertFalse(ControllerPrefs.read(context).adaptiveSticks) } @Test fun savedGamepadsFromTheFirstUnifiedBuildGetTheRoundLookOnce() { 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 4fed06c1c4..4b30f0aa0d 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -17,6 +17,7 @@ import com.droiddeck.launcher.R import com.droiddeck.launcher.SessionActivity import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.Lossless +import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.PadBridgeRoutingTest @@ -93,6 +94,22 @@ class SessionSecondScreenTest { assertEquals(SecondScreenMode.CUSTOM_CONTROLS, selected) } + @Test fun onScreenOpacitySliderExposesTheRangeAndUpdatesTheLiveSetting() { + val changed = mutableListOf() + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.CONTROLLER, false, {}, + actions(true, emptyList(), controller = ControllerPrefs.read(context), onOpacity = { changed += it })) + } + } + val open = compose.runOnIdle { DrawerSectionState.isOpen("controller-osc") } + if (!open) compose.onNodeWithTag("drawer-section-controller-osc").performScrollTo().performClick() + val slider = compose.onNodeWithTag("controller-opacity").performScrollTo() + slider.assertIsDisplayed().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(0f) } + slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(45f) } + assertEquals(listOf(10, 45), changed) + } + @Test fun desktopWithoutASecondDisplayHasNoScreenPicker() { SessionState.mode = SessionService.MODE_DESKTOP compose.setContent { @@ -408,9 +425,11 @@ class SessionSecondScreenTest { micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {}, desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {}, onClose: () -> Unit = {}, mode: SecondScreenMode = SecondScreenMode.NONE, gameSwap: Boolean = false, + controller: ControllerPrefs.Settings? = null, onOpacity: (Int) -> Unit = {}, select: (SecondScreenMode) -> Unit = {}) = DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection, isHomeApp = false, androidApps = emptyList(), hudOn = false, + controller = controller, onControllerOpacity = onOpacity, micAvailable = micAvailable, micEnabled = micEnabled, onMicEnabled = onMic, frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never", suspendPolicy = "auto", backActionsInverted = false, From f761e5f1db3e9325f49c2d53ae2e88c2089fe024 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:13:55 -0500 Subject: [PATCH 37/80] Change Steam picture position live from the session menu (#3661) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use independent portrait and landscape alignment, with Top and 1280×800 as the default in Steam portrait. Keep explicit resolutions and existing controls modes. --- app/src/main/cpp/waylandcomp/src/vk_present.c | 4 ++ .../droiddeck/launcher/FrontEndActivity.kt | 23 +++++++--- .../com/droiddeck/launcher/SessionActivity.kt | 11 ++++- .../launcher/session/SessionDisplay.kt | 1 + .../launcher/session/SessionPrefs.kt | 26 +++++++---- .../launcher/session/SettingsReset.kt | 2 +- .../launcher/ui/ModeSettingsDialog.kt | 43 ++++++++++++++----- .../droiddeck/launcher/ui/ResolutionRow.kt | 6 ++- .../droiddeck/launcher/ui/SessionOverlay.kt | 3 ++ app/src/main/res/values-ar/strings.xml | 4 +- app/src/main/res/values-b+es+419/strings.xml | 4 +- app/src/main/res/values-bg/strings.xml | 4 +- app/src/main/res/values-cs/strings.xml | 4 +- app/src/main/res/values-da/strings.xml | 4 +- app/src/main/res/values-de/strings.xml | 4 +- app/src/main/res/values-el/strings.xml | 4 +- app/src/main/res/values-es/strings.xml | 4 +- app/src/main/res/values-fi/strings.xml | 4 +- app/src/main/res/values-fr/strings.xml | 4 +- app/src/main/res/values-hi/strings.xml | 4 +- app/src/main/res/values-hu/strings.xml | 4 +- app/src/main/res/values-in/strings.xml | 4 +- app/src/main/res/values-it/strings.xml | 4 +- app/src/main/res/values-ja/strings.xml | 4 +- app/src/main/res/values-ko/strings.xml | 4 +- app/src/main/res/values-ms/strings.xml | 4 +- app/src/main/res/values-nb/strings.xml | 4 +- app/src/main/res/values-nl/strings.xml | 4 +- app/src/main/res/values-pl/strings.xml | 4 +- app/src/main/res/values-pt-rPT/strings.xml | 4 +- app/src/main/res/values-pt/strings.xml | 4 +- app/src/main/res/values-ro/strings.xml | 4 +- app/src/main/res/values-ru/strings.xml | 4 +- app/src/main/res/values-sv/strings.xml | 4 +- app/src/main/res/values-th/strings.xml | 4 +- app/src/main/res/values-tr/strings.xml | 4 +- app/src/main/res/values-uk/strings.xml | 4 +- app/src/main/res/values-vi/strings.xml | 4 +- app/src/main/res/values-zh-rCN/strings.xml | 4 +- app/src/main/res/values-zh-rHK/strings.xml | 4 +- app/src/main/res/values-zh-rTW/strings.xml | 4 +- app/src/main/res/values/strings.xml | 4 +- .../session/PortraitResolutionTest.kt | 17 +++++++- .../session/SessionScalingPrefsTest.kt | 27 ++++++++++++ .../launcher/ui/SessionSecondScreenTest.kt | 36 ++++++++++++++++ tools/tests/test_picture_position_mapping.py | 18 ++++++++ 46 files changed, 287 insertions(+), 62 deletions(-) diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 9059b5620b..909eb830d8 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -604,6 +604,10 @@ static void update_map(int scene_w, int scene_h) { float min_y = (float)g_map.ry + g_map.rh - image_h; if (g_map.off_y < min_y) g_map.off_y = min_y; if (g_map.off_y > g_map.ry) g_map.off_y = (float)g_map.ry; + } else if (align == VKP_ALIGN_PICTURE_TOP) { + g_map.off_y = 0; + } else if (align == VKP_ALIGN_PICTURE_BOTTOM) { + g_map.off_y = H - image_h; } else { g_map.off_y = (float)g_map.ry + (g_map.rh - image_h) * 0.5f; } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index e8993cff66..8c9657f1f5 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -200,7 +200,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE) private var showPhantomGate by mutableStateOf(false) private var directAudio by mutableStateOf(false) - private var picturePosition by mutableStateOf("center") + private var picturePositionLandscape by mutableStateOf("center") + private var picturePositionPortrait by mutableStateOf("top") private var integerScaling by mutableStateOf(false) private var stretch16x9 by mutableStateOf(false) private var avoidNotch by mutableStateOf(false) @@ -2365,7 +2366,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet refreshHomeAppState() } if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() - settingsMode?.let { hdrOn = SessionPrefs.hdr(this, it) } + settingsMode?.let { mode -> + hdrOn = SessionPrefs.hdr(this, mode) + if (mode == SessionService.MODE_STEAM) loadPicturePositions() + } compatLaunchVisible = true com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) com.droiddeck.launcher.ui.DualScreenPanel.ownerPaused(taskId, false) @@ -2924,7 +2928,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet backHold = backHold, backActionsInverted = backActionsInverted, directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, - picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null, + picturePositionLandscape = picturePositionLandscape.takeIf { mode == SessionService.MODE_STEAM }, + picturePositionPortrait = picturePositionPortrait.takeIf { mode == SessionService.MODE_STEAM }, integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null, stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null, avoidNotch = if (mode == SessionService.MODE_STEAM) avoidNotch else null, @@ -3001,7 +3006,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet backActionsInverted = inverted }, onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on }, - onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value }, + onPicturePosition = { portrait, value -> + SessionPrefs.setPicturePosition(this, portrait, value) + if (portrait) picturePositionPortrait = value else picturePositionLandscape = value + }, onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on }, onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on }, onAvoidNotch = { on -> SessionPrefs.setAvoidNotch(this, on); avoidNotch = on }, @@ -3318,6 +3326,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet resolutionPortrait = SessionPrefs.resolutionStored(this, mode, panel, true) } + private fun loadPicturePositions() { + picturePositionLandscape = SessionPrefs.picturePosition(this, portrait = false) + picturePositionPortrait = SessionPrefs.picturePosition(this, portrait = true) + } + private fun loadModeSettings(mode: String) { pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) @@ -3353,7 +3366,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet backHold = SessionPrefs.backHold(this) backActionsInverted = SessionPrefs.backActionsInverted(this) directAudio = SessionPrefs.directAudio(this) - picturePosition = SessionPrefs.picturePosition(this) + loadPicturePositions() integerScaling = SessionPrefs.integerScaling(this) stretch16x9 = SessionPrefs.stretch16x9(this) avoidNotch = SessionPrefs.avoidNotch(this) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index ef4e874e1e..6cf2f43a9f 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -180,6 +180,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var adaptiveSticks by mutableStateOf(null) private var quickButtons by mutableStateOf>(emptyMap()) private var picturePosition by mutableStateOf("center") + + private fun picturePortrait(config: android.content.res.Configuration = resources.configuration): Boolean = + config.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT private var integerScaling by mutableStateOf(false) private var gameZoom by mutableStateOf(SessionState.gameZoom) private var avoidNotch = false @@ -1717,6 +1720,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionState.gameZoom = gameZoom runCatching { WaylandCompositor.nativeSetZoom(gameZoom) } }, + picturePosition = picturePosition, + onPicturePosition = { position -> + SessionPrefs.setPicturePosition(this@SessionActivity, picturePortrait(), position) + picturePosition = position + }, integerScaling = integerScaling, onIntegerScaling = { enabled -> SessionPrefs.setIntegerScaling(this@SessionActivity, enabled) @@ -2793,7 +2801,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pipAutoEnter = SessionPrefs.pipAutoEnter(this) unfoldedControls = SessionPrefs.unfoldedControls(this) unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this) - picturePosition = SessionPrefs.picturePosition(this) + picturePosition = SessionPrefs.picturePosition(this, picturePortrait()) integerScaling = SessionPrefs.integerScaling(this) avoidNotch = SessionPrefs.avoidNotch(this) applyNotchInset() @@ -3230,6 +3238,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) + picturePosition = SessionPrefs.picturePosition(this, picturePortrait(newConfig)) if (refreshActivityDisplayId() && started) { SessionService.setActivityDisplay(this, sessionActivityDisplayId) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt index 919891fa45..10a20f9fcc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt @@ -16,6 +16,7 @@ object SessionDisplay { const val LINK_PORTRAIT = "link/portrait" const val DEFAULT_RESOLUTION = "720p" + const val DEFAULT_STEAM_PORTRAIT_RESOLUTION = "1280x800" private val PRESET_HEIGHTS = listOf(720, 900, 1080) fun presetHeight(choice: String): Int? = 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 a050da5789..b2cc52bcee 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -946,13 +946,21 @@ object SessionPrefs { } - fun picturePosition(context: Context): String = - prefs(context).getString("picturePosition", "center") - ?.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center" + private val picturePositions = setOf("center", "top", "bottom", "left", "right") - fun setPicturePosition(context: Context, position: String) { - prefs(context).edit().putString("picturePosition", - position.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center").apply() + private fun picturePositionKey(portrait: Boolean) = + if (portrait) "picturePosition.portrait" else "picturePosition.landscape" + + fun picturePosition(context: Context, portrait: Boolean): String { + val preferences = prefs(context) + return preferences.getString(picturePositionKey(portrait), null)?.takeIf { it in picturePositions } + ?: preferences.getString("picturePosition", null)?.takeIf { it in picturePositions } + ?: if (portrait) "top" else "center" + } + + fun setPicturePosition(context: Context, portrait: Boolean, position: String) { + require(position in picturePositions) + prefs(context).edit().putString(picturePositionKey(portrait), position).apply() } fun integerScaling(context: Context): Boolean = @@ -1513,10 +1521,12 @@ object SessionPrefs { fun resolutionStored(context: Context, mode: String, panel: Pair, portrait: Boolean): String { if (!portrait) return landscapeResolutionStored(context, mode, panel) - val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE + val fallback = if (mode == SessionService.MODE_STEAM) SessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION + else SessionDisplay.LINK_LANDSCAPE + val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return fallback if (value == SessionDisplay.LINK_LANDSCAPE || value == SessionDisplay.MATCH_SCREEN || SessionDisplay.isFollow(value) || SessionDisplay.presetHeight(value) != null) return value - return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: SessionDisplay.LINK_LANDSCAPE + return parseOrientedResolution(value)?.let { "${it.first}x${it.second}" } ?: fallback } fun parseOrientedResolution(text: String): Pair? = 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 313f67a574..e4fb6ed9c3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -18,7 +18,7 @@ object SettingsReset { "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "avoidNotch", "picturePosition", "picturePosition.portrait", "picturePosition.landscape", "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", "producerAcquireFences", "paceCores", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", 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 cc8a9bc0eb..2f0cc48a1f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -87,7 +87,8 @@ class ModeSettings( val fexPreset: String? = null, val forceSsbs: Boolean = false, val syncBackend: String? = null, - val picturePosition: String? = null, + val picturePositionLandscape: String? = null, + val picturePositionPortrait: String? = null, val integerScaling: Boolean? = null, val stretch16x9: Boolean? = null, val avoidNotch: Boolean? = null, @@ -152,7 +153,7 @@ class ModeSettingsActions( val onFexPreset: (String) -> Unit = {}, val onForceSsbs: (Boolean) -> Unit = {}, val onSyncBackend: (String) -> Unit = {}, - val onPicturePosition: (String) -> Unit = {}, + val onPicturePosition: (Boolean, String) -> Unit = { _, _ -> }, val onIntegerScaling: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {}, val onAvoidNotch: (Boolean) -> Unit = {}, @@ -262,15 +263,16 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: ResolutionRow(host, "resolution-portrait", stringResource(R.string.display_resolution_portrait), s.resolutionPortrait, portraitChoice, com.droiddeck.launcher.session.SessionDisplay.LINK_LANDSCAPE, if (sessionDisplay.isLink(s.resolution)) portraitChoice else sessionDisplay.orientCustom(s.resolution, true), - s.panelSize, a.onResolutionPortrait, portrait = true) - s.picturePosition?.let { position -> - ChoiceRow(host, "picture-position", stringResource(R.string.display_picture_position), null, - listOf("top" to stringResource(R.string.display_position_top), - "bottom" to stringResource(R.string.display_position_bottom), - "left" to stringResource(R.string.display_position_left), - "right" to stringResource(R.string.display_position_right), - "center" to stringResource(R.string.display_position_center)), - position, onPick = a.onPicturePosition) + s.panelSize, a.onResolutionPortrait, portrait = true, + defaultChoice = if (s.mode == SessionService.MODE_STEAM) sessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION + else sessionDisplay.DEFAULT_RESOLUTION) + s.picturePositionLandscape?.let { position -> + PicturePositionRow(host, position, key = "picture-position-landscape", + labelRes = R.string.display_picture_position_landscape) { a.onPicturePosition(false, it) } + } + s.picturePositionPortrait?.let { position -> + PicturePositionRow(host, position, key = "picture-position-portrait", + labelRes = R.string.display_picture_position_portrait) { a.onPicturePosition(true, it) } } if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) || com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) { @@ -742,3 +744,22 @@ internal fun CustomFollowScaleDialog(initial: Float?, onSave: (Float) -> Unit, o dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss, modifier = Modifier.focusGlide(CircleShape)) { Text(stringResource(R.string.common_cancel)) } }, ) } + +@Composable +internal fun PicturePositionRow( + host: MenuHost, position: String, + chipModifier: Modifier = Modifier, + key: String = "picture-position", + @androidx.annotation.StringRes labelRes: Int = R.string.display_picture_position, + onPick: (String) -> Unit, +) { + ChoiceRow(host, key, stringResource(labelRes), null, + listOf( + "center" to stringResource(R.string.display_position_center), + "top" to stringResource(R.string.display_position_top), + "bottom" to stringResource(R.string.display_position_bottom), + "left" to stringResource(R.string.display_position_left), + "right" to stringResource(R.string.display_position_right), + ), + position, chipModifier = chipModifier, onPick = onPick) +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt index ca9ca5976c..34121eb342 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ResolutionRow.kt @@ -16,12 +16,14 @@ fun ResolutionRow( panel: Pair, onPick: (String) -> Unit, chipModifier: Modifier = Modifier, portrait: Boolean = false, + defaultChoice: String = SessionDisplay.DEFAULT_RESOLUTION, ) { val custom = "custom" val linked = stored == link val size = SessionDisplay.resolveChoice(panel, choice, portrait) val screen = SessionDisplay.resolveChoice(panel, SessionDisplay.MATCH_SCREEN, portrait) - val choices = SessionDisplay.resolutionOptions(panel) + val presets = SessionDisplay.resolutionOptions(panel) + val choices = if (defaultChoice == SessionDisplay.DEFAULT_RESOLUTION) presets else listOf(defaultChoice) + presets val customFollow = !linked && SessionDisplay.isFollow(choice) && choice !in choices val selected = if (linked) link else if (SessionDisplay.isFollow(choice)) choice else if (size == screen) SessionDisplay.MATCH_SCREEN else choice @@ -36,7 +38,7 @@ fun ResolutionRow( else if (value == SessionDisplay.FOLLOW_SCREEN) stringResource(R.string.display_follow_screen) else if (SessionDisplay.isFollow(value)) stringResource(R.string.display_follow_screen_scaled, SessionDisplay.formatScale(SessionDisplay.followScale(value) ?: 1f)) + " (${dimensions.first}×${dimensions.second})" - else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}") + else if (value == defaultChoice) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}") else "${dimensions.first}×${dimensions.second}" } + listOf(SessionDisplay.FOLLOW_CUSTOM to stringResource(R.string.display_follow_screen_scaled, if (customFollow) SessionDisplay.formatScale(SessionDisplay.followScale(choice) ?: 1f) else "…" 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 b149bc2c72..2fa213d89c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -270,6 +270,8 @@ class DrawerActions( val upscaleSharpness: Int = 75, val integerScaling: Boolean = false, val onIntegerScaling: (Boolean) -> Unit = {}, + val picturePosition: String = "center", + val onPicturePosition: (String) -> Unit = {}, val gameZoomAvailable: Boolean = false, val gameZoom: Float = 1.0f, val onGameZoom: (Float) -> Unit = {}, @@ -935,6 +937,7 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) if (a.gameZoomAvailable) GameZoomRow(a, track) ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null, orientations, a.orientation, chipModifier = track("orientation"), onPick = a.onOrientation) + if (a.steam) PicturePositionRow(host, a.picturePosition, track("picture-position"), onPick = a.onPicturePosition) } val filters = SessionPrefs.upscalerChoices(LocalContext.current) val integer = stringResource(if (a.integerScaling) R.string.display_scaling_integer else R.string.display_scaling_fit) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 754bd58c81..ea85ca5c12 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -3329,9 +3329,11 @@ %1$s س %1$d د موضع الصورة + موضع الصورة (أفقي) + موضع الصورة (عمودي) أعلى أسفل - الوسط (افتراضي) + الوسط يسار يمين التخزين 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 f6780a5bd2..12254b5715 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -3205,9 +3205,11 @@ Seguimiento de manos ¿Rastrear las manos o los mandos Joy-Con con la cámara del teléfono? Posición de la imagen + Posición de la imagen (Horizontal) + Posición de la imagen (Vertical) Arriba Abajo - Centro (predeterminado) + Centro Izquierda Derecha Almacenamiento diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index ad5942ef4e..bb4ff12581 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -3209,9 +3209,11 @@ %1$s ч %1$d мин Позиция на картината + Позиция на картината (Хоризонтална) + Позиция на картината (Вертикална) Горе Долу - В средата (по подразбиране) + В средата Наляво Надясно Съхранение diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index dc6d83dcc3..02d5c6d00d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -3269,9 +3269,11 @@ %1$s h %1$d min Poloha obrázku + Poloha obrázku (Na šířku) + Poloha obrázku (Na výšku) Nahoře Dole - Uprostřed (výchozí) + Uprostřed Vlevo Vpravo Úložiště diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 62ba81b634..f3383e6768 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -3209,9 +3209,11 @@ %1$s t %1$d min Billedets placering + Billedets placering (Liggende) + Billedets placering (Stående) Øverst Nederst - Midten (standard) + Midten Venstre Højre Lager diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b3cef5f653..ce45ef01d4 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -3209,9 +3209,11 @@ Zu wenig Speicher (%1$s frei, %2$s benötigt) Freier Speicher unbekannt Bildposition + Bildposition (Querformat) + Bildposition (Hochformat) Oben Unten - Mitte (Standard) + Mitte Links Rechts Speicher diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 2c0bc9f686..7205dd9940 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -3209,9 +3209,11 @@ %1$s ώ. %1$d λεπ. Θέση εικόνας + Θέση εικόνας (Οριζόντιος προσανατολισμός) + Θέση εικόνας (Κατακόρυφος) Πάνω Κάτω - Κέντρο (προεπιλογή) + Κέντρο Αριστερά Δεξιά Αποθήκευση diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b7d9fc9715..71e10bdab3 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -3239,9 +3239,11 @@ Espacio insuficiente (%1$s libres, se necesitan %2$s) Espacio libre desconocido Posición de la imagen + Posición de la imagen (Horizontal) + Posición de la imagen (Vertical) Arriba Abajo - Centro (predeterminado) + Centro Izquierda Derecha Almacenamiento diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 72b6e1bf8b..464e2576be 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -3209,9 +3209,11 @@ %1$s t %1$d min Kuvan sijainti + Kuvan sijainti (Vaakasuunta) + Kuvan sijainti (Pystysuunta) Ylhäällä Alhaalla - Keskellä (oletus) + Keskellä Vasen Oikea Tallennustila diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e45c8eaeb6..7c1c1ef44d 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -3238,9 +3238,11 @@ Espace insuffisant (%1$s libres, %2$s nécessaires) Espace libre inconnu Position de l\'image + Position de l\'image (Paysage) + Position de l\'image (Portrait) Haut Bas - Centre (par défaut) + Centre Gauche Droite Stockage diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 264f4ec9a3..281c5914d5 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -3209,9 +3209,11 @@ %1$s घं %1$d मि चित्र की स्थिति + चित्र की स्थिति (लैंडस्केप) + चित्र की स्थिति (पोर्ट्रेट) ऊपर नीचे - बीच में (डिफ़ॉल्ट) + बीच में बाएँ दाएँ स्टोरेज diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 8fbbda9dc7..a74cef1df8 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -3209,9 +3209,11 @@ %1$s óra %1$d perc A kép pozíciója + A kép pozíciója (Fekvő) + A kép pozíciója (Álló) Fent Lent - Középen (alapértelmezett) + Középen Bal Jobb Tárhely diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index b31983df6a..8bd5840655 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -3180,9 +3180,11 @@ %1$s j %1$d mnt Posisi gambar + Posisi gambar (Lanskap) + Posisi gambar (Potret) Atas Bawah - Tengah (bawaan) + Tengah Kiri Kanan Penyimpanan diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9b21a504f5..0d79a90921 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -3238,9 +3238,11 @@ Spazio insufficiente (%1$s liberi, ne servono %2$s) Spazio libero sconosciuto Posizione immagine + Posizione immagine (Orizzontale) + Posizione immagine (Verticale) In alto In basso - Centro (predefinito) + Centro Sinistra Destra Archiviazione diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 1e37e3fd19..f66a14fc6e 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -3180,9 +3180,11 @@ ダウンロードは「コンポーネント」ページと共有されます。上でダウンロード済みのバージョンを選ぶと、次回のゲーム起動時に使用されます。 ダウンロードするバージョンを選択 画面の位置 + 画面の位置(横向き) + 画面の位置(縦向き) 上 下 - 中央(既定) + 中央 左 右 ストレージ diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 4265a93915..dbcf405e3f 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -3180,9 +3180,11 @@ 다운로드는 구성 요소 페이지와 공유됩니다. 위에서 다운로드한 버전을 선택하면 다음 게임 실행 시 사용됩니다. 다운로드할 버전 선택 화면 위치 + 화면 위치 (가로 모드) + 화면 위치 (세로) 위 아래 - 가운데(기본) + 가운데 왼쪽 오른쪽 저장 공간 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index d756db11c2..2dc5bcea1b 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -3180,9 +3180,11 @@ %1$s j %1$d min Kedudukan gambar + Kedudukan gambar (Lanskap) + Kedudukan gambar (Potret) Atas Bawah - Tengah (lalai) + Tengah Kiri Kanan Storan diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 19ef1fb16e..70da47fde8 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -3209,9 +3209,11 @@ %1$s t %1$d min Bildets posisjon + Bildets posisjon (Liggende) + Bildets posisjon (Stående) Øverst Nederst - Midten (standard) + Midten Venstre Høyre Lagring diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index bcf4b8e01b..aa95f349be 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -3209,9 +3209,11 @@ %1$s u %1$d min Positie van de afbeelding + Positie van de afbeelding (Liggend) + Positie van de afbeelding (Staand) Boven Onder - Midden (standaard) + Midden Links Rechts Opslag diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a5600f8599..350871461b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -3269,9 +3269,11 @@ %1$s godz. %1$d min Pozycja obrazu + Pozycja obrazu (Pozioma) + Pozycja obrazu (Pionowa) Góra Dół - Środek (domyślnie) + Środek Lewo Prawo Pamięć diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index e4a63e898e..58c25267da 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -3253,11 +3253,13 @@ Espaço livre insuficiente: são necessários %1$s, só há %2$s livres Espaço livre desconhecido Posição da imagem + Posição da imagem (Horizontal) + Posição da imagem (Vertical) Topo Esquerda Direita Fundo - Centro (predefinido) + Centro Armazenamento A medir o armazenamento… Na primeira vez demora alguns segundos. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 86bf64d7b3..08eb2c38de 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -3263,11 +3263,13 @@ Espaço insuficiente (%1$s livres, são necessários %2$s) Espaço livre desconhecido Posição da imagem + Posição da imagem (Paisagem) + Posição da imagem (Retrato) Topo Esquerda Direita Base - Centro (padrão) + Centro Armazenamento Medindo o armazenamento… Na primeira vez leva alguns segundos. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 8b546406e7..bd89893d52 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -3239,9 +3239,11 @@ %1$s h %1$d min Poziția imaginii + Poziția imaginii (Peisaj) + Poziția imaginii (Portret) Sus Jos - Centru (implicit) + Centru Stânga Dreapta Stocare diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index ba81437f53..c75b0aa343 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -3270,9 +3270,11 @@ Недостаточно места (свободно %1$s, нужно %2$s) Свободное место неизвестно Положение изображения + Положение изображения (Альбомная) + Положение изображения (Портретная) Сверху Снизу - По центру (по умолчанию) + По центру Слева Справа Хранилище diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 6a807c9cf6..f3819c7385 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -3209,9 +3209,11 @@ %1$s h %1$d min Bildens position + Bildens position (Liggande) + Bildens position (Stående) Överst Nederst - Mitten (standard) + Mitten Vänster Höger Lagring diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 1e740d1d48..21c96ecd2a 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -3180,9 +3180,11 @@ %1$s ชม. %1$d นาที ตำแหน่งภาพ + ตำแหน่งภาพ (แนวนอน) + ตำแหน่งภาพ (แนวตั้ง) บน ล่าง - กลาง (ค่าเริ่มต้น) + กลาง ซ้าย ขวา พื้นที่จัดเก็บ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 360505b6e6..acc9089167 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -3209,9 +3209,11 @@ Yetersiz alan (%1$s boş, %2$s gerekli) Boş alan bilinmiyor Görüntü konumu + Görüntü konumu (Yatay) + Görüntü konumu (Dikey) Üst Alt - Orta (varsayılan) + Orta Sol Sağ Depolama diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index fe153bb8d9..6ca06df91c 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -3269,9 +3269,11 @@ %1$s год %1$d хв Позиція зображення + Позиція зображення (Альбомна) + Позиція зображення (Книжкова) Угорі Унизу - По центру (типово) + По центру Ліворуч Праворуч Сховище diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 89f173d547..420c0c1bf5 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -3180,9 +3180,11 @@ %1$s giờ %1$d phút Vị trí ảnh + Vị trí ảnh (Ngang) + Vị trí ảnh (Dọc) Trên Dưới - Giữa (mặc định) + Giữa Trái Phải Lưu trữ diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index faca08c4fa..eb5407a271 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -3180,9 +3180,11 @@ 下载内容与“组件”页面共享。在上方选择已下载的版本,即可在下次启动游戏时使用。 选择要下载的版本 画面位置 + 画面位置(横屏) + 画面位置(竖屏) 置顶 置底 - 居中(默认) + 居中 左侧 右侧 存储 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index dad8b25c85..7f4bbd0233 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -3177,9 +3177,11 @@ 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 + 畫面位置(橫向) + 畫面位置(直向) 置頂 置底 - 置中(預設) + 置中 左側 右側 儲存空間 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index dbe4020e01..e52193ca17 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -3177,9 +3177,11 @@ 下載內容與「元件」頁面共用。在上方選擇已下載的版本,即可在下次啟動遊戲時使用。 選擇要下載的版本 畫面位置 + 畫面位置(橫向) + 畫面位置(直向) 置頂 置底 - 置中(預設) + 置中 左側 右側 儲存空間 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0aa6e64681..a0be598c63 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -3577,11 +3577,13 @@ Experimental XREAL 1S, One, One Pro, One Pro+ and Aura support. Use Follow mode and turn off stabilization in the glasses menu; on the Aura, also turn off Spatial Anchor. Head tracking and 2D/3D switching are tested on the Aura and One Pro+. Experimental Pro 2 head tracking. Brightness, volume, and display switching are not supported yet. Picture position + Landscape picture position + Portrait picture position Top Left Right Bottom - Center (default) + Center 6DoF virtual screen Positional tracking — experimental Physical movement in VR and around virtual screens. Restarting tracking takes a moment. diff --git a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt index f010e97a65..a5c3d057fb 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PortraitResolutionTest.kt @@ -20,7 +20,18 @@ class PortraitResolutionTest { app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } - @Test fun portraitFollowsLandscapeUntilItIsSet() { + @Test fun steamPortraitStartsWithA16By10PictureWithoutChangingLandscapeOrDesktop() { + assertEquals(SessionDisplay.DEFAULT_RESOLUTION, SessionPrefs.resolutionChoice(app, "steam", panel)) + assertEquals(SessionDisplay.DEFAULT_STEAM_PORTRAIT_RESOLUTION, SessionPrefs.resolutionStored(app, "steam", panel, true)) + val choice = SessionPrefs.resolutionChoice(app, "steam", panel, true) + assertEquals(1280 to 800, SessionDisplay.resolveChoice(panel, choice, portrait = true)) + assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "lxqt", panel, true)) + SessionPrefs.setResolutionChoice(app, "steam", "900p") + assertEquals(choice, SessionPrefs.resolutionChoice(app, "steam", panel, true)) + } + + @Test fun explicitlyLinkedPortraitKeepsFollowingLandscape() { + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) assertEquals(SessionDisplay.LINK_LANDSCAPE, SessionPrefs.resolutionStored(app, "steam", panel, true)) SessionPrefs.setResolutionChoice(app, "steam", "900p") assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) @@ -45,6 +56,7 @@ class PortraitResolutionTest { @Test fun followingEachOtherNeverLoops() { SessionPrefs.setResolutionChoice(app, "steam", "900p") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, false)) assertEquals("900p", SessionPrefs.resolutionChoice(app, "steam", panel, true)) @@ -53,6 +65,7 @@ class PortraitResolutionTest { @Test fun aGeneratedPortraitSizeSurvivesAReload() { SessionPrefs.setResolutionChoice(app, "steam", "2560x1440") + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) assertEquals("1440x2560", SessionPrefs.resolutionStored(app, "steam", panel, true)) assertEquals("2560x1440", SessionPrefs.resolutionChoice(app, "steam", panel, false)) @@ -89,6 +102,8 @@ class PortraitResolutionTest { @Test fun followScalesKeepLinkedAndFixedChoices() { SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.followScaled(1.5f)) + assertEquals(1.5f to null, SessionPrefs.followScales(app, "steam", panel)) + SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_LANDSCAPE, portrait = true) assertEquals(1.5f to 1.5f, SessionPrefs.followScales(app, "steam", panel)) SessionPrefs.setResolutionChoice(app, "steam", "1024x768", portrait = true) SessionPrefs.setResolutionChoice(app, "steam", SessionDisplay.LINK_PORTRAIT) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt index 3d0e420001..023aa85553 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt @@ -72,6 +72,33 @@ class SessionScalingPrefsTest { assertEquals("1024x768", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080)) } + @Test fun picturePositionDefaultsToTopInPortraitAndCenterInLandscape() { + val ctx = RuntimeEnvironment.getApplication() + assertEquals("top", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("center", SessionPrefs.picturePosition(ctx, portrait = false)) + } + + @Test fun eachOrientationKeepsItsOwnPicturePosition() { + val ctx = RuntimeEnvironment.getApplication() + SessionPrefs.setPicturePosition(ctx, portrait = true, position = "bottom") + assertEquals("center", SessionPrefs.picturePosition(ctx, portrait = false)) + SessionPrefs.setPicturePosition(ctx, portrait = false, position = "right") + assertEquals("bottom", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("right", SessionPrefs.picturePosition(ctx, portrait = false)) + } + + @Test fun legacyPicturePositionIsPreservedUntilEachOrientationIsChanged() { + val ctx = RuntimeEnvironment.getApplication() + ctx.getSharedPreferences("session", Context.MODE_PRIVATE).edit().putString("picturePosition", "left").commit() + assertEquals("left", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("left", SessionPrefs.picturePosition(ctx, portrait = false)) + SessionPrefs.setPicturePosition(ctx, portrait = true, position = "top") + assertEquals("top", SessionPrefs.picturePosition(ctx, portrait = true)) + assertEquals("left", SessionPrefs.picturePosition(ctx, portrait = false)) + assertTrue(SettingsReset.isSessionSetting("picturePosition.portrait")) + assertTrue(SettingsReset.isSessionSetting("picturePosition.landscape")) + } + @Test fun legacySavedFiltersStillResolveToAVisibleEquivalentChoice() { val context = RuntimeEnvironment.getApplication() val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE) 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 4b30f0aa0d..da99b2f8a9 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -12,6 +12,7 @@ import android.widget.TextView import androidx.compose.ui.test.* import androidx.compose.ui.semantics.SemanticsProperties.StateDescription import androidx.compose.runtime.MutableState +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.geometry.Offset import com.droiddeck.launcher.R import com.droiddeck.launcher.SessionActivity @@ -153,6 +154,39 @@ class SessionSecondScreenTest { compose.onNodeWithText("Bottom screen").performScrollTo().assertIsDisplayed() } + @Test fun steamDisplayCanChooseTopAndBottomLive() { + SessionState.mode = SessionService.MODE_STEAM + val position = mutableStateOf("center") + val choices = mutableListOf() + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, actions( + true, emptyList(), picturePosition = position.value, + onPicturePosition = { choices += it; position.value = it }, + )) + } + } + compose.openSection("display") + val picker = compose.onNodeWithTag("setting-picture-position") + picker.performScrollTo().assert(hasText(context.getString(R.string.display_position_center))).performClick() + compose.onNodeWithText(context.getString(R.string.display_position_top)).performClick() + picker.assert(hasText(context.getString(R.string.display_position_top))).performClick() + compose.onNodeWithText(context.getString(R.string.display_position_bottom)).performClick() + picker.assert(hasText(context.getString(R.string.display_position_bottom))) + assertEquals(listOf("top", "bottom"), choices) + } + + @Test fun desktopDisplayDoesNotOfferSteamPicturePosition() { + SessionState.mode = SessionService.MODE_DESKTOP + compose.setContent { + DroidDeckTheme { + SessionDrawer(true, SessionDrawerPage.DISPLAY, false, {}, actions(false, emptyList())) + } + } + compose.openSection("display") + compose.onNodeWithTag("setting-picture-position").assertDoesNotExist() + } + @Test fun provisionalBottomScreenPanelSettlesOnlyOnceTheSessionIsInFront() { SessionState.mode = SessionService.MODE_STEAM val previousMode = SessionState.secondScreenMode @@ -425,9 +459,11 @@ class SessionSecondScreenTest { micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {}, desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {}, onClose: () -> Unit = {}, mode: SecondScreenMode = SecondScreenMode.NONE, gameSwap: Boolean = false, + picturePosition: String = "center", onPicturePosition: (String) -> Unit = {}, controller: ControllerPrefs.Settings? = null, onOpacity: (Int) -> Unit = {}, select: (SecondScreenMode) -> Unit = {}) = DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection, + picturePosition = picturePosition, onPicturePosition = onPicturePosition, isHomeApp = false, androidApps = emptyList(), hudOn = false, controller = controller, onControllerOpacity = onOpacity, micAvailable = micAvailable, micEnabled = micEnabled, onMicEnabled = onMic, diff --git a/tools/tests/test_picture_position_mapping.py b/tools/tests/test_picture_position_mapping.py index 2c9eb8e32b..f6e7673840 100644 --- a/tools/tests/test_picture_position_mapping.py +++ b/tools/tests/test_picture_position_mapping.py @@ -50,6 +50,20 @@ static void check(int sw, int sh, int ow, int oh, int alignment) { assert(!vkp_game_picture_rect(rect)); near(g_map.off_y, (int)((oh - sh * g_map.ky) * 0.5)); } +static void check_zoomed_portrait(int alignment) { + g_extent.width = 1080; g_extent.height = 1920; + g_mode = VKP_MODE_FIT; g_align = alignment; g_zoom = 1.5f; + update_map(1280, 720); + float rect[4]; + assert(vkp_game_picture_rect(rect)); + double height = 720 * g_map.ky; + assert(height < 1920); + near(rect[1], alignment == VKP_ALIGN_PICTURE_TOP ? 0 : 1920 - height); + double sx, sy; + assert(vkp_output_to_scene(540, rect[1] + height / 2, &sx, &sy)); + near(sx, 640); near(sy, 360); + g_zoom = 1.0f; +} int main(void) { for (int alignment = VKP_ALIGN_PICTURE_TOP; alignment <= VKP_ALIGN_PICTURE_BOTTOM; alignment++) { check(1240, 1100, 2480, 2200, alignment); @@ -57,7 +71,11 @@ int main(void) { check(1024, 768, 2480, 2200, alignment); check(1920, 1080, 2400, 1080, alignment); check(1240, 1100, 2480, 1394, alignment); + check(1280, 720, 1080, 1920, alignment); + check(1280, 800, 1080, 1920, alignment); + check_zoomed_portrait(alignment); } + g_extent.width = 2480; g_extent.height = 1394; g_align = VKP_ALIGN_TOP; update_map(1280, 720); assert(g_map.rh == 697 && g_map.ry == 0); puts("PASS"); From bd016858c7a3167d3767a650db2e6e6c986f945a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:49:50 -0500 Subject: [PATCH 38/80] fix(agent): keys reach the pet's editor after its chat closes and opens again (#3666) The pet's chat panel absorbed taps with a clickable disabled while the chat was closed. A disabled clickable drops its focus node, so closing the chat removed a node above the still-focused editor and reopening put back a new, unfocused one in its place. Compose then found no focus target for key events: backspace and other key presses were dropped, and with the pet's view focused, DroidDeck crashed with "Event can't be processed because we do not have an active focus target". --- .../droiddeck/launcher/ui/AgentPetWindows.kt | 15 ++++-- .../launcher/ui/AgentPetChatFocusTest.kt | 47 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt index 72e5d0b635..e2381ca2a4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPetWindows.kt @@ -21,6 +21,7 @@ import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -495,7 +496,13 @@ internal class PetWindows(private val context: Context) { * under it. Its contents are built while it is closed, so opening only animates. */ @Composable -internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onClosed: () -> Unit) { +internal fun PetChat( + open: Boolean, motion: PetMotion, onClose: () -> Unit, + page: @Composable ColumnScope.(AgentMenuSlot) -> Unit = { slot -> + AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = slot) + }, + onClosed: () -> Unit, +) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val density = androidx.compose.ui.platform.LocalDensity.current @@ -552,14 +559,16 @@ internal fun PetChat(open: Boolean, motion: PetMotion, onClose: () -> Unit, onCl alpha = fade.value } .clip(Shape16).background(colors.background).border(1.dp, pal.line, Shape16) - .clickable(remember { MutableInteractionSource() }, null, enabled = open) {} + // Never disabled: a disabled clickable leaves the focus tree, and the one it puts back on reopening + // sits unfocused above the still-focused editor, where key events then find no focus target. + .clickable(remember { MutableInteractionSource() }, null) {} .padding(start = 12.dp, end = 12.dp, top = 6.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(bottom = 2.dp)) { Box(Modifier.weight(1f)) { menuSlot.content?.invoke() } HeaderAction(Icons.Outlined.Close, stringResource(R.string.agent_close), size = 34.dp, tag = "agent-pet-close", onClick = onClose) } - AgentPage(Modifier.weight(1f).fillMaxWidth(), visible = open, startTyping = AgentHost.entries.isEmpty(), hidesPet = false, menuSlot = menuSlot) + page(menuSlot) } } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt new file mode 100644 index 0000000000..e5214e1e98 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AgentPetChatFocusTest.kt @@ -0,0 +1,47 @@ +package com.droiddeck.launcher.ui + +import android.view.KeyEvent as AndroidKeyEvent +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performKeyPress +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], qualifiers = "w411dp-h891dp-port", application = android.app.Application::class) +class AgentPetChatFocusTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun keysStillReachTheEditorAfterTheChatClosesAndOpensAgain() { + val open = mutableStateOf(true) + val text = mutableStateOf("ab") + val motion = PetMotion(RuntimeEnvironment.getApplication()) + compose.setContent { + DroidDeckTheme { + PetChat(open.value, motion, onClose = { open.value = false }, page = { + BasicTextField(text.value, { text.value = it }, Modifier.testTag("editor")) + }) {} + } + } + compose.onNodeWithTag("editor").performClick() + open.value = false + compose.waitForIdle() + open.value = true + compose.waitForIdle() + + compose.onNodeWithTag("editor").performKeyPress(KeyEvent(AndroidKeyEvent(AndroidKeyEvent.ACTION_DOWN, AndroidKeyEvent.KEYCODE_DEL))) + compose.waitForIdle() + + assertEquals("a", text.value) + } +} From 34b78e2e420eb4893ba3775496816768e2fedf24 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:27:31 -0500 Subject: [PATCH 39/80] Agent chat: open pictures full screen (#3668) feat(agent): open chat pictures full screen Tapping a picture in the agent chat, or an attached image, opens it over the whole window. Pinch or double-tap zooms and dragging pans; a tap, a swipe down, Back or B, or the close button closes it. It is a popup so it also works in the pet's chat, which lives in an overlay window. --- .../com/droiddeck/launcher/ui/AgentEntries.kt | 4 +- .../droiddeck/launcher/ui/AgentMarkdown.kt | 6 +- .../launcher/ui/AgentPictureViewer.kt | 113 ++++++++++++++++++ 3 files changed, 119 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt 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 800a829cb8..1df2b17315 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentEntries.kt @@ -377,10 +377,11 @@ private fun CodeBox(label: String, text: String, color: Color) { internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) { val context = LocalContext.current val pal = LocalPalette.current + var viewing by remember(path) { mutableStateOf(false) } Box { if (AgentAttachments.isImage(path)) AsyncImage( model = AgentAttachments.host(context, path), contentDescription = path.substringAfterLast('/'), contentScale = ContentScale.Crop, - modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant), + modifier = Modifier.size(72.dp).clip(Shape12).background(pal.surfaceVariant).clickable { viewing = true }, ) else Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.heightIn(min = 40.dp).clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 10.dp, vertical = 8.dp), @@ -396,4 +397,5 @@ internal fun AttachmentChip(path: String, onRemove: (() -> Unit)?) { Icon(Icons.Outlined.Close, stringResource(R.string.agent_remove_attachment), tint = pal.onSurfaceVariant, modifier = Modifier.size(14.dp)) } } + if (viewing) PictureViewer(AgentAttachments.host(context, path), path.substringAfterLast('/')) { viewing = false } } 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 2a13c4119b..49f351a175 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentMarkdown.kt @@ -126,16 +126,16 @@ internal fun AgentReply(text: String, modifier: Modifier) { 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) } + var viewing 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 }, + modifier = Modifier.widthIn(max = 560.dp).heightIn(max = 420.dp).clip(Shape12).clickable { viewing = true }, ) + if (viewing) PictureViewer(file, picture.alt.ifBlank { file.name }) { viewing = false } } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt new file mode 100644 index 0000000000..3dea67d609 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPictureViewer.kt @@ -0,0 +1,113 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.calculatePan +import androidx.compose.foundation.gestures.calculateZoom +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.input.pointer.positionChanged +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupProperties +import coil.compose.AsyncImage +import com.droiddeck.launcher.R +import kotlin.math.abs + +private const val MAX_ZOOM = 5f +private const val TAP_ZOOM = 2.5f + +/** + * A picture over the whole window: pinch or double-tap to zoom, drag to pan. A tap, a swipe down, + * Back or B close it. It is a popup, not a dialog, because the pet's chat lives in an overlay window, + * which has no activity token to show a dialog with. + */ +@Composable +internal fun PictureViewer(model: Any, description: String?, onDismiss: () -> Unit) { + Popup( + alignment = Alignment.Center, onDismissRequest = onDismiss, + properties = PopupProperties(focusable = true, dismissOnBackPress = true, dismissOnClickOutside = false), + ) { + var size by remember { mutableStateOf(IntSize.Zero) } + var scale by remember { mutableFloatStateOf(1f) } + var offset by remember { mutableStateOf(Offset.Zero) } + fun clamp(o: Offset, s: Float): Offset { + val x = size.width * (s - 1f) / 2f + val y = size.height * (s - 1f) / 2f + return Offset(o.x.coerceIn(-x, x), o.y.coerceIn(-y, y)) + } + val fade = if (scale == 1f && size.height > 0) (1f - abs(offset.y) / size.height * 2f).coerceIn(0.3f, 1f) else 1f + Box( + Modifier.fillMaxSize().onSizeChanged { size = it }.background(Color.Black.copy(alpha = 0.94f * fade)) + .pointerInput(Unit) { + detectTapGestures( + onDoubleTap = { at -> + if (scale > 1f) { scale = 1f; offset = Offset.Zero } else { + scale = TAP_ZOOM + offset = clamp((Offset(size.width / 2f, size.height / 2f) - at) * (TAP_ZOOM - 1f), TAP_ZOOM) + } + }, + onTap = { if (scale == 1f) onDismiss() }, + ) + } + .pointerInput(Unit) { + awaitEachGesture { + awaitFirstDown(requireUnconsumed = false) + do { + val event = awaitPointerEvent() + val zoom = event.calculateZoom() + val pan = event.calculatePan() + if (zoom != 1f || pan != Offset.Zero) { + val next = (scale * zoom).coerceIn(1f, MAX_ZOOM) + offset = if (next > 1f) clamp(offset * (next / scale) + pan, next) else Offset(0f, offset.y + pan.y) + scale = next + event.changes.forEach { if (it.positionChanged()) it.consume() } + } + } while (event.changes.any { it.pressed }) + if (scale == 1f) { + if (abs(offset.y) > size.height / 6f) onDismiss() else offset = Offset.Zero + } + } + }, + ) { + AsyncImage( + model = model, contentDescription = description, contentScale = ContentScale.Fit, + modifier = Modifier.fillMaxSize().graphicsLayer { + scaleX = scale; scaleY = scale; translationX = offset.x; translationY = offset.y + }, + ) + IconButton( + onClick = onDismiss, + modifier = Modifier.align(Alignment.TopEnd).padding(12.dp).size(44.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.5f)), + ) { + Icon(Icons.Outlined.Close, stringResource(R.string.common_close), tint = Color.White) + } + } + } +} From a6ffbe7d8116d448f2bb4849a51ba7e950fe6eec Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:29:39 -0400 Subject: [PATCH 40/80] Add ZeroFG and optional ZeroPacer (#3552) Add ZeroFG as a frame generation engine with its opt-in pacer. Keep frame generation in the dedicated session tab and keep manual DLL import removed. --- app/src/main/cpp/CMakeLists.txt | 11 + .../cpp/thirdparty/zerofg/README.DroidDeck.md | 1 + app/src/main/cpp/waylandcomp/CMakeLists.txt | 5 +- .../main/cpp/waylandcomp/src/effects_chain.c | 51 +- .../main/cpp/waylandcomp/src/effects_chain.h | 1 + .../cpp/waylandcomp/src/framegen_bridge.c | 115 +++- .../cpp/waylandcomp/src/framegen_bridge.h | 14 +- .../cpp/waylandcomp/src/framegen_engine.cpp | 160 ++++- .../cpp/waylandcomp/src/framegen_engine.h | 19 +- .../waylandcomp/src/framegen_engine_stub.c | 25 +- .../main/cpp/waylandcomp/src/framegen_jni.c | 6 + .../cpp/waylandcomp/src/framegen_zerofg.cpp | 602 ++++++++++++++++++ .../cpp/waylandcomp/src/framegen_zerofg.h | 38 ++ app/src/main/cpp/waylandcomp/src/sc_layer.c | 46 +- app/src/main/cpp/waylandcomp/src/sc_layer.h | 13 + app/src/main/cpp/waylandcomp/src/vk_present.c | 91 ++- .../com/droiddeck/launcher/gpu/FrameGen.kt | 17 + .../com/droiddeck/launcher/ui/FrameGenMenu.kt | 123 +++- .../droiddeck/launcher/ui/SessionOverlay.kt | 32 +- .../launcher/wayland/WaylandCompositor.java | 4 +- app/src/main/res/values/zerofg_framegen.xml | 4 + .../droiddeck/launcher/gpu/FrameGenTest.kt | 10 + docs/development/framegen-post-upscale.md | 5 +- tools/tests/test_effects_source_resolution.py | 60 +- tools/tests/test_framegen_ring_lifetime.py | 2 + tools/tests/vk_terminal_callers_test.c | 4 + 26 files changed, 1348 insertions(+), 111 deletions(-) create mode 100644 app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md create mode 100644 app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp create mode 100644 app/src/main/cpp/waylandcomp/src/framegen_zerofg.h create mode 100644 app/src/main/res/values/zerofg_framegen.xml diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index a33cf37e49..01ae9fd830 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -10,6 +10,17 @@ add_subdirectory(adrenotools) add_subdirectory(thirdparty/dxbc) +# Pin ZeroFG to a fixed revision instead of vendoring thousands of generated shader lines. +include(FetchContent) +set(ZEROFG_VULKAN_HEADERS_DIR "${CMAKE_SYSROOT}/usr/include" CACHE PATH "" FORCE) +set(ZEROFG_PREBUILT_SHADERS ON CACHE STRING "" FORCE) +FetchContent_Declare(zerofg + GIT_REPOSITORY https://github.com/hy300leosquizz-ctrl/ZeroFG.git + GIT_TAG e6ca7ef9f9765db89847b6d8eed352e458f1a8bb + GIT_PROGRESS TRUE +) +FetchContent_MakeAvailable(zerofg) + set(DDFG_UPSTREAM "v0.3.0") set(DDFG_CHAIN_SRC framegen/ddfg/framegen.cpp diff --git a/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md b/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md new file mode 100644 index 0000000000..0872e65ca9 --- /dev/null +++ b/app/src/main/cpp/thirdparty/zerofg/README.DroidDeck.md @@ -0,0 +1 @@ +ZeroFG is fetched by CMake from hy300leosquizz-ctrl/ZeroFG (the upstream repository) at pinned commit e6ca7ef9f9765db89847b6d8eed352e458f1a8bb. DroidDeck keeps ownership of presentation; the independent presenter is not used. License: Apache-2.0 OR GPL-2.0-or-later; see the fetched ZeroFG source tree for the license text. diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index ca528afb88..2cd55b2761 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -64,6 +64,7 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, DD-FG Native)") target_sources(droiddeckwayland PRIVATE src/framegen_engine.cpp + src/framegen_zerofg.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dll.cpp ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dxbc.cpp @@ -90,12 +91,12 @@ if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/../framegen ) target_compile_options(droiddeckwayland PRIVATE - $<$:-std=c++17 -fvisibility=hidden>) + $<$:-std=c++20 -fvisibility=hidden>) target_compile_definitions(droiddeckwayland PRIVATE DDFG_UPSTREAM="${DDFG_UPSTREAM}" DDFG_CHAIN_HASH="${DDFG_CHAIN_HASH}" ) - target_link_libraries(droiddeckwayland dxbc atomic) + target_link_libraries(droiddeckwayland dxbc atomic zerofg::zerofg) else() message(STATUS "droiddeckwayland: frame-generation engines NOT built in (standalone build): stub") target_sources(droiddeckwayland PRIVATE src/framegen_engine_stub.c) diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.c b/app/src/main/cpp/waylandcomp/src/effects_chain.c index a94d7b7906..6d307dcd7d 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.c +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.c @@ -366,6 +366,44 @@ void vkp_effects_forget_image(VkImage img) { g_context = saved; } +VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt) { + if (!g_dev || !img || w <= 0 || h <= 0 || fmt == VK_FORMAT_UNDEFINED) return VK_NULL_HANDLE; + + for (int i = 0; i < FX_CONTEXTS; ++i) { + struct fx_context *ctx = &g_contexts[i]; + if (ctx->scene.img == img && ctx->scene.view) return ctx->scene.view; + for (int j = 0; j < 2; ++j) + if (ctx->targets[j].img == img && ctx->targets[j].view) return ctx->targets[j].view; + if (ctx->mid.img == img && ctx->mid.view) return ctx->mid.view; + if (ctx->nissrc.img == img && ctx->nissrc.view) return ctx->nissrc.view; + } + if (g_smaa_edges.img == img && g_smaa_edges.view) return g_smaa_edges.view; + if (g_smaa_weights.img == img && g_smaa_weights.view) return g_smaa_weights.view; + + /* The effects chain can bypass every pass and return the compositor's scene image + * directly. Keep a view for that image in the existing per-context cache so the + * normal image-forget path destroys it before the image itself. */ + int saved = g_context; + g_context = 0; + if (g_scene.img != img || g_scene.view == VK_NULL_HANDLE || + g_scene.w != w || g_scene.h != h) { + scene_release(); + VkImageView view = make_view(img, fmt); + if (!view) { + g_context = saved; + return VK_NULL_HANDLE; + } + g_scene.img = img; + g_scene.view = view; + g_scene.w = w; + g_scene.h = h; + g_scene.ds = VK_NULL_HANDLE; + } + VkImageView result = g_scene.view; + g_context = saved; + return result; +} + void vkp_effects_release_generated_sources(void) { for (g_context = 1; g_context < FX_CONTEXTS; g_context++) scene_release(); g_context = 0; @@ -1026,13 +1064,18 @@ VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_ struct fx_source_state source_state = {0}; VkImage result = effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h, VK_IMAGE_LAYOUT_GENERAL, &g_generated_settings, &source_state); - barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, - VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); - if (result != scene) + if (result != scene) { + barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); barrier(cmd, scene, source_state.layout, VK_IMAGE_LAYOUT_GENERAL, source_state.stage, source_state.access, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT); + } else if (source_state.layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL) { + barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT); + } g_context = 0; return result; } diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.h b/app/src/main/cpp/waylandcomp/src/effects_chain.h index 99f2ad93d5..a0aba31138 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.h +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.h @@ -28,6 +28,7 @@ VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_ void vkp_effects_destroy(void); void vkp_effects_forget_image(VkImage img); +VkImageView vkp_effects_framegen_image_view(VkImage img, int w, int h, VkFormat fmt); void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_is_pq); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c index 385475f950..7745c3ddc0 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c @@ -3,6 +3,7 @@ #include "framegen_engine.h" #include "effects_chain.h" #include "vk_loader.h" +#include "sc_layer.h" #include #include #include @@ -36,7 +37,7 @@ static VkQueue g_queue; static uint32_t g_qfam; static _Atomic int g_dev_ready, g_dev_lost; static int g_features_enabled; -static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok; +static _Atomic int g_caps_lsfg_ok, g_caps_ddfg_ok, g_caps_zero_ok; static VkPhysicalDeviceMemoryProperties g_memprops; static struct { PFN_vkCreateImage CreateImage; @@ -87,9 +88,44 @@ static int64_t now_ns(void) { return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec; } +/* The pair the last run made, for the display probe and the pacer: when its real frame reached the + * compositor, the game moment each generated frame shows, and the refresh the pacer timed each for. */ +static _Atomic int g_pacer_on; +static int g_layer_path; +static int g_out_gens; +static int64_t g_out_planned[VKP_FG_MAX_GENERATIONS + 1]; +static int64_t g_completion_issue; + +void vkp_framegen_set_pacer(int on) { + if (atomic_exchange(&g_pacer_on, on ? 1 : 0) != (on ? 1 : 0)) { + fge_pacer_reset(); + FGLOG("ZeroFG pacer %s", on ? "on: frame generation times its frames itself" : "off: the display layer times them"); + } +} + +static int pacer_wanted(void) { return atomic_load(&g_pacer_on); } + +void vkp_framegen_pacer_abort(void) { + g_completion_issue = 0; + fge_pacer_reset(); +} + +void vkp_framegen_output_planned(int k, int gens, int64_t *planned) { + *planned = (k < 0 || k >= gens || k >= g_out_gens) + ? g_out_planned[g_out_gens] : g_out_planned[k]; +} + +void vkp_framegen_completed(void) { + if (!g_completion_issue) return; + fge_pacer_completed(g_completion_issue, now_ns()); + g_completion_issue = 0; +} + +void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns) { fge_pacer_shown(planned_ns, shown_ns); } + void vkp_framegen_set_engine(int kind) { - if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG) kind = VKP_FG_ENGINE_LSFG; + if (kind != VKP_FG_ENGINE_LSFG && kind != VKP_FG_ENGINE_DDFG && kind != VKP_FG_ENGINE_ZEROFG) kind = VKP_FG_ENGINE_LSFG; atomic_store(&g_kind, kind); atomic_store(&g_failed_kind, -1); atomic_store(&g_cfg_dirty, 1); @@ -118,6 +154,11 @@ void vkp_framegen_set_lsfg_cache_path(const char *path) { pthread_mutex_unlock(&g_lock); } +void vkp_framegen_set_layer_timing(int layer) { + g_layer_path = layer; + fge_set_layer_timing(layer); +} + void vkp_framegen_set_tuning(float flow_scale, float refresh_hz) { if (flow_scale < 0.25f) flow_scale = 0.25f; if (flow_scale > 1.0f) flow_scale = 1.0f; @@ -146,15 +187,15 @@ static void mark_failed(int kind) { int vkp_framegen_problem(void) { if (!atomic_load(&g_dev_ready)) return -1; int kind = atomic_load(&g_kind); - int caps_ok = kind == VKP_FG_ENGINE_DDFG - ? atomic_load(&g_caps_ddfg_ok) - : atomic_load(&g_caps_lsfg_ok); + int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) : + kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) : + atomic_load(&g_caps_lsfg_ok); if (!caps_ok) return 1; if (start_failed_for(kind)) return 2; if (g_engine_ok && g_engine_kind == kind && fge_unavailable()) return 2; return 0; } -const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(); } +const char *vkp_framegen_caps_reason(void) { return fge_caps_reason(atomic_load(&g_kind)); } void vkp_framegen_stats(float out[6]) { float accepted = 0.0f, src = 0.0f, thermal = -1.0f; @@ -187,12 +228,14 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f fge_device_ready(g_gipa, g_inst, g_pd, dev, queue, qfam, features_enabled); atomic_store(&g_caps_lsfg_ok, fge_caps_ok(VKP_FG_ENGINE_LSFG)); atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG)); + atomic_store(&g_caps_zero_ok, fge_caps_ok(VKP_FG_ENGINE_ZEROFG)); atomic_store(&g_dev_lost, 0); atomic_store(&g_dev_ready, vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier); - FGLOG("engines ready on the compositor's device: LSFG Native %s (%s), DD-FG Native %s", - fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", fge_caps_reason(), - fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable"); + FGLOG("engines ready on compositor device: LSFG %s, DD-FG %s, ZeroFG %s", + fge_caps_ok(VKP_FG_ENGINE_LSFG) ? "available" : "unavailable", + fge_caps_ok(VKP_FG_ENGINE_DDFG) ? "available" : "unavailable", + fge_caps_ok(VKP_FG_ENGINE_ZEROFG) ? "available" : "unavailable"); } void vkp_framegen_device_lost(void) { @@ -283,16 +326,18 @@ static int engine_usable(void) { int kind = atomic_load(&g_kind); int ready = atomic_load(&g_dev_ready); int lost = atomic_load(&g_dev_lost); - int caps_ok = kind == VKP_FG_ENGINE_DDFG - ? atomic_load(&g_caps_ddfg_ok) - : atomic_load(&g_caps_lsfg_ok); + int caps_ok = kind == VKP_FG_ENGINE_ZEROFG ? atomic_load(&g_caps_zero_ok) : + kind == VKP_FG_ENGINE_DDFG ? atomic_load(&g_caps_ddfg_ok) : + atomic_load(&g_caps_lsfg_ok); return ready && !lost && caps_ok && !start_failed_for(kind); } int vkp_framegen_format_ok(VkFormat fmt) { - if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1; if (!g_dev_ready || g_dev_lost || format_refused(fmt)) return 0; - return fge_format_ok(fmt); + int kind = atomic_load(&g_kind); + if (kind == VKP_FG_ENGINE_ZEROFG) return fge_format_ok(VKP_FG_ENGINE_ZEROFG, fmt); + if (fmt == VK_FORMAT_R8G8B8A8_UNORM) return 1; + return fge_format_ok(kind, fmt); } static void refuse_format(VkFormat fmt, int kind, int w, int h, const char *what) { @@ -377,11 +422,14 @@ static void log_arm_transition(int armed, int kind, int mult) { int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h, VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]) { - (void)scene_view; int kind = atomic_load(&g_kind); int armed = atomic_load(&g_armed); int mult = atomic_load(&g_mult); g_planned = 0; + const int64_t issue = now_ns(); + g_out_gens = 0; + memset(g_out_planned, 0, sizeof(g_out_planned)); + g_completion_issue = 0; if (!armed || !engine_usable() || w <= 0 || h <= 0) { log_arm_transition(0, kind, mult); return 0; } if (!ensure_engine(kind)) { log_arm_transition(0, kind, mult); return 0; } log_arm_transition(1, kind, mult); @@ -423,8 +471,31 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, ++g_source_frames; const uint64_t game_frames = droiddeck_game_frames(); - uint32_t n_gen = fge_plan(g_ring_n, game_frames ? game_frames : g_source_frames, g_presented_rate); + const uint64_t planning_sequence = game_frames ? game_frames : g_source_frames; + uint32_t n_gen = fge_plan(g_ring_n, planning_sequence, g_presented_rate); if (n_gen > g_ring_n) n_gen = g_ring_n; + if (kind == VKP_FG_ENGINE_ZEROFG && n_gen > 0 && !scene_view) { + scene_view = vkp_effects_framegen_image_view(scene, w, h, fmt); + if (!scene_view) { + static int view_warning; + if (!view_warning++) FGLOG("ZeroFG could not create a view for the source image; showing real frames only"); + n_gen = 0; + } + } + fge_set_phases(NULL, 0); + if (kind == VKP_FG_ENGINE_ZEROFG && pacer_wanted() && g_layer_path) { + int64_t vsync = 0, period = 0; + sc_layer_timeline(&vsync, &period); + int64_t planned[VKP_FG_MAX_GENERATIONS + 1]; + float phases[VKP_FG_MAX_GENERATIONS + 1]; + const uint32_t count = period > 0 + ? fge_pacer_plan((uint32_t)mult, period, vsync, issue, n_gen, planned, phases) : 0; + if (count >= 1 && count - 1 <= n_gen) { + n_gen = count - 1; + for (uint32_t i = 0; i < count; i++) g_out_planned[i] = planned[i]; + fge_set_phases(phases, n_gen); + } + } g_planned = n_gen; VkImageMemoryBarrier bars[1 + VKP_FG_MAX_GENERATIONS]; @@ -452,21 +523,25 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, nb, bars); - fge_process(cmd, scene, (uint32_t)w, (uint32_t)h, n_gen); + fge_process(cmd, scene, scene_view, (uint32_t)w, (uint32_t)h, fmt, planning_sequence, n_gen); for (uint32_t g = 0; g < n_gen; g++) { fge_generate(cmd, g, n_gen, g_ring[g].img, g_ring[g].view, (uint32_t)w, (uint32_t)h); gens[g] = g_ring[g].img; } if (n_gen) { nb = 0; + const VkAccessFlags generated_access = kind == VKP_FG_ENGINE_ZEROFG + ? VK_ACCESS_MEMORY_WRITE_BIT : VK_ACCESS_SHADER_WRITE_BIT; + const VkPipelineStageFlags generated_stage = kind == VKP_FG_ENGINE_ZEROFG + ? VK_PIPELINE_STAGE_ALL_COMMANDS_BIT : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; for (uint32_t g = 0; g < n_gen; g++) bars[nb++] = (VkImageMemoryBarrier){ .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, - .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, + .srcAccessMask = generated_access, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, .oldLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_ring[g].img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}; - vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + vk.CmdPipelineBarrier(cmd, generated_stage, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, nb, bars); if (!g_generating_logged) { g_generating_logged = 1; @@ -476,6 +551,8 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? ", FP16: the HDR picture" : ""); } } + g_out_gens = (int)n_gen; + if (n_gen > 0) g_completion_issue = issue; return (int)n_gen; } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h index 573d6fd3c6..3412eda7f1 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.h @@ -6,7 +6,7 @@ #endif #include -enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1 }; +enum { VKP_FG_ENGINE_LSFG = 0, VKP_FG_ENGINE_DDFG = 1, VKP_FG_ENGINE_ZEROFG = 2 }; #define VKP_FG_MAX_GENERATIONS 3 void vkp_framegen_set_engine(int kind); @@ -26,6 +26,18 @@ void vkp_framegen_device_lost(void); int vkp_framegen_active(void); int vkp_framegen_extra_images(void); +/* 1 when the next run's frames are shown through the scene layer's timed group, 0 through the swapchain's FIFO. */ +void vkp_framegen_set_layer_timing(int layer); +/* ZeroFG's pacer (include/zerofg/inline_pacer.h) times the layer's frames instead of the layer's own spacing. */ +void vkp_framegen_set_pacer(int on); +/* Reset pacing history when a planned real-frame pair is aborted before presentation. */ +void vkp_framegen_pacer_abort(void); +/* Refresh planned for output k of the last run (k == gens: its real frame; 0: use layer timing). */ +void vkp_framegen_output_planned(int k, int gens, int64_t *planned); +/* The last run's GPU work finished (the compositor's fence signalled). */ +void vkp_framegen_completed(void); +/* A real frame the pacer timed for planned_ns was shown at shown_ns. */ +void vkp_framegen_real_shown(int64_t planned_ns, int64_t shown_ns); int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, int w, int h, VkFormat fmt, VkImage gens[VKP_FG_MAX_GENERATIONS]); void vkp_framegen_presented(int generated); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp index ed16dd4c88..6f0b6db6b0 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -13,6 +14,9 @@ #include "lsfg/lsfg_probe.h" #include "lsfg/lsfg_vkd.h" #include "ddfg/ddfg_engine.h" +#include "framegen_zerofg.h" + +#include #define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__) #define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__) @@ -22,12 +26,17 @@ namespace { VkTable g_table{}; lsfg::Caps g_caps{}; VkPhysicalDeviceVulkan12Features g_v12{}; +VkPhysicalDeviceVulkan13Features g_v13{}; VkPhysicalDeviceFeatures2 g_f2{}; VkPhysicalDevice g_pd = VK_NULL_HANDLE; VkDevice g_dev = VK_NULL_HANDLE; VkQueue g_queue = VK_NULL_HANDLE; uint32_t g_qfam = 0; bool g_probed = false, g_ready = false; +bool g_zero_supported = false, g_zero_enabled = false; +zerofg::InlinePacer g_pacer; +zerofg::InlineReadiness g_readiness; +std::mutex g_pacer_mutex; std::unique_ptr g_lsfg; std::unique_ptr g_ddfg; @@ -88,30 +97,57 @@ const void *fge_probe(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica if (n) enumExts(pd, nullptr, &n, exts.data()); } g_caps = lsfg::Caps{}; - - - g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false); + g_caps.features = lsfg::queryFeatures(g_table, pd, exts, false); g_caps.probedFormat = ring_fmt; g_caps.storageOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties ? lsfg::probeStorageFormat(g_table, pd, ring_fmt) : false; g_caps.linearBlitOnSwapchainFormat = g_table.GetPhysicalDeviceFormatProperties ? lsfg::probeLinearBlit(g_table, pd, ring_fmt) : false; g_probed = true; - if (!g_caps.features.deviceGatesPass()) { + + VkPhysicalDeviceProperties props{}; + if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props); + VkPhysicalDeviceVulkan13Features supported13{}; + supported13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + VkPhysicalDeviceFeatures2 supported2{}; + supported2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + if (props.apiVersion >= VK_API_VERSION_1_3) supported2.pNext = &supported13; + if (g_table.GetPhysicalDeviceFeatures2) g_table.GetPhysicalDeviceFeatures2(pd, &supported2); + g_zero_supported = props.apiVersion >= VK_API_VERSION_1_3 && + supported13.synchronization2 == VK_TRUE && + supported2.features.shaderStorageImageExtendedFormats == VK_TRUE; + g_zero_enabled = false; + + const bool lsfg_supported = g_caps.features.deviceGatesPass(); + if (!lsfg_supported) { lsfg::explain(g_caps); ELOG("device gates for the LSFG chain fail: %s", g_caps.reason); + } + if (!lsfg_supported && !g_zero_supported) { + g_v12 = {}; + g_v13 = {}; + g_f2 = {}; return nullptr; } + g_v12 = VkPhysicalDeviceVulkan12Features{}; g_v12.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; - g_v12.vulkanMemoryModel = VK_TRUE; + g_v12.vulkanMemoryModel = + g_caps.features.vulkanMemoryModel ? VK_TRUE : VK_FALSE; g_v12.vulkanMemoryModelDeviceScope = g_caps.features.vulkanMemoryModelDeviceScope ? VK_TRUE : VK_FALSE; + g_v13 = VkPhysicalDeviceVulkan13Features{}; + g_v13.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES; + g_v13.synchronization2 = g_zero_supported ? VK_TRUE : VK_FALSE; + if (g_zero_supported) g_v12.pNext = &g_v13; + g_f2 = VkPhysicalDeviceFeatures2{}; g_f2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; g_f2.pNext = &g_v12; - g_f2.features.shaderStorageImageWriteWithoutFormat = VK_TRUE; - g_f2.features.shaderStorageImageExtendedFormats = VK_TRUE; + g_f2.features.shaderStorageImageWriteWithoutFormat = + supported2.features.shaderStorageImageWriteWithoutFormat ? VK_TRUE : VK_FALSE; + g_f2.features.shaderStorageImageExtendedFormats = + supported2.features.shaderStorageImageExtendedFormats ? VK_TRUE : VK_FALSE; return &g_f2; } @@ -122,9 +158,17 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica fill_device(dev); g_caps.featuresEnabled = features_enabled != 0; lsfg::explain(g_caps); + VkPhysicalDeviceProperties props{}; + if (g_table.GetPhysicalDeviceProperties) g_table.GetPhysicalDeviceProperties(pd, &props); + g_zero_enabled = g_zero_supported && features_enabled != 0; + zfg_device_ready(gipa, inst, pd, dev, + props.apiVersion > VK_API_VERSION_1_3 ? VK_API_VERSION_1_3 : props.apiVersion, + g_zero_enabled, + g_zero_enabled && g_f2.features.shaderStorageImageExtendedFormats == VK_TRUE); g_ready = true; - ELOG("device ready: lsfg caps '%s', storage on ring format %d", g_caps.reason, - (int)g_caps.storageOnSwapchainFormat); + ELOG("device ready: lsfg caps '%s', storage on ring format %d, ZeroFG %s", + g_caps.reason, (int)g_caps.storageOnSwapchainFormat, + g_zero_enabled ? "available" : "unavailable"); } void fge_device_lost(void) { @@ -149,24 +193,45 @@ void fge_device_lost(void) { g_v12 = {}; g_f2 = {}; g_build[0] = 0; + g_zero_supported = g_zero_enabled = false; + zfg_device_lost(); } int fge_caps_ok(int kind) { if (!g_ready) return 0; + if (kind == 2) return g_zero_enabled && zfg_caps_ok(); if (kind == 1) return g_caps.storageOnSwapchainFormat ? 1 : 0; return g_caps.supported() ? 1 : 0; } -const char *fge_caps_reason(void) { return g_caps.reason; } +int fge_engine_available(int kind) { return fge_caps_ok(kind); } -int fge_format_ok(VkFormat fmt) { +const char *fge_caps_reason(int kind) { + if (kind == 2 && !g_zero_enabled) + return "ZeroFG requires Vulkan 1.3, synchronization2 and extended storage-image formats"; + if (kind == 2) return zfg_caps_reason(); + return g_caps.reason; +} + +int fge_format_ok(int kind, VkFormat fmt) { + if (kind == 2) return zfg_format_ok(fmt); if (!g_ready || !g_table.GetPhysicalDeviceFormatProperties || fmt == VK_FORMAT_UNDEFINED) return 0; return lsfg::probeStorageFormat(g_table, g_pd, fmt) && lsfg::probeLinearBlit(g_table, g_pd, fmt) ? 1 : 0; } int fge_start(int kind, const char *cache_path) { fge_stop(); + fge_pacer_reset(); if (!g_ready) return -1; + if (kind == 2) { + if (!g_zero_enabled || !zfg_start()) { + ELOGE("ZeroFG engine init failed"); + return -1; + } + g_kind = 2; + std::snprintf(g_build, sizeof(g_build), "ZeroFG ReallyZero, Vulkan 1.3 Compat"); + return 0; + } if (kind == 1) { auto e = std::make_unique(); if (!e->init(g_table, g_pd, g_dev, g_qfam, g_queue)) { @@ -201,14 +266,16 @@ int fge_start(int kind, const char *cache_path) { } void fge_stop(void) { - if (g_lsfg) { - if (g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev); - g_lsfg.reset(); - } + if ((g_kind == 0 || g_kind == 2) && g_table.DeviceWaitIdle && g_dev) + g_table.DeviceWaitIdle(g_dev); + + g_lsfg.reset(); + for (auto it = g_retained_ddfg.begin(); it != g_retained_ddfg.end();) { if ((*it)->destroy()) it = g_retained_ddfg.erase(it); else ++it; } + if (g_ddfg) { if (g_ddfg->destroy()) g_ddfg.reset(); else { @@ -216,10 +283,13 @@ void fge_stop(void) { g_retained_ddfg.push_back(std::move(g_ddfg)); } } + + zfg_stop(); g_kind = -1; } int fge_unavailable(void) { + if (g_kind == 2) return zfg_unavailable(); if (g_kind == 1) return g_ddfg && g_ddfg->unavailable() ? 1 : 0; return g_lsfg && g_lsfg->unavailable() ? 1 : 0; } @@ -227,11 +297,13 @@ int fge_unavailable(void) { void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, float refresh_hz, int model, int perf_preset) { if (multiplier < 2) multiplier = 2; + if (g_kind == 2) { zfg_configure(multiplier, refresh_hz); return; } if (g_kind == 1 && g_ddfg) g_ddfg->configure(multiplier, model, perf_preset, flow_scale); else if (g_lsfg) g_lsfg->configure(multiplier, target_fps, flow_scale, refresh_hz); } int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { + if (g_kind == 2) return zfg_prepare(w, h, fmt); if (g_kind == 1) return g_ddfg && g_ddfg->prepare(w, h, fmt) ? 1 : 0; if (!g_lsfg) return 0; g_lsfg->setGuestExtent(w, h); @@ -239,24 +311,74 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { } uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { + if (g_kind == 2) return zfg_plan(capacity, source_frames); if (g_kind == 1) return g_ddfg ? g_ddfg->plan(capacity) : 0; if (!g_lsfg) return 0; g_lsfg->setPresentedRate(presented_rate); return g_lsfg->plan(capacity, source_frames); } -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens) { + if (g_kind == 2) { + zfg_process(cmd, source, source_view, w, h, fmt, sequence, gens); + return; + } if (g_kind == 1) { if (g_ddfg) g_ddfg->process(cmd, source, w, h, gens); return; } if (g_lsfg) g_lsfg->process(cmd, source, w, h, gens); } void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h) { + if (g_kind == 2) { zfg_generate(cmd, g, count, img, view, w, h); return; } if (g_kind == 1) { if (g_ddfg) g_ddfg->generateInto(cmd, g, count, img, view, w, h); return; } if (g_lsfg) g_lsfg->generateInto(cmd, g, g, img, view, w, h); } +void fge_set_layer_timing(int layer) { zfg_set_layer_timing(layer); } + +void fge_set_phases(const float *phases, uint32_t count) { zfg_set_phases(phases, count); } + +float fge_phase(uint32_t index, uint32_t count) { + if (g_kind == 2) return zfg_phase(index, count); + return static_cast(index + 1) / static_cast(count + 1); +} + +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases) { + if (period_ns <= 0 || issue_ns <= 0) return 0; + std::lock_guard lock(g_pacer_mutex); + g_pacer.SetMultiplier(multiplier); + g_pacer.ObserveVsync(static_cast(period_ns), static_cast(vsync_ns > 0 ? vsync_ns : 0)); + const uint64_t issue = static_cast(issue_ns); + const zerofg::InlinePacer::Plan plan = + g_pacer.PlanPair(issue, issue + g_readiness.MarginNs(static_cast(period_ns)), max_generated + 1); + for (uint32_t i = 0; i < plan.count; i++) { + present_ns[i] = static_cast(plan.outputs[i].present_ns); + phases[i] = plan.outputs[i].phase; + } + return plan.count; +} + +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { + std::lock_guard lock(g_pacer_mutex); + if (issue_ns > 0 && done_ns > issue_ns) + g_readiness.ObserveCompleted(static_cast(issue_ns), static_cast(done_ns)); +} + +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { + std::lock_guard lock(g_pacer_mutex); + if (planned_ns > 0 && shown_ns > 0) + g_pacer.ObserveRealShown(static_cast(planned_ns), static_cast(shown_ns)); +} + +void fge_pacer_reset(void) { + std::lock_guard lock(g_pacer_mutex); + g_pacer.Reset(); +} + void fge_forget_targets(void) { + if (g_kind == 2) { zfg_forget_targets(); return; } if (g_lsfg) g_lsfg->forgetTargets(); } @@ -266,10 +388,14 @@ void fge_telemetry(float *accepted, float *source_rate, float *thermal) { *accepted = (float)g_lsfg->acceptedGenerations(); *source_rate = g_lsfg->sourceRate(); *thermal = (float)g_lsfg->thermalStatus(); + } else if (g_kind == 2) { + zfg_telemetry(accepted, source_rate); } } -const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } +const char *fge_engine_name(int kind) { + return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; +} const char *fge_build_info(void) { return g_build; } } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine.h b/app/src/main/cpp/waylandcomp/src/framegen_engine.h index d52ce3ffd4..8295a930f3 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine.h +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine.h @@ -16,8 +16,9 @@ void fge_device_lost(void); void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysicalDevice pd, VkDevice dev, VkQueue queue, uint32_t qfam, int features_enabled); int fge_caps_ok(int kind); -const char *fge_caps_reason(void); -int fge_format_ok(VkFormat fmt); +const char *fge_caps_reason(int kind); +int fge_format_ok(int kind, VkFormat fmt); +int fge_engine_available(int kind); int fge_start(int kind, const char *cache_path); void fge_stop(void); @@ -26,10 +27,22 @@ void fge_configure(uint32_t multiplier, uint32_t target_fps, float flow_scale, f int model, int perf_preset); int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt); uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate); -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens); +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t w, uint32_t h, VkFormat fmt, uint64_t sequence, uint32_t gens); void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h); void fge_forget_targets(void); +void fge_set_layer_timing(int layer); +/* The phases the pacer chose for the next pair's generated frames (engines that can take any phase). */ +void fge_set_phases(const float *phases, uint32_t count); +/* The phase generated frame [index] of [count] shows. */ +float fge_phase(uint32_t index, uint32_t count); + +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases); +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns); +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns); +void fge_pacer_reset(void); void fge_telemetry(float *accepted, float *source_rate, float *thermal); const char *fge_engine_name(int kind); const char *fge_build_info(void); diff --git a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c index 3d11228577..6dcf3a8d5b 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_engine_stub.c @@ -10,9 +10,12 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica (void)gipa; (void)inst; (void)pd; (void)dev; (void)queue; (void)qfam; (void)features_enabled; } void fge_device_lost(void) {} +void zfg_discard_history_update(void) {} +void zfg_commit_history_update(void) {} int fge_caps_ok(int kind) { (void)kind; return 0; } -const char *fge_caps_reason(void) { return "frame-generation engines not built into this compositor"; } -int fge_format_ok(VkFormat fmt) { (void)fmt; return 0; } +const char *fge_caps_reason(int kind) { (void)kind; return "frame-generation engines not built into this compositor"; } +int fge_format_ok(int kind, VkFormat fmt) { (void)kind; (void)fmt; return 0; } +int fge_engine_available(int kind) { (void)kind; return 0; } int fge_start(int kind, const char *cache_path) { (void)kind; (void)cache_path; return -1; } void fge_stop(void) {} int fge_unavailable(void) { return 1; } @@ -24,16 +27,28 @@ int fge_prepare(uint32_t w, uint32_t h, VkFormat fmt) { (void)w; (void)h; (void) uint32_t fge_plan(uint32_t capacity, uint64_t source_frames, float presented_rate) { (void)capacity; (void)source_frames; (void)presented_rate; return 0; } -void fge_process(VkCommandBuffer cmd, VkImage source, uint32_t w, uint32_t h, uint32_t gens) { - (void)cmd; (void)source; (void)w; (void)h; (void)gens; +void fge_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, uint32_t w, uint32_t h, + VkFormat fmt, uint64_t sequence, uint32_t gens) { + (void)cmd; (void)source; (void)source_view; (void)w; (void)h; (void)fmt; (void)sequence; (void)gens; } void fge_generate(VkCommandBuffer cmd, uint32_t g, uint32_t count, VkImage img, VkImageView view, uint32_t w, uint32_t h) { (void)cmd; (void)g; (void)count; (void)img; (void)view; (void)w; (void)h; } void fge_forget_targets(void) {} +void fge_set_layer_timing(int layer) { (void)layer; } +void fge_set_phases(const float *phases, uint32_t count) { (void)phases; (void)count; } +float fge_phase(uint32_t index, uint32_t count) { return (float)(index + 1) / (float)(count + 1); } +uint32_t fge_pacer_plan(uint32_t multiplier, int64_t period_ns, int64_t vsync_ns, int64_t issue_ns, uint32_t max_generated, + int64_t *present_ns, float *phases) { + (void)multiplier; (void)period_ns; (void)vsync_ns; (void)issue_ns; (void)max_generated; (void)present_ns; (void)phases; + return 0; +} +void fge_pacer_completed(int64_t issue_ns, int64_t done_ns) { (void)issue_ns; (void)done_ns; } +void fge_pacer_shown(int64_t planned_ns, int64_t shown_ns) { (void)planned_ns; (void)shown_ns; } +void fge_pacer_reset(void) {} void fge_telemetry(float *accepted, float *source_rate, float *thermal) { *accepted = 0.0f; *source_rate = 0.0f; *thermal = -1.0f; } -const char *fge_engine_name(int kind) { return kind == 1 ? "DD-FG Native" : "LSFG Native"; } +const char *fge_engine_name(int kind) { return kind == 2 ? "ZeroFG" : kind == 1 ? "DD-FG Native" : "LSFG Native"; } const char *fge_build_info(void) { return "stub"; } diff --git a/app/src/main/cpp/waylandcomp/src/framegen_jni.c b/app/src/main/cpp/waylandcomp/src/framegen_jni.c index e5a51456ed..e210597b8f 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_jni.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_jni.c @@ -14,6 +14,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenArmed(JNI vkp_framegen_set_armed(armed ? 1 : 0, (int)multiplier, (int)targetFps); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFrameGenPacer(JNIEnv *env, jclass clazz, jboolean on) { + (void)env; (void)clazz; + vkp_framegen_set_pacer(on ? 1 : 0); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLsfgCachePath(JNIEnv *env, jclass clazz, jstring path) { (void)clazz; diff --git a/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp new file mode 100644 index 0000000000..786c830964 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.cpp @@ -0,0 +1,602 @@ +#include "framegen_zerofg.h" +#include "sc_layer.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#define ZFG_LOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__) +#define ZFG_ERR(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "ZeroFG: " __VA_ARGS__) + +namespace { +PFN_vkGetInstanceProcAddr g_gipa = nullptr; +PFN_vkGetDeviceProcAddr g_gdpa = nullptr; +VkInstance g_instance = VK_NULL_HANDLE; +VkPhysicalDevice g_physical = VK_NULL_HANDLE; +VkDevice g_device = VK_NULL_HANDLE; +uint32_t g_api_version = VK_API_VERSION_1_0; +bool g_synchronization2 = false, g_extended_formats = false; +bool g_ready = false, g_supported = false, g_failed = false; +char g_reason[160] = "device has not been checked"; + +PFN_vkGetPhysicalDeviceMemoryProperties g_GetPhysicalDeviceMemoryProperties = nullptr; +PFN_vkGetPhysicalDeviceFormatProperties g_GetPhysicalDeviceFormatProperties = nullptr; +PFN_vkCreateImage g_CreateImage = nullptr; +PFN_vkDestroyImage g_DestroyImage = nullptr; +PFN_vkCreateImageView g_CreateImageView = nullptr; +PFN_vkDestroyImageView g_DestroyImageView = nullptr; +PFN_vkGetImageMemoryRequirements g_GetImageMemoryRequirements = nullptr; +PFN_vkAllocateMemory g_AllocateMemory = nullptr; +PFN_vkFreeMemory g_FreeMemory = nullptr; +PFN_vkBindImageMemory g_BindImageMemory = nullptr; +PFN_vkCmdPipelineBarrier g_CmdPipelineBarrier = nullptr; +PFN_vkCmdCopyImage g_CmdCopyImage = nullptr; +PFN_vkDeviceWaitIdle g_DeviceWaitIdle = nullptr; +VkPhysicalDeviceMemoryProperties g_memory_properties{}; + +std::unique_ptr g_interpolator; +VkImage g_history = VK_NULL_HANDLE; +VkImageView g_history_view = VK_NULL_HANDLE; +VkDeviceMemory g_history_memory = VK_NULL_HANDLE; +uint32_t g_width = 0, g_height = 0; +VkFormat g_format = VK_FORMAT_UNDEFINED; +bool g_history_layout_defined = false, g_history_valid = false; +uint64_t g_history_sequence = 0; +bool g_history_recorded_pending = false; +uint64_t g_history_recorded_sequence = 0; +std::array g_fallback_outputs{}; +VkImage g_current = VK_NULL_HANDLE; +VkImageView g_current_view = VK_NULL_HANDLE; +uint64_t g_current_sequence = 0; +bool g_pair_pending = false; + +// Pacing. The compositor presents a pair's generated frames and its real frame back to back in FIFO, +// so they reach the panel on consecutive refreshes right after the tick that drew them. +constexpr uint64_t kBreakNs = 250000000ull; +constexpr size_t kIntervalWindow = 8; +constexpr size_t kMinIntervals = 4; +constexpr double kSlotTolerance = 0.15; +uint32_t g_multiplier = 2; +float g_refresh_hz = 0.0f; +bool g_layer_timing = false; +// The phases the pacer chose for this pair (count 0: none, the timing above decides). +std::array g_external_phases{}; +uint32_t g_external_count = 0; +uint64_t g_last_sequence = 0; +uint64_t g_last_issue_ns = 0; +uint64_t g_pair_interval_ns = 0; +uint32_t g_prev_count = 0, g_pair_count = 0; +std::array g_intervals{}; +size_t g_interval_count = 0, g_interval_next = 0; + +uint64_t now_ns() { + return static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count()); +} + +void reset_pacing() { + g_last_issue_ns = 0; + g_pair_interval_ns = 0; + g_prev_count = g_pair_count = 0; + g_interval_count = g_interval_next = 0; +} + +uint64_t period_ns() { + return g_refresh_hz > 1.0f ? static_cast(1e9 / static_cast(g_refresh_hz)) : 0; +} + +uint64_t typical_interval_ns() { + if (g_interval_count < kMinIntervals) return 0; + std::array sorted = g_intervals; + std::sort(sorted.begin(), sorted.begin() + g_interval_count); + return sorted[g_interval_count / 2]; +} + +void note_sequence(uint64_t sequence) { + if (sequence == g_last_sequence) return; + const uint64_t now = now_ns(); + if (sequence < g_last_sequence) { + // The frame counter changed source (game frames vs compositor scenes): no pair across it. + g_history_valid = false; + g_history_sequence = 0; + reset_pacing(); + } else if (g_last_issue_ns && now > g_last_issue_ns) { + const uint64_t interval = now - g_last_issue_ns; + if (interval > kBreakNs) { + reset_pacing(); + } else { + g_pair_interval_ns = interval; + g_intervals[g_interval_next] = interval; + g_interval_next = (g_interval_next + 1) % kIntervalWindow; + g_interval_count = std::min(g_interval_count + 1, kIntervalWindow); + } + } + g_last_sequence = sequence; + g_last_issue_ns = now; +} + +// Generated frames a pair can show without its presents queueing past the next game frame: +// one refresh each, the real frame one more, all inside the game's typical frame interval. +uint32_t pair_capacity(uint32_t wanted) { + const uint64_t period = period_ns(); + const uint64_t typical = typical_interval_ns(); + if (!period || !typical) return wanted; + const double slots = std::floor(static_cast(typical) / static_cast(period) + kSlotTolerance); + return slots < 2.0 ? 0u : std::min(wanted, static_cast(slots) - 1u); +} + +// The scene layer (sc_layer.c) shows a group of [count] generated frames and then B, frame k of the group +// max(k, round(k * gap / (count + 1))) refreshes after the first, a group every game frame interval. +float layer_phase(uint32_t index, uint32_t count, uint64_t period) { + const float even = static_cast(index + 1) / static_cast(count + 1); + int64_t cadence_gap = 0; + int cadence_frames = 0; + sc_layer_cadence_info(&cadence_gap, &cadence_frames); + const uint64_t gap = cadence_gap > 0 ? static_cast(cadence_gap) : typical_interval_ns(); + const uint32_t group_frames = cadence_frames > static_cast(count) + ? static_cast(cadence_frames) : count + 1; + if (!gap) return even; + const int64_t slots = static_cast((gap + period / 2) / period); + if (slots < static_cast(group_frames)) return even; + const auto step = [&](uint32_t k) { + const int64_t s = static_cast((static_cast(k) * gap / group_frames + period / 2) / period); + return std::max(s, k); + }; + const double phase = static_cast(step(index) - step(count) + slots) / static_cast(slots); + return static_cast(std::clamp(phase, 0.05, 0.95)); +} + +// FIFO presents the generated group and B back-to-back; phase uses the measured real-frame span. +float pair_phase(uint32_t index, uint32_t count) { + if (g_external_count == count && index < count) return std::clamp(g_external_phases[index], 0.01f, 0.99f); + const float even = static_cast(index + 1) / static_cast(count + 1); + const uint64_t period = period_ns(); + if (!period) return even; + if (g_layer_timing) return layer_phase(index, count, period); + if (!g_pair_interval_ns) return even; + const double span = static_cast(g_pair_interval_ns) + + (static_cast(count) - static_cast(g_prev_count)) * static_cast(period); + if (span <= static_cast(period) * (count + 1)) return even; + const double phase = 1.0 - static_cast(count - index) * static_cast(period) / span; + return static_cast(std::clamp(phase, 0.05, 0.95)); +} + +void load_device_functions() { + if (g_gipa && g_instance) { + g_GetPhysicalDeviceMemoryProperties = + reinterpret_cast( + g_gipa(g_instance, "vkGetPhysicalDeviceMemoryProperties")); + g_GetPhysicalDeviceFormatProperties = + reinterpret_cast( + g_gipa(g_instance, "vkGetPhysicalDeviceFormatProperties")); + } + if (!g_gdpa || !g_device) return; +#define LOAD(name) g_##name = reinterpret_cast(g_gdpa(g_device, "vk" #name)) + LOAD(CreateImage); + LOAD(DestroyImage); + LOAD(CreateImageView); + LOAD(DestroyImageView); + LOAD(GetImageMemoryRequirements); + LOAD(AllocateMemory); + LOAD(FreeMemory); + LOAD(BindImageMemory); + LOAD(CmdPipelineBarrier); + LOAD(CmdCopyImage); + LOAD(DeviceWaitIdle); +#undef LOAD +} + +void clear_history_state() { + g_history_valid = false; + g_history_sequence = 0; + g_pair_pending = false; + g_current = VK_NULL_HANDLE; + g_current_view = VK_NULL_HANDLE; + g_current_sequence = 0; +} + +void destroy_history() { + if (g_device) { + if (g_history_view && g_DestroyImageView) g_DestroyImageView(g_device, g_history_view, nullptr); + if (g_history && g_DestroyImage) g_DestroyImage(g_device, g_history, nullptr); + if (g_history_memory && g_FreeMemory) g_FreeMemory(g_device, g_history_memory, nullptr); + } + g_history = VK_NULL_HANDLE; + g_history_view = VK_NULL_HANDLE; + g_history_memory = VK_NULL_HANDLE; + g_width = g_height = 0; + g_format = VK_FORMAT_UNDEFINED; + g_history_layout_defined = false; + clear_history_state(); +} + +uint32_t find_memory_type(uint32_t bits) { + uint32_t fallback = UINT32_MAX; + for (uint32_t i = 0; i < g_memory_properties.memoryTypeCount; ++i) { + if ((bits & (1u << i)) == 0) continue; + const auto flags = g_memory_properties.memoryTypes[i].propertyFlags; + if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) return i; + if (fallback == UINT32_MAX) fallback = i; + } + return fallback; +} + +bool make_history(uint32_t width, uint32_t height, VkFormat format) { + if (!g_CreateImage || !g_GetImageMemoryRequirements || !g_AllocateMemory || + !g_BindImageMemory || !g_CreateImageView || !g_GetPhysicalDeviceMemoryProperties) { + std::snprintf(g_reason, sizeof(g_reason), "Vulkan image functions unavailable"); + return false; + } + VkImageCreateInfo image_info{}; + image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + image_info.imageType = VK_IMAGE_TYPE_2D; + image_info.format = format; + image_info.extent = {width, height, 1}; + image_info.mipLevels = 1; + image_info.arrayLayers = 1; + image_info.samples = VK_SAMPLE_COUNT_1_BIT; + image_info.tiling = VK_IMAGE_TILING_OPTIMAL; + image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + if (g_CreateImage(g_device, &image_info, nullptr, &g_history) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history image"); + return false; + } + + VkMemoryRequirements requirements{}; + g_GetImageMemoryRequirements(g_device, g_history, &requirements); + const uint32_t memory_index = find_memory_type(requirements.memoryTypeBits); + if (memory_index == UINT32_MAX) { + std::snprintf(g_reason, sizeof(g_reason), "no compatible memory for temporal history"); + destroy_history(); + return false; + } + VkMemoryAllocateInfo allocation{}; + allocation.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + allocation.allocationSize = requirements.size; + allocation.memoryTypeIndex = memory_index; + if (g_AllocateMemory(g_device, &allocation, nullptr, &g_history_memory) != VK_SUCCESS || + g_BindImageMemory(g_device, g_history, g_history_memory, 0) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not allocate temporal history memory"); + destroy_history(); + return false; + } + + VkImageViewCreateInfo view_info{}; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.image = g_history; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = format; + view_info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + if (g_CreateImageView(g_device, &view_info, nullptr, &g_history_view) != VK_SUCCESS) { + std::snprintf(g_reason, sizeof(g_reason), "could not create temporal history view"); + destroy_history(); + return false; + } + g_width = width; + g_height = height; + g_format = format; + g_history_layout_defined = false; + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; + clear_history_state(); + return true; +} + +void copy_current_to_history(VkCommandBuffer cmd, VkImage source, + uint32_t width, uint32_t height, uint64_t sequence) { + if (!g_history || !source || !g_CmdPipelineBarrier || !g_CmdCopyImage) return; + VkImageMemoryBarrier before{}; + before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + const bool layout_defined = g_history_layout_defined || g_history_recorded_pending; + before.srcAccessMask = layout_defined ? VK_ACCESS_SHADER_READ_BIT : 0; + before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + before.oldLayout = layout_defined ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_UNDEFINED; + before.newLayout = VK_IMAGE_LAYOUT_GENERAL; + before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.image = g_history; + before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, + layout_defined ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &before); + + VkImageCopy region{}; + region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.extent = {width, height, 1}; + g_CmdCopyImage(cmd, source, VK_IMAGE_LAYOUT_GENERAL, g_history, VK_IMAGE_LAYOUT_GENERAL, 1, ®ion); + + VkImageMemoryBarrier after{}; + after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + after.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + after.newLayout = VK_IMAGE_LAYOUT_GENERAL; + after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.image = g_history; + after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &after); + g_history_recorded_pending = true; + g_history_recorded_sequence = sequence; + g_pair_pending = false; +} + +void copy_current_to_output(VkCommandBuffer cmd, VkImage output, uint32_t width, uint32_t height) { + if (!g_current || !output || !g_CmdPipelineBarrier || !g_CmdCopyImage) return; + VkImageMemoryBarrier before{}; + before.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + before.srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT | VK_ACCESS_SHADER_WRITE_BIT; + before.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + before.oldLayout = VK_IMAGE_LAYOUT_GENERAL; + before.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + before.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + before.image = output; + before.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, nullptr, 0, nullptr, 1, &before); + VkImageCopy region{}; + region.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + region.extent = {width, height, 1}; + g_CmdCopyImage(cmd, g_current, VK_IMAGE_LAYOUT_GENERAL, + output, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion); + VkImageMemoryBarrier after{}; + after.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + after.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + after.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_SHADER_READ_BIT; + after.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + after.newLayout = VK_IMAGE_LAYOUT_GENERAL; + after.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + after.image = output; + after.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + g_CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + 0, 0, nullptr, 0, nullptr, 1, &after); +} +} // namespace + +extern "C" { +void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, + VkPhysicalDevice physical_device, VkDevice device, + uint32_t api_version, int synchronization2_enabled, + int extended_storage_formats_enabled) { + g_gipa = gipa; + g_instance = instance; + g_physical = physical_device; + g_device = device; + g_api_version = api_version; + g_synchronization2 = synchronization2_enabled != 0; + g_extended_formats = extended_storage_formats_enabled != 0; + g_gdpa = g_gipa && g_instance + ? reinterpret_cast(g_gipa(g_instance, "vkGetDeviceProcAddr")) + : nullptr; + load_device_functions(); + if (g_GetPhysicalDeviceMemoryProperties && g_physical) + g_GetPhysicalDeviceMemoryProperties(g_physical, &g_memory_properties); + g_ready = g_device != VK_NULL_HANDLE; + g_supported = g_ready && g_api_version >= VK_API_VERSION_1_3 && + g_synchronization2 && g_extended_formats; + g_failed = false; + std::snprintf(g_reason, sizeof(g_reason), "%s", g_supported ? "available" : + "requires Vulkan 1.3, synchronization2 and shaderStorageImageExtendedFormats"); +} + +void zfg_device_lost(void) { + g_interpolator.reset(); + destroy_history(); + g_gipa = nullptr; g_gdpa = nullptr; + g_instance = VK_NULL_HANDLE; g_physical = VK_NULL_HANDLE; g_device = VK_NULL_HANDLE; + g_ready = g_supported = g_failed = false; + g_synchronization2 = g_extended_formats = false; + g_api_version = VK_API_VERSION_1_0; + g_GetPhysicalDeviceMemoryProperties = nullptr; + g_GetPhysicalDeviceFormatProperties = nullptr; + g_CreateImage = nullptr; g_DestroyImage = nullptr; + g_CreateImageView = nullptr; g_DestroyImageView = nullptr; + g_GetImageMemoryRequirements = nullptr; g_AllocateMemory = nullptr; + g_FreeMemory = nullptr; g_BindImageMemory = nullptr; + g_CmdPipelineBarrier = nullptr; g_CmdCopyImage = nullptr; g_DeviceWaitIdle = nullptr; + g_memory_properties = {}; + std::snprintf(g_reason, sizeof(g_reason), "device lost"); +} + +int zfg_caps_ok(void) { return g_supported ? 1 : 0; } +const char *zfg_caps_reason(void) { return g_reason; } + +int zfg_start(void) { + if (!g_supported || !g_ready) return 0; + if (g_interpolator) return 1; + zerofg::CreateInfo info{}; + info.vulkan.instance = g_instance; + info.vulkan.physical_device = g_physical; + info.vulkan.device = g_device; + info.vulkan.get_instance_proc_addr = g_gipa; + info.mode = zerofg::Mode::kReallyZero; + info.backend = zerofg::Backend::kCompat; + info.frame_context_count = 4; + info.capabilities.effective_api_version = g_api_version; + info.capabilities.synchronization2_enabled = g_synchronization2; + info.capabilities.shader_storage_image_extended_formats_enabled = g_extended_formats; + zerofg::Status status = zerofg::Status::kSuccess; + g_interpolator = zerofg::Interpolator::Create(info, &status); + if (!g_interpolator) { + std::snprintf(g_reason, sizeof(g_reason), "interpolator creation failed (%d)", (int)status); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + g_failed = false; + ZFG_LOG("ReallyZero engine ready (Compat backend)"); + return 1; +} + +void zfg_stop(void) { + g_interpolator.reset(); + destroy_history(); + reset_pacing(); + g_last_sequence = 0; + g_failed = false; +} +int zfg_unavailable(void) { return g_failed || !g_interpolator ? 1 : 0; } + +int zfg_format_ok(VkFormat format) { + if (!g_supported || !g_GetPhysicalDeviceFormatProperties || format == VK_FORMAT_UNDEFINED) return 0; + VkFormatProperties input{}; + g_GetPhysicalDeviceFormatProperties(g_physical, format, &input); + const VkFormatFeatureFlags sampled = + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; + if ((input.optimalTilingFeatures & sampled) != sampled) return 0; + if (format == VK_FORMAT_A2B10G10R10_UNORM_PACK32) + return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) != 0; + VkFormatProperties internal{}; + g_GetPhysicalDeviceFormatProperties(g_physical, VK_FORMAT_A2B10G10R10_UNORM_PACK32, &internal); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_BLIT_SRC_BIT; + return (input.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT) != 0 && + (internal.optimalTilingFeatures & needed) == needed; +} + +int zfg_prepare(uint32_t width, uint32_t height, VkFormat format) { + if (!g_interpolator || g_failed || !width || !height) return 0; + if (!zfg_format_ok(format)) { + std::snprintf(g_reason, sizeof(g_reason), "unsupported input/output format %d", (int)format); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + if (g_width == width && g_height == height && g_format == format && g_history) return 1; + if (g_DeviceWaitIdle) g_DeviceWaitIdle(g_device); + destroy_history(); + const zerofg::Status resized = g_interpolator->Resize(width, height, format, format); + if (resized != zerofg::Status::kSuccess) { + std::snprintf(g_reason, sizeof(g_reason), "resize failed (%d)", (int)resized); + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + if (!make_history(width, height, format)) { + g_failed = true; + ZFG_ERR("%s", g_reason); + return 0; + } + ZFG_LOG("prepared %ux%u format %d", width, height, (int)format); + return 1; +} + +void zfg_configure(uint32_t multiplier, float refresh_hz) { + g_multiplier = std::clamp(multiplier, 2, 4); + g_refresh_hz = refresh_hz > 1.0f ? refresh_hz : 0.0f; +} + +void zfg_set_layer_timing(int layer) { g_layer_timing = layer != 0; } + +void zfg_set_phases(const float *phases, uint32_t count) { + g_external_count = phases ? std::min(count, static_cast(g_external_phases.size())) : 0; + for (uint32_t i = 0; i < g_external_count; i++) g_external_phases[i] = phases[i]; +} + +float zfg_phase(uint32_t index, uint32_t count) { return pair_phase(index, count); } + +uint32_t zfg_plan(uint32_t capacity, uint64_t sequence) { + if (!g_interpolator || g_failed) return 0; + note_sequence(sequence); + if (!g_history_valid || sequence <= g_history_sequence || !g_pair_interval_ns) return 0; + return pair_capacity(std::min({capacity, 3u, g_multiplier - 1})); +} + +void zfg_telemetry(float *generated, float *source_rate) { + const uint64_t typical = typical_interval_ns(); + *generated = static_cast(g_pair_count); + *source_rate = typical ? static_cast(1e9 / static_cast(typical)) : 0.0f; +} + +void zfg_process(VkCommandBuffer cmd, VkImage source, VkImageView source_view, + uint32_t width, uint32_t height, VkFormat format, + uint64_t sequence, uint32_t generations) { + g_pair_pending = false; + g_fallback_outputs.fill(false); + if (!g_interpolator || g_failed || !source || !g_history || + format != g_format || width != g_width || height != g_height) return; + if (sequence > g_history_sequence) { + g_prev_count = g_pair_count; + g_pair_count = generations; + } + if (generations == 0 || !g_history_valid || sequence <= g_history_sequence) { + copy_current_to_history(cmd, source, width, height, sequence); + return; + } + if (!source_view) return; + g_current = source; + g_current_view = source_view; + g_current_sequence = sequence; + g_pair_pending = true; +} + +void zfg_generate(VkCommandBuffer cmd, uint32_t index, uint32_t count, + VkImage output, VkImageView output_view, uint32_t width, uint32_t height) { + if (!g_pair_pending || !g_interpolator || !g_history_valid || index >= count || !output || !output_view) return; + const float phase = pair_phase(index, count); + zerofg::Image previous{}; + previous.image = g_history; previous.view = g_history_view; + previous.layout = VK_IMAGE_LAYOUT_GENERAL; previous.format = g_format; + previous.width = g_width; previous.height = g_height; + previous.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + previous.sequence = g_history_sequence; + zerofg::Image current{}; + current.image = g_current; current.view = g_current_view; + current.layout = VK_IMAGE_LAYOUT_GENERAL; current.format = g_format; + current.width = g_width; current.height = g_height; + current.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + current.sequence = g_current_sequence; + zerofg::Image result{}; + result.image = output; result.view = output_view; + result.layout = VK_IMAGE_LAYOUT_GENERAL; result.format = g_format; + result.width = width; result.height = height; + result.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + + const zerofg::Status status = + g_interpolator->Interpolate(cmd, index, previous, current, phase, result); + if (status != zerofg::Status::kSuccess) { + ZFG_ERR("interpolation status %d; copying the real frame as fallback", (int)status); + g_fallback_outputs[index] = true; + copy_current_to_output(cmd, output, width, height); + } + if (index + 1 >= count) { + copy_current_to_history(cmd, g_current, width, height, g_current_sequence); + g_pair_pending = false; + } +} + +void zfg_commit_history_update(void) { + if (!g_history_recorded_pending) return; + g_history_layout_defined = true; + g_history_valid = true; + g_history_sequence = g_history_recorded_sequence; + g_history_recorded_pending = false; +} + +void zfg_discard_history_update(void) { + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; +} + +void zfg_forget_targets(void) { + g_pair_pending = false; + g_history_recorded_pending = false; + g_history_recorded_sequence = 0; + g_history_valid = false; + g_history_sequence = 0; + reset_pacing(); +} +} // extern "C" diff --git a/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h new file mode 100644 index 0000000000..83c9c39e24 --- /dev/null +++ b/app/src/main/cpp/waylandcomp/src/framegen_zerofg.h @@ -0,0 +1,38 @@ +#ifndef FRAMEGEN_ZEROFG_H +#define FRAMEGEN_ZEROFG_H +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +void zfg_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, + VkPhysicalDevice physical_device, VkDevice device, + uint32_t api_version, int synchronization2_enabled, + int extended_storage_formats_enabled); +void zfg_device_lost(void); +int zfg_caps_ok(void); +const char *zfg_caps_reason(void); +int zfg_start(void); +void zfg_stop(void); +int zfg_unavailable(void); +int zfg_format_ok(VkFormat format); +int zfg_prepare(uint32_t width, uint32_t height, VkFormat format); +void zfg_configure(uint32_t multiplier, float refresh_hz); +void zfg_set_layer_timing(int layer); +void zfg_set_phases(const float *phases, uint32_t count); +float zfg_phase(uint32_t index, uint32_t count); +uint32_t zfg_plan(uint32_t capacity, uint64_t sequence); +void zfg_telemetry(float *generated, float *source_rate); +void zfg_process(VkCommandBuffer command_buffer, VkImage source, VkImageView source_view, + uint32_t width, uint32_t height, VkFormat format, + uint64_t sequence, uint32_t generations); +void zfg_generate(VkCommandBuffer command_buffer, uint32_t index, uint32_t count, + VkImage output, VkImageView output_view, + uint32_t width, uint32_t height); +void zfg_forget_targets(void); +void zfg_commit_history_update(void); +void zfg_discard_history_update(void); +#ifdef __cplusplus +} +#endif +#endif diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.c b/app/src/main/cpp/waylandcomp/src/sc_layer.c index 3093feb28e..d38cc7ede5 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.c +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.c @@ -58,6 +58,7 @@ static struct { void (*reparent)(ASurfaceTransaction *, ASurfaceControl *, ASurfaceControl *); void (*setOnComplete)(ASurfaceTransaction *, void *, sc_complete_fn); int (*prevReleaseFence)(ASurfaceTransactionStats *, ASurfaceControl *); + int (*presentFence)(ASurfaceTransactionStats *); void (*setFrameRate)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t); void (*setFrameRateStrategy)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t, int8_t); void (*setBufferDataSpace)(ASurfaceTransaction *, ASurfaceControl *, int32_t); @@ -102,6 +103,7 @@ static int load_api(void) { SYM(reparent, "ASurfaceTransaction_reparent"); SYM(setOnComplete, "ASurfaceTransaction_setOnComplete"); SYM(prevReleaseFence, "ASurfaceTransactionStats_getPreviousReleaseFenceFd"); + SYM(presentFence, "ASurfaceTransactionStats_getPresentFenceFd"); SYM(setFrameRate, "ASurfaceTransaction_setFrameRate"); SYM(setFrameRateStrategy, "ASurfaceTransaction_setFrameRateWithChangeStrategy"); SYM(setBufferDataSpace, "ASurfaceTransaction_setBufferDataSpace"); @@ -265,7 +267,33 @@ static int64_t cadence_target(int64_t now, int64_t earliest, int64_t period) { return target; } +static int64_t g_planned_next_ns; + +void sc_layer_set_planned(int64_t present_ns) { + pthread_mutex_lock(&g_lock); + g_planned_next_ns = present_ns; + pthread_mutex_unlock(&g_lock); +} + +void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns) { + pthread_mutex_lock(&g_timeline_lock); + *present_ns = g_timeline_present_ns; + *period_ns = g_timeline_period_ns; + pthread_mutex_unlock(&g_timeline_lock); +} + +void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames) { + if (gap_ns) *gap_ns = g_cadence_gap_ns; + if (group_frames) *group_frames = g_group_frames; +} + static void apply_present_time(ASurfaceTransaction *tx, int game) { + pthread_mutex_lock(&g_lock); + const int64_t planned = game ? g_planned_next_ns : 0; + if (game) { + g_planned_next_ns = 0; + } + pthread_mutex_unlock(&g_lock); if (!api.setDesiredPresentTime) return; pthread_mutex_lock(&g_timeline_lock); const int64_t present = g_timeline_present_ns, deadline = g_timeline_deadline_ns, period = g_timeline_period_ns; @@ -285,6 +313,9 @@ static void apply_present_time(ASurfaceTransaction *tx, int game) { target = cadence_target(now, target, period); } if (game && g_group_frames > 1 && ++g_group_index >= g_group_frames) { g_group_index = 0; g_group_frames = 1; } + if (planned > 0) { + target = planned; + } api.setDesiredPresentTime(tx, target - period / 2); } @@ -893,7 +924,9 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct d int translucent) { struct slot *s = &l->slots[idx]; ASurfaceTransaction *tx = api.txCreate(); - if (!tx) return -1; + if (!tx) { + return -1; + } const int was_shown = l->shown; const int32_t ds_applied = l->ds_applied; const uint32_t md_applied = l->md_applied; @@ -1114,7 +1147,7 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (!mapped) { vkp_pass_abort(); sc_layer_hide(); return 0; } idx[VKP_FG_MAX_GENERATIONS] = deep ? take_hdr_slot(l, rw, rh, &first_fd) : take_free_slot(l, rw, rh, AHB_RGBA8, &first_fd); - if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } + if (idx[VKP_FG_MAX_GENERATIONS] < 0) { vkp_pass_abort(); vkp_framegen_pacer_abort(); log_drop(l); return g_alloc_failed ? -1 : 0; } pthread_mutex_lock(&g_lock); l->slots[idx[VKP_FG_MAX_GENERATIONS]].busy = 1; pthread_mutex_unlock(&g_lock); @@ -1136,13 +1169,18 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const if (!have_fd) { first_fd = fd; have_fd = 1; } } if (vkp_pass_copy_generated(dst, m, real, first_fd) != 0) { + vkp_framegen_pacer_abort(); slots_idle(l, idx, 0, m); if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); return -1; } g_group_frames = m + 1; for (int k = 0; k < m; k++) { + int64_t planned; + vkp_framegen_output_planned(k, m, &planned); + sc_layer_set_planned(planned); if (present_slot(l, idx[k], r, color, 0) == 0) continue; + vkp_framegen_pacer_abort(); slots_idle(l, idx, k, m); if (real) slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); g_group_index = 0; @@ -1151,7 +1189,11 @@ int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws, const } vkp_framegen_presented(m); if (real) { + int64_t planned; + vkp_framegen_output_planned(m, m, &planned); + sc_layer_set_planned(planned); if (present_slot(l, idx[VKP_FG_MAX_GENERATIONS], r, color, 0) != 0) { + vkp_framegen_pacer_abort(); slots_idle(l, idx, VKP_FG_MAX_GENERATIONS, VKP_FG_MAX_GENERATIONS + 1); g_group_index = 0; g_group_frames = 1; diff --git a/app/src/main/cpp/waylandcomp/src/sc_layer.h b/app/src/main/cpp/waylandcomp/src/sc_layer.h index b6ecead4a4..a7977378fa 100644 --- a/app/src/main/cpp/waylandcomp/src/sc_layer.h +++ b/app/src/main/cpp/waylandcomp/src/sc_layer.h @@ -4,6 +4,10 @@ #include #include +#ifdef __cplusplus +extern "C" { +#endif + struct vkp_image; struct vkp_draw; struct droiddeck_color; @@ -51,7 +55,16 @@ void sc_layer_window_gone(void); void sc_layer_frame_timeline(int64_t present_ns, int64_t deadline_ns, int64_t period_ns); void sc_layer_aim_take(unsigned *next, unsigned *later, unsigned *even); +/* The refresh the next game-layer frame is timed for, instead of the layer's own spacing (0: the layer's). */ +void sc_layer_set_planned(int64_t present_ns); +/* The display's frame timeline: the next expected present and the refresh period (0 until known). */ +void sc_layer_timeline(int64_t *present_ns, int64_t *period_ns); +void sc_layer_cadence_info(int64_t *gap_ns, int *group_frames); unsigned sc_layer_frames_take(void); unsigned sc_layer_drops_take(void); +#ifdef __cplusplus +} +#endif + #endif diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 909eb830d8..ab0d50bea6 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -7,6 +7,7 @@ #include "effects_chain.h" #include "cardboard.h" #include "framegen_bridge.h" +#include "framegen_zerofg.h" #include "hdr_compose.h" #include "blend_pass.h" #include "gpu_busy.h" @@ -2899,6 +2900,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (!(pass && fx)) release_external_client_draws(cmd, draws, n); int ngen = 0; + int history_staged = 0; VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE}; VkImage result = scene_img; int rw = input_w, rh = input_h; @@ -2937,6 +2939,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i 0, 0, NULL, 0, NULL, 1, &b_general); if (fg) { + vkp_framegen_set_layer_timing(0); + history_staged = 1; ngen = vkp_framegen_run(cmd, result, VK_NULL_HANDLE, rw, rh, scene_fmt, gens); if (ngen < 0) ngen = 0; if (ngen > VKP_FG_MAX_GENERATIONS) ngen = VKP_FG_MAX_GENERATIONS; @@ -2962,7 +2966,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i /* Teardown may have retained this frame's pending work, or * acquire may have reported real device loss. Neither permits * a completion-marker submit or another fence wait. */ - if (g_dev_state != 1) return -1; + if (g_dev_state != 1) { + if (history_staged) zfg_discard_history_update(); + return -1; + } droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents); pr = VK_ERROR_OUT_OF_DATE_KHR; break; @@ -2986,6 +2993,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i if (img >= g_rnd_count || !g_rnds[img]) { droiddeck_log("error", "present: image index %u exceeds semaphore count %u", img, g_rnd_count); + if (history_staged) zfg_discard_history_update(); destroy_swapchain(); return -1; } @@ -2994,12 +3002,17 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i .pCommandBuffers = &g_cmds[k], .signalSemaphoreCount = 1, .pSignalSemaphores = &g_rnds[img]}; VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, last ? g_fence : VK_NULL_HANDLE); if (qr != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); if (qr == VK_ERROR_DEVICE_LOST) device_lost("submit"); else LOGE("present: submit %d/%d failed (%d)", k + 1, presents, (int)qr); if (g_dev_state != -2) destroy_swapchain(); return -1; } fence_submitted = last; + if (k == 0 && history_staged) { + zfg_commit_history_update(); + history_staged = 0; + } VkPresentInfoKHR pi = {.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, .waitSemaphoreCount = 1, .pWaitSemaphores = &g_rnds[img], .swapchainCount = 1, .pSwapchains = &g_swapchain, .pImageIndices = &img}; @@ -3007,21 +3020,37 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i pr = g_vk.QueuePresentKHR(g_queue, &pi); perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres); if (k < ngen) presented_gen++; - if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; } + if (pr == VK_ERROR_DEVICE_LOST) { + if (history_staged) zfg_discard_history_update(); + device_lost("present"); + return -1; + } if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break; } if (!fence_submitted) { VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO}; VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence); if (marker != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit"); else quarantine_pending_work(marker, "frame completion submit"); return -1; /* no fence was submitted; never wait on its unsignalled state */ } + if (history_staged) { + zfg_discard_history_update(); + history_staged = 0; + } } VkResult fr = timed_wait(g_fence, UINT64_MAX); - if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; } - if (fr != VK_SUCCESS) return -1; + if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { + if (history_staged) zfg_discard_history_update(); + device_lost("present"); + return -1; + } + if (fr != VK_SUCCESS) { + if (history_staged) zfg_discard_history_update(); + return -1; + } vkp_effects_release_generated_sources(); if (fg) vkp_framegen_presented(presented_gen); if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) { @@ -3373,6 +3402,9 @@ static struct { int active; VkImage result; int rw, rh; + /* The layer buffers' size: rw x rh, or the spatial filter's output when it runs on each frame after generation. */ + int ow, oh; + int post_upscale; int ngen; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; @@ -3512,10 +3544,29 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw } int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); + g_pass.post_upscale = generate && !hf && vkp_effects_active() && vkp_effects_upscaling() && + vkp_effects_prepare_generated() && (mapped_w > input_w || mapped_h > input_h); + if (g_pass.post_upscale) { + static int last_input_w, last_input_h, last_output_w, last_output_h; + if (input_w != last_input_w || input_h != last_input_h || mapped_w != last_output_w || mapped_h != last_output_h) { + droiddeck_log("framegen", "post-upscale on the display layer: interpolate %dx%d, spatial filter each " + "frame to %dx%d", input_w, input_h, mapped_w, mapped_h); + last_input_w = input_w; last_input_h = input_h; + last_output_w = mapped_w; last_output_h = mapped_h; + } + } if (generate && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } g_pass.rw = input_w; g_pass.rh = input_h; - g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, - &g_pass.rw, &g_pass.rh); + if (g_pass.post_upscale) { + g_pass.ow = (int)(scene_w * g_map.kx + 0.5f); + g_pass.oh = (int)(scene_h * g_map.ky + 0.5f); + g_pass.result = vkp_effects_run_before_generated(cmd, scene_img, input_w, input_h, &g_pass.rw, &g_pass.rh); + } else { + g_pass.result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, + &g_pass.rw, &g_pass.rh); + g_pass.ow = g_pass.rw; + g_pass.oh = g_pass.rh; + } effects_overlay_draws(cmd, g_pass.result, g_pass.rw, g_pass.rh, scene_w, scene_h, draws ? draws + overlay_start : NULL, n - overlay_start); release_external_client_draws(cmd, draws, n); @@ -3530,38 +3581,45 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, &b); + vkp_framegen_set_layer_timing(1); int ngen = vkp_framegen_run(cmd, g_pass.result, VK_NULL_HANDLE, g_pass.rw, g_pass.rh, scene_fmt, g_pass.gens); if (ngen < 0) ngen = 0; g_pass.ngen = ngen > VKP_FG_MAX_GENERATIONS ? VKP_FG_MAX_GENERATIONS : ngen; } g_pass.active = 1; - if (rw) *rw = g_pass.rw; - if (rh) *rh = g_pass.rh; + if (rw) *rw = g_pass.ow; + if (rh) *rh = g_pass.oh; return 0; } static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp_image *const *dsts, int n, int wait_fd) { - if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; } + if (!g_pass.active) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; } g_pass.active = 0; - if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; } + if (g_dev_state != 1) { zfg_discard_history_update(); if (wait_fd >= 0) close(wait_fd); return -1; } VkCommandBuffer cmd = g_cmds[0]; for (int i = 0; i < n; i++) { if (dsts[i] && dsts[i]->blit_dst) continue; if (wait_fd >= 0) close(wait_fd); g_vk.EndCommandBuffer(cmd); + zfg_discard_history_update(); return -1; } const int gpu_wait = take_wait_fd(wait_fd); - if (gpu_wait < 0) { g_vk.EndCommandBuffer(cmd); return -1; } + if (gpu_wait < 0) { zfg_discard_history_update(); g_vk.EndCommandBuffer(cmd); return -1; } + const int post_upscale = g_pass.post_upscale && src_layout == VK_IMAGE_LAYOUT_GENERAL; for (int i = 0; i < n; i++) { struct vkp_image *dst = dsts[i]; + VkImage src = srcs[i]; + int sw = g_pass.rw, sh = g_pass.rh; + if (post_upscale) + src = vkp_effects_run_generated(cmd, src, g_pass.rw, g_pass.rh, g_pass.ow, g_pass.oh, i, &sw, &sh); VkImageBlit blit = {.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, - .srcOffsets = {{0, 0, 0}, {g_pass.rw, g_pass.rh, 1}}, + .srcOffsets = {{0, 0, 0}, {sw, sh, 1}}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstOffsets = {{0, 0, 0}, {dst->w, dst->h, 1}}}; - blit_to_layer(cmd, srcs[i], src_layout, dst, &blit, - (g_pass.rw == dst->w && g_pass.rh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); + blit_to_layer(cmd, src, src_layout, dst, &blit, + (sw == dst->w && sh == dst->h) ? VK_FILTER_NEAREST : VK_FILTER_LINEAR); } g_vk.EndCommandBuffer(cmd); @@ -3572,13 +3630,17 @@ static int pass_finish(const VkImage *srcs, VkImageLayout src_layout, struct vkp g_vk.ResetFences(g_dev, 1, &g_fence); VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence); if (qr != VK_SUCCESS) { + zfg_discard_history_update(); if (qr == VK_ERROR_DEVICE_LOST) device_lost("layer pass"); else LOGE("layer: effects pass submit failed (%d)", (int)qr); return -1; } + zfg_commit_history_update(); VkResult fr = timed_wait(g_fence, 1000000000ULL); if (fr == VK_ERROR_DEVICE_LOST) { device_lost("layer pass"); return -1; } if (fr != VK_SUCCESS) { LOGE("layer: effects pass fence wait -> %s", vk_result_name(fr)); return -1; } + if (post_upscale) vkp_effects_release_generated_sources(); + vkp_framegen_completed(); return 0; } @@ -3596,6 +3658,7 @@ int vkp_pass_copy_generated(struct vkp_image *const *dsts, int n, struct vkp_ima } void vkp_pass_abort(void) { + zfg_discard_history_update(); if (!g_pass.active) return; g_pass.active = 0; if (g_dev_state == 1) 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 9f08a424a1..2ae97cfc4f 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/FrameGen.kt @@ -10,11 +10,13 @@ object FrameGen { const val ENGINE_DDFG = "ddfg" private const val LEGACY_ENGINE_WINFG = "winfg" const val ENGINE_LSFG = "lsfg" + const val ENGINE_ZEROFG = "zerofg" private const val DDFG_PERF_PRESET = 2 private const val DDFG_MODEL = 4 private const val FLOW_SCALE_DDFG = 0.60f private const val FLOW_SCALE_LSFG = 0.80f + private const val FLOW_SCALE_ZEROFG = 1.0f val ADAPTIVE_TARGETS = listOf(120, 90, 60) @@ -69,6 +71,14 @@ object FrameGen { .putString("engine", mode.engine).putInt("multiplier", mode.multiplier).putInt("target", mode.target).apply() } + fun pacerEnabled(context: Context): Boolean = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean("pacer", false) + + fun setPacer(context: Context, enabled: Boolean) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("pacer", enabled).apply() + WaylandCompositor.nativeSetFrameGenPacer(enabled) + } + fun clearGlobal(context: Context) { context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() .remove("engine").remove("multiplier").remove("target").apply() @@ -80,6 +90,7 @@ object FrameGen { mode.engine == ENGINE_DDFG -> context.getString(R.string.frame_gen_ddfg, mode.multiplier) mode.engine == ENGINE_LSFG && mode.target > 0 -> context.getString(R.string.frame_gen_lsfg_adaptive, mode.target) mode.engine == ENGINE_LSFG -> context.getString(R.string.frame_gen_lsfg, mode.multiplier) + mode.engine == ENGINE_ZEROFG -> context.getString(R.string.frame_gen_zerofg, mode.multiplier) else -> context.getString(R.string.frame_gen_off) } @@ -104,6 +115,7 @@ object FrameGen { fun applyPrepared(context: Context, prepared: PreparedApply, refreshHz: Float): String? { val mode = prepared.mode + WaylandCompositor.nativeSetFrameGenPacer(pacerEnabled(context)) when (mode.engine) { ENGINE_LSFG -> { val status = prepared.lsfgStatus ?: LsfgNative.STATUS_NOT_INSTALLED @@ -127,6 +139,11 @@ object FrameGen { WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_DDFG, refreshHz) WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) } + ENGINE_ZEROFG -> { + WaylandCompositor.nativeSetFrameGenEngine(WaylandCompositor.FG_ENGINE_ZEROFG) + WaylandCompositor.nativeSetFrameGenTuning(FLOW_SCALE_ZEROFG, refreshHz) + WaylandCompositor.nativeSetFrameGenArmed(true, mode.multiplier, 0) + } else -> WaylandCompositor.nativeSetFrameGenArmed(false, 0, 0) } Log.i(TAG, "frame generation: $mode at ${refreshHz}Hz") 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 9e6667a28c..2c7ed785ea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -11,6 +11,10 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource @@ -29,18 +33,22 @@ internal fun FrameGenMenu( onResetGame: () -> Unit = {}, focusModifier: Modifier = Modifier, legacyButtons: Boolean = false, + listLayout: Boolean = false, ) { 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 - val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG") + val context = LocalContext.current + var pacerEnabled by remember { mutableStateOf(FrameGen.pacerEnabled(context)) } + val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG", FrameGen.ENGINE_ZEROFG to "ZeroFG") if (legacyButtons) { val context = LocalContext.current val options = buildList { add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) } + (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, it)) } (2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) } FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) } } @@ -99,48 +107,85 @@ internal fun FrameGenMenu( ), ) { Text(offLabel) } - Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - val focusIndex = engines.indexOfFirst { (engine, _) -> - selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + if (listLayout) { + Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + engines.forEach { (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } + } } - engines.forEachIndexed { index, (engine, label) -> - val selected = selectedEngine == engine - val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready - val pick = { - onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } else { + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val focusIndex = engines.indexOfFirst { (engine, _) -> + selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + } + engines.forEachIndexed { index, (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = (if (index == focusIndex) focusModifier else Modifier) + .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } } - OutlinedButton( - onClick = pick, - enabled = enabled, - modifier = (if (index == focusIndex) focusModifier else Modifier) - .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, - contentColor = if (selected) colors.primary else colors.onSurface, - ), - ) { Text(label) } } } - if (selectedEngine != null) { - val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready + val multiplierEnabled = mode.engine != FrameGen.ENGINE_LSFG || lossless.ready + if (listLayout) { + Column( + Modifier.fillMaxWidth().padding(top = 8.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + (2..4).forEach { multiplier -> + val selected = mode.multiplier == multiplier && mode.target == 0 + val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) } + OutlinedButton( + onClick = pickMultiplier, + enabled = multiplierEnabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, + contentColor = if (selected) colors.secondary else colors.onSurface, + ), + ) { Text("${multiplier}×") } + } + } + } else { Row( Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { (2..4).forEach { multiplier -> val selected = mode.multiplier == multiplier && mode.target == 0 - val pickMultiplier = { - onPick(mode.copy(multiplier = multiplier, target = 0)) - } + val pickMultiplier = { onPick(mode.copy(multiplier = multiplier, target = 0)) } OutlinedButton( onClick = pickMultiplier, enabled = multiplierEnabled, - modifier = Modifier.weight(1f).controllerConfirm( - enabled = multiplierEnabled, - onClick = pickMultiplier, - ), + modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, @@ -151,6 +196,25 @@ internal fun FrameGenMenu( } } + val togglePacer = { + val enabled = !pacerEnabled + FrameGen.setPacer(context, enabled) + pacerEnabled = enabled + } + OutlinedButton( + onClick = togglePacer, + modifier = Modifier.fillMaxWidth().padding(top = 8.dp) + .controllerConfirm(onClick = togglePacer), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (pacerEnabled) colors.primary else colors.onSurface, + ), + ) { + Text("ZeroPacer" + if (pacerEnabled) " ✓" else "") + } + + if (selectedEngine == FrameGen.ENGINE_LSFG) { Row( Modifier.fillMaxWidth().padding(top = 8.dp), @@ -196,6 +260,5 @@ internal fun FrameGenMenu( Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") } } - } } 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 2fa213d89c..d7d596aa92 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -482,6 +482,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } } LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } + LaunchedEffect(host.open) { + if (host.open == "frame-generation") repeat(24) { + androidx.compose.runtime.withFrameNanos { } + focus.request("frame-generation") + if (focus.focused == "frame-generation") return@LaunchedEffect + } + } LaunchedEffect(a.selectedGameProfileId) { if (host.open == "fex") host.open = null } @@ -910,24 +917,31 @@ private fun DrawerPerformancePage(host: MenuHost, a: DrawerActions, track: (Stri @Composable -private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { +private fun DrawerFrameGenSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) val scope = if (a.frameGenTargetGameId != null) "${stringResource(R.string.frame_gen_scope_game)} · ${a.frameGenTargetGameName ?: "ID ${a.frameGenTargetGameId}"}" else stringResource(R.string.frame_gen_scope_global) 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, - gameProfileId = a.frameGenTargetGameId, - hasGameOverride = a.hasGameOverride, - onResetGame = a.onFrameGenReset, - ) - } + FrameGenMenu( + mode = a.frameGen, + lossless = a.lossless, + onPick = a.onFrameGenPick, + + gameProfileId = a.frameGenTargetGameId, + hasGameOverride = a.hasGameOverride, + onResetGame = a.onFrameGenReset, + focusModifier = track("frame-generation"), + ) } } +@Composable +private fun DrawerFrameGenPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + DrawerFrameGenSettings(host, a, track) +} + @Composable private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { 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 86e5b90601..2cc0ecd638 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -460,12 +460,14 @@ public final class WaylandCompositor { public static final int SCENE_BUTTON = 3, SCENE_WHEEL = 4, SCENE_POINTER_DELTA = 6, SCENE_AXIS = 11, SCENE_AXIS_FINGER = 12; public static final int WHEEL_STEP_UNITS = 120, POINTER_DELTA_SCALE = 256; - public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1; + public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1, FG_ENGINE_ZEROFG = 2; public static native void nativeSetFrameGenEngine(int kind); public static native void nativeSetFrameGenArmed(boolean armed, int multiplier, int targetFps); + public static native void nativeSetFrameGenPacer(boolean on); + public static native void nativeSetLsfgCachePath(String path); public static native void nativeSetFrameGenTuning(float flowScale, float refreshHz); diff --git a/app/src/main/res/values/zerofg_framegen.xml b/app/src/main/res/values/zerofg_framegen.xml new file mode 100644 index 0000000000..0f98cf7e8e --- /dev/null +++ b/app/src/main/res/values/zerofg_framegen.xml @@ -0,0 +1,4 @@ + + + ZeroFG %1$d× + diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt index 5afd7f83a9..0eda995f76 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/FrameGenTest.kt @@ -30,6 +30,16 @@ class FrameGenTest { assertEquals(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 90), FrameGen.mode(context)) } + @Test fun zeroFgModeRoundTrips() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), FrameGen.mode(context)) + } + + @Test fun zeroFgDoesNotKeepAdaptiveTarget() { + FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_ZEROFG, multiplier = 4, target = 60)) + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 4), FrameGen.mode(context)) + } + @Test fun fixedMultiplierReplacesATarget() { FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, target = 120)) FrameGen.set(context, FrameGen.Mode(FrameGen.ENGINE_LSFG, 3)) diff --git a/docs/development/framegen-post-upscale.md b/docs/development/framegen-post-upscale.md index 084040d96d..dcec8257f0 100644 --- a/docs/development/framegen-post-upscale.md +++ b/docs/development/framegen-post-upscale.md @@ -50,8 +50,9 @@ feature-level or game compatibility changes. - Compare the same scene on baseline main and this branch: FG off/on, Linear, FSR, GSR, GSR HQ, NIS, FSR Fit, sharpen-only and nearest. -- Test each supported interpolation multiplier, both engines, warm-up/no - generated frames, 720p-to-1080p and 1080p-to-panel scaling, and no upscale. +- Test each supported interpolation multiplier on LSFG, DDFG and ZeroFG, + including warm-up/no generated frames, 720p-to-1080p and 1080p-to-panel + scaling, and no upscale. - Check real and generated frames for consistent sharpness, halos, ghosting, text/cursor artifacts, black bars, stretching and frame-order errors. - Change resolution/filter/engine/multiplier live; open Steam/QAM, rotate, diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index fbbff9271e..38ca6f9f3c 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -31,7 +31,7 @@ class EffectsSourceResolutionTest(unittest.TestCase): 'static int draw_to_scene_blit(', 'static int effects_source_draw(', 'static void effects_source_note(', 'static void effects_overlay_draws(', - 'static int render_impl(', 'static int pass_begin_impl(')) + 'static int render_impl(', 'static int pass_begin_impl(', 'static int pass_finish(', 'int vkp_pass_copy_generated(')) functions = (re.search(r'static int spatial_mode\([^\n]+', effects).group() + '\n' + re.search(r'static int cas_active\([^\n]+', effects).group() + '\n' + function(effects, 'int vkp_effects_upscaling(') + @@ -109,6 +109,9 @@ class EffectsSourceResolutionTest(unittest.TestCase): def test_frame_generation_runs_spatial_post_upscale(self): self.check_case('framegen-upscale') + def test_display_layer_interpolates_before_the_spatial_upscale(self): + self.check_case('framegen-layer-upscale') + TYPES = r''' #include @@ -116,6 +119,7 @@ TYPES = r''' #include #include #include +#include typedef int VkImage, VkDeviceMemory, VkFormat, VkCommandBuffer, VkResult, VkFilter, VkBuffer; typedef int VkImageLayout, VkPipelineStageFlags, VkImageUsageFlags; typedef uint64_t VkDeviceSize; @@ -179,6 +183,8 @@ typedef struct AHardwareBuffer AHardwareBuffer; STUBS = r''' +static void zfg_discard_history_update(void) {} +static void zfg_commit_history_update(void) {} static void stage_linear_dmabufs(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) { (void)cmd; (void)draws; (void)count; } static int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) { return dmabuf && !staged; } static void quarantine_pending_work(VkResult result, const char *where) { (void)result; (void)where; } @@ -214,7 +220,7 @@ static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map; static struct { VkImage img; int w, h; } g_scene; struct vkp_img_slot { VkImage img; int w, h; }; static struct vkp_img_slot g_hdrscene, g_fgscene; -static struct { int active, rw, rh, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; +static struct { int active, rw, rh, ow, oh, post_upscale, ngen; VkImage result; VkImage gens[VKP_FG_MAX_GENERATIONS]; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; struct fx_settings { int scaling, cas_on, cas_pct; }; @@ -294,6 +300,21 @@ static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int fo return generations; } static void vkp_effects_release_generated_sources(void) {} +static void vkp_framegen_set_layer_timing(int layer) {} +static int g_wait_sem, blit_count, blit_src_w[4], blit_src_h[4], blit_dst_w[4], blit_dst_h[4]; +static VkImage blit_src_images[4], blit_dst_images[4]; +static VkImageLayout blit_layouts[4]; +static int take_wait_fd(int fd) { return fd < 0 ? 0 : fd; } +static void blit_to_layer(int cmd, VkImage src, VkImageLayout layout, struct vkp_image *dst, + const VkImageBlit *blit, VkFilter filter) { + assert(blit_count < 4); + blit_src_images[blit_count] = src; blit_dst_images[blit_count] = dst->image; + blit_layouts[blit_count] = layout; + blit_src_w[blit_count] = blit->srcOffsets[1].x; blit_src_h[blit_count] = blit->srcOffsets[1].y; + blit_dst_w[blit_count] = blit->dstOffsets[1].x; blit_dst_h[blit_count] = blit->dstOffsets[1].y; + blit_count++; +} +static void vkp_framegen_completed(void) {} static VkImage vkp_effects_run_generated(int cmd, int source, int w, int h, int ow, int oh, int slot, int *rw, int *rh) { assert(slot == post_count && slot < 4); @@ -660,6 +681,40 @@ static void check_framegen_upscale(void) { struct vkp_hdr_frame hdr = {0}; run_path(0, &draw, 1, &hdr); assert(post_count == 0); } +static void check_framegen_layer_upscale(void) { + reset(); framegen = 1; generations = 2; + struct vkp_draw draw = fullscreen(); + int rw = 0, rh = 0; + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0); + assert(effects_count == 1 && output_w == 1280 && output_h == 720); + assert(fg_w == 1280 && fg_h == 720); + assert(g_pass.post_upscale && g_pass.rw == 1280 && g_pass.rh == 720); + assert(rw == 1920 && rh == 1080); + struct vkp_image generated_dst[2] = {{.image = 50, .w = 1920, .h = 1080, .blit_dst = 1}, {.image = 51, .w = 1920, .h = 1080, .blit_dst = 1}}; + struct vkp_image real_dst = {.image = 52, .w = 1920, .h = 1080, .blit_dst = 1}; + struct vkp_image *generated_ptrs[2] = {&generated_dst[0], &generated_dst[1]}; + g_pass.gens[0] = 20; g_pass.gens[1] = 21; g_pass.result = 4; g_pass.ngen = 2; + assert(vkp_pass_copy_generated(generated_ptrs, 2, &real_dst, -1) == 0); + assert(post_count == 3 && blit_count == 3); + assert(post_sources[0] == 20 && post_sources[1] == 21 && post_sources[2] == 4); + for (int i = 0; i < 3; i++) { + assert(blit_src_images[i] == 40 + i); + assert(blit_dst_images[i] == 50 + i); + assert(blit_layouts[i] == VK_IMAGE_LAYOUT_GENERAL); + } + for (int i = 0; i < 3; i++) { + assert(blit_src_w[i] == 1920 && blit_src_h[i] == 1080); + assert(blit_dst_w[i] == 1920 && blit_dst_h[i] == 1080); + } + reset(); framegen = 1; postprocessing = 1; + draw = fullscreen(); + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 1, &rw, &rh) == 0); + assert(!g_pass.post_upscale && rw == g_pass.rw && rh == g_pass.rh); + reset(); framegen = 1; + draw = fullscreen(); + assert(pass_begin_impl(1920, 1080, &draw, 1, NULL, 0, &rw, &rh) == 0); + assert(!g_pass.post_upscale); +} int main(int argc, char **argv) { assert(argc == 2); reset(); if (!strcmp(argv[1], "helper")) check_helper(); @@ -677,6 +732,7 @@ int main(int argc, char **argv) { else if (!strcmp(argv[1], "postprocessing")) check_postprocessing(); else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening(); else if (!strcmp(argv[1], "framegen-upscale")) check_framegen_upscale(); + else if (!strcmp(argv[1], "framegen-layer-upscale")) check_framegen_layer_upscale(); else assert(0); puts("PASS"); } diff --git a/tools/tests/test_framegen_ring_lifetime.py b/tools/tests/test_framegen_ring_lifetime.py index ca39670844..082edc32ba 100644 --- a/tools/tests/test_framegen_ring_lifetime.py +++ b/tools/tests/test_framegen_ring_lifetime.py @@ -31,6 +31,8 @@ static void destroy_image(int d, int image, const void *a) { static void destroy_view(int d, int view, const void *a) { assert(idle == 1); views++; } static void free_memory(int d, int mem, const void *a) { assert(images > memory); memory++; } static void fge_forget_targets(void) { assert(images == 3); engine++; } +static void vkp_framegen_set_layer_timing(int layer) { (void)layer; } +static void vkp_framegen_completed(void) {} static struct { void (*DeviceWaitIdle)(int); void (*DestroyImage)(int, int, const void *); diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index 0bc1bf31ba..be7b2f328a 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -108,6 +108,10 @@ int vkp_framegen_run(VkCommandBuffer c, VkImage s, VkImageView v, int w, int h, return generated; } void vkp_framegen_presented(int n) { ++presented_notifications; } +void vkp_framegen_set_layer_timing(int layer) {} +void vkp_framegen_completed(void) {} +void zfg_discard_history_update(void) {} +void zfg_commit_history_update(void) {} void vkp_gpu_busy_device(VkPhysicalDevice p, VkDevice d, uint32_t f) {} void vkp_gpu_busy_device_lost(void) {} void hdrc_bind_device(VkDevice d, const VkPhysicalDeviceMemoryProperties *m) {} From bf8faf06e1b2e76079383f0a386ebc12d9162c55 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:20:03 -0500 Subject: [PATCH 41/80] Make frame generation and game zoom controller-friendly (#3669) Add the session engine picker and the stepped Game zoom slider. Keep Frame Generation in its own tab and use the standard controller focus ring on its buttons. --- .../com/droiddeck/launcher/ui/FrameGenMenu.kt | 231 ++++++++++++----- .../droiddeck/launcher/ui/SessionOverlay.kt | 83 ++++-- .../droiddeck/launcher/ui/SettingsWidgets.kt | 13 +- .../main/res/drawable/ic_frame_generation.xml | 12 +- app/src/main/res/values/strings.xml | 3 + .../launcher/ui/SessionControlDesignTest.kt | 239 ++++++++++++++++++ 6 files changed, 492 insertions(+), 89 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt 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 2c7ed785ea..eb6f1854f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -1,21 +1,35 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.withFrameNanos import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @@ -34,7 +48,9 @@ internal fun FrameGenMenu( focusModifier: Modifier = Modifier, legacyButtons: Boolean = false, listLayout: Boolean = false, + sessionHost: MenuHost? = null, ) { + val sessionEngineAnchor = remember { FocusRequester() } 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) @@ -95,60 +111,67 @@ internal fun FrameGenMenu( } Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) { - OutlinedButton( - onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, - modifier = Modifier.fillMaxWidth().controllerConfirm( - onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, - ), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface, - contentColor = if (selectedEngine == null) colors.primary else colors.onSurface, - ), - ) { Text(offLabel) } - - if (listLayout) { - Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { - engines.forEach { (engine, label) -> - val selected = selectedEngine == engine - val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready - val pick = { - onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) - } - OutlinedButton( - onClick = pick, - enabled = enabled, - modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, - contentColor = if (selected) colors.primary else colors.onSurface, - ), - ) { Text(label) } - } - } + if (sessionHost != null) { + SessionFrameGenEngine( + sessionHost, mode, listOf(FrameGen.ENGINE_OFF to offLabel) + engines, + lossless.ready, need, focusModifier, sessionEngineAnchor, onPick, + ) } else { - Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - val focusIndex = engines.indexOfFirst { (engine, _) -> - selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + OutlinedButton( + onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, + modifier = Modifier.fillMaxWidth().controllerConfirm( + onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) }, + ), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selectedEngine == null) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selectedEngine == null) colors.primary else colors.onSurface, + ), + ) { Text(offLabel) } + + if (listLayout) { + Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + engines.forEach { (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } + } } - engines.forEachIndexed { index, (engine, label) -> - val selected = selectedEngine == engine - val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready - val pick = { - onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } else { + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + val focusIndex = engines.indexOfFirst { (engine, _) -> + selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready + } + engines.forEachIndexed { index, (engine, label) -> + val selected = selectedEngine == engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || lossless.ready + val pick = { + onPick(if (selected) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + OutlinedButton( + onClick = pick, + enabled = enabled, + modifier = (if (index == focusIndex) focusModifier else Modifier) + .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } } - OutlinedButton( - onClick = pick, - enabled = enabled, - modifier = (if (index == focusIndex) focusModifier else Modifier) - .weight(1f).controllerConfirm(enabled = enabled, onClick = pick), - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), - colors = ButtonDefaults.outlinedButtonColors( - containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, - contentColor = if (selected) colors.primary else colors.onSurface, - ), - ) { Text(label) } } } } @@ -165,7 +188,8 @@ internal fun FrameGenMenu( OutlinedButton( onClick = pickMultiplier, enabled = multiplierEnabled, - modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier), + modifier = Modifier.fillMaxWidth().controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier) + .frameGenFocus(sessionHost), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, @@ -185,7 +209,8 @@ internal fun FrameGenMenu( OutlinedButton( onClick = pickMultiplier, enabled = multiplierEnabled, - modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier), + modifier = Modifier.weight(1f).controllerConfirm(enabled = multiplierEnabled, onClick = pickMultiplier) + .frameGenFocus(sessionHost), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, @@ -204,7 +229,7 @@ internal fun FrameGenMenu( OutlinedButton( onClick = togglePacer, modifier = Modifier.fillMaxWidth().padding(top = 8.dp) - .controllerConfirm(onClick = togglePacer), + .controllerConfirm(onClick = togglePacer).frameGenFocus(sessionHost), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (pacerEnabled) colors.primary.copy(alpha = 0.16f) else colors.surface, @@ -230,7 +255,7 @@ internal fun FrameGenMenu( modifier = Modifier.weight(1f).controllerConfirm( enabled = lossless.ready, onClick = pickTarget, - ), + ).frameGenFocus(sessionHost), contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = if (selected) colors.secondary.copy(alpha = 0.18f) else colors.surface, @@ -243,21 +268,107 @@ internal fun FrameGenMenu( } } - if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { + if (sessionHost == null && selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) { Text(need, color = colors.onSurfaceVariant, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(top = 6.dp)) } - if (gameProfileId != null) { - val resetGame = onResetGame + if (gameProfileId != null && (sessionHost == null || hasGameOverride)) { + val input = LocalInputModeManager.current + val resetGame = { + if (sessionHost != null && input.inputMode == InputMode.Keyboard) { + sessionEngineAnchor.requestFocus() + } + onResetGame() + } OutlinedButton( onClick = resetGame, modifier = Modifier.fillMaxWidth().padding(top = 8.dp) - .controllerConfirm(onClick = resetGame), + .testTag("framegen-use-global").controllerConfirm(onClick = resetGame) + .frameGenFocus(sessionHost), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), ) { - Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") + Text(if (sessionHost != null) stringResource(R.string.frame_gen_use_global) + else stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") + } + } + } +} + +@Composable +private fun Modifier.frameGenFocus(sessionHost: MenuHost?): Modifier = + if (sessionHost != null) focusGlide(RoundedCornerShape(percent = 50)) else this + +@Composable +private fun SessionFrameGenEngine( + host: MenuHost, + mode: FrameGen.Mode, + options: List>, + losslessReady: Boolean, + losslessNote: String, + focusModifier: Modifier, + anchor: FocusRequester, + onPick: (FrameGen.Mode) -> Unit, +) { + val label = stringResource(R.string.frame_gen_engine) + val selectedLabel = options.firstOrNull { (engine, _) -> engine == mode.engine }?.second + ?: options.first().second + val key = "frame-generation-engine" + val open = host.open == key + val input = LocalInputModeManager.current + var anchorFocused by remember { mutableStateOf(false) } + var restoreFocus by remember { mutableStateOf(false) } + + // The menu has its own focusable window; wait for its exit transition before restoring the anchor. + LaunchedEffect(open) { + if (!open && restoreFocus && host.open == null) { + repeat(24) { + withFrameNanos { } + runCatching { anchor.requestFocus() } + if (anchorFocused) { + restoreFocus = false + return@LaunchedEffect + } + } + restoreFocus = false + } + } + + val blockedSelection = !losslessReady && mode.engine == FrameGen.ENGINE_LSFG + SettingsRow(label, losslessNote.takeIf { blockedSelection && !open }, highlighted = open) { + Box { + ValueChip( + selectedLabel, open, + modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused } + .heightIn(min = 48.dp).testTag("setting-$key") + .semantics { contentDescription = label; stateDescription = selectedLabel }, + ) { + if (open) host.open = null + else { + restoreFocus = anchorFocused || input.inputMode == InputMode.Keyboard + host.open = key + } + } + AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, keyboardFocus = restoreFocus) { firstFocus -> + val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first + ?: FrameGen.ENGINE_OFF + options.forEach { (engine, text) -> + val selected = engine == mode.engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady + MenuItem( + label = text, checked = selected, enabled = enabled, + detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady }, + focusRequester = firstFocus.takeIf { engine == initial }, + modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"), + ) { + host.open = null + if (!selected) { + onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) + else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) + } + } + } } } } 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 d7d596aa92..2430aa45f9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -18,9 +18,11 @@ import androidx.compose.ui.input.key.type import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection import kotlin.math.roundToInt import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay @@ -89,6 +91,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -933,6 +936,7 @@ private fun DrawerFrameGenSettings(host: MenuHost, a: DrawerActions, track: (Str hasGameOverride = a.hasGameOverride, onResetGame = a.onFrameGenReset, focusModifier = track("frame-generation"), + sessionHost = host, ) } } @@ -948,7 +952,7 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) val orientations = SessionPrefs.orientationOptions.map { (value, label) -> value to stringResource(label) } SettingsGroup(stringResource(R.string.drawer_page_display), key = "display", detail = summary(if (a.gameZoomAvailable) "${(a.gameZoom * 100.0f).toInt()}%" else null, orientations.labelOf(a.orientation))) { - if (a.gameZoomAvailable) GameZoomRow(a, track) + if (a.gameZoomAvailable) GameZoomRow(a.gameZoom, track, a.onGameZoom) ChoiceRow(host, "orientation", stringResource(R.string.setup_session_orientation), null, orientations, a.orientation, chipModifier = track("orientation"), onPick = a.onOrientation) if (a.steam) PicturePositionRow(host, a.picturePosition, track("picture-position"), onPick = a.onPicturePosition) @@ -970,27 +974,66 @@ private fun DrawerDisplayPage(host: MenuHost, a: DrawerActions, track: (String) SecondScreenGroup(host, a, track) } +private const val GAME_ZOOM_MIN = 100 +private const val GAME_ZOOM_MAX = 300 +private const val GAME_ZOOM_STEP = 25 +private const val GAME_ZOOM_INTERVALS = (GAME_ZOOM_MAX - GAME_ZOOM_MIN) / GAME_ZOOM_STEP + @Composable -private fun GameZoomRow(a: DrawerActions, track: (String) -> Modifier) { - SettingsRow(stringResource(R.string.game_zoom_title), stringResource(R.string.game_zoom_hint)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { - val zoomOutEnabled = a.gameZoom > 1.0f - val zoomInEnabled = a.gameZoom < 3.0f - val zoomOut = { a.onGameZoom((a.gameZoom - 0.25f).coerceAtLeast(1.0f)) } - val zoomIn = { a.onGameZoom((a.gameZoom + 0.25f).coerceAtMost(3.0f)) } - val zoomReset = { a.onGameZoom(1.0f) } - OutlinedButton(onClick = zoomOut, enabled = zoomOutEnabled, - modifier = track("game-zoom-out").width(42.dp).controllerConfirm(enabled = zoomOutEnabled, onClick = zoomOut), - contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)) { Text("−") } - Text("${(a.gameZoom * 100.0f).toInt()}%", fontSize = 12.sp) - OutlinedButton(onClick = zoomIn, enabled = zoomInEnabled, - modifier = track("game-zoom-in").width(42.dp).controllerConfirm(enabled = zoomInEnabled, onClick = zoomIn), - contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp)) { Text("+") } - OutlinedButton(onClick = zoomReset, enabled = zoomOutEnabled, - modifier = track("game-zoom-reset").width(48.dp).controllerConfirm(enabled = zoomOutEnabled, onClick = zoomReset), - contentPadding = PaddingValues(horizontal = 2.dp, vertical = 0.dp)) { Text("1×") } - } +internal fun GameZoomRow( + zoom: Float, + track: (String) -> Modifier, + onZoom: (Float) -> Unit, +) { + val source = remember { MutableInteractionSource() } + val focused by source.collectIsFocusedAsState() + val label = stringResource(R.string.game_zoom_title) + val percent = (zoom * 100f).roundToInt().coerceIn(GAME_ZOOM_MIN, GAME_ZOOM_MAX) + val value = stringResource(R.string.game_zoom_value, percent) + fun detent(value: Float): Int = ((value - GAME_ZOOM_MIN) / GAME_ZOOM_STEP).roundToInt() + val selectedDetent = detent(percent.toFloat()) + val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl + val pal = LocalPalette.current + val colors = MaterialTheme.colorScheme + + fun chooseDetent(index: Int) { + val next = GAME_ZOOM_MIN + index.coerceIn(0, GAME_ZOOM_INTERVALS) * GAME_ZOOM_STEP + if (next != percent) onZoom(next / 100f) } + Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 6.dp)) { + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + Text(value, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, + color = colors.onSurface, modifier = Modifier.testTag("game-zoom-value")) + } + Slider( + value = (GAME_ZOOM_MIN + selectedDetent * GAME_ZOOM_STEP).toFloat(), + onValueChange = { chooseDetent(detent(it)) }, + valueRange = GAME_ZOOM_MIN.toFloat()..GAME_ZOOM_MAX.toFloat(), + steps = GAME_ZOOM_INTERVALS - 1, + interactionSource = source, + modifier = track("game-zoom-slider").fillMaxWidth().heightIn(min = 48.dp) + .glideBorder(focused, RoundedCornerShape(10.dp), pal.signal) + .testTag("game-zoom-slider") + .semantics { contentDescription = label; stateDescription = value } + .onPreviewKeyEvent { event -> + val delta = when (event.key) { + Key.DirectionLeft -> if (rtl) 1 else -1 + Key.DirectionRight -> if (rtl) -1 else 1 + else -> return@onPreviewKeyEvent false + } + if (event.type == KeyEventType.KeyDown && event.nativeKeyEvent.repeatCount == 0) { + chooseDetent(selectedDetent + delta) + } + true + }, + ) + } + Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 5d09490e39..16712ad3b8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -322,6 +322,7 @@ private fun PassTriggerMotion(host: android.view.View) { fun AnchoredMenu( open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, compact: Boolean = false, minWidth: androidx.compose.ui.unit.Dp = 120.dp, + keyboardFocus: Boolean = false, content: @Composable ColumnScope.(FocusRequester) -> Unit, ) { val state = remember { MutableTransitionState(false) } @@ -335,9 +336,9 @@ fun AnchoredMenu( } val hostView = androidx.compose.ui.platform.LocalView.current val firstItemFocus = remember { FocusRequester() } - val inputMode = LocalInputModeManager.current.inputMode - LaunchedEffect(open, inputMode) { - if (open && inputMode == InputMode.Keyboard) { + val requestKeyboardFocus = keyboardFocus || LocalInputModeManager.current.inputMode == InputMode.Keyboard + LaunchedEffect(open, requestKeyboardFocus) { + if (open && requestKeyboardFocus) { repeat(2) { androidx.compose.runtime.withFrameNanos { } } runCatching { firstItemFocus.requestFocus() } android.util.Log.i("AnchoredMenu", "requested first option focus") @@ -353,10 +354,10 @@ fun AnchoredMenu( TrackKeyWindow() PassTriggerMotion(hostView) val popupInput = LocalInputModeManager.current - LaunchedEffect(open, inputMode) { - if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect + LaunchedEffect(open, requestKeyboardFocus) { + if (!open || !requestKeyboardFocus) return@LaunchedEffect popupInput.requestInputMode(InputMode.Keyboard) - repeat(8) { + repeat(if (keyboardFocus) 24 else 8) { androidx.compose.runtime.withFrameNanos { } if (runCatching { firstItemFocus.captureFocus() }.getOrDefault(false)) { firstItemFocus.freeFocus() diff --git a/app/src/main/res/drawable/ic_frame_generation.xml b/app/src/main/res/drawable/ic_frame_generation.xml index ea4c55cd2f..bf643a0c8d 100644 --- a/app/src/main/res/drawable/ic_frame_generation.xml +++ b/app/src/main/res/drawable/ic_frame_generation.xml @@ -2,7 +2,13 @@ - + android:viewportWidth="24" + android:viewportHeight="24"> + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a0be598c63..158461750a 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2838,6 +2838,9 @@ Image scaling Adjust game magnification from 100% to 300% Game zoom + %1$d%% + Engine + Use global setting Integer scaling Uses the largest whole-number scale that fits. May crop screen edges. If the source is larger than the output, fractional scaling fits the full image. Resolution is configured separately. Fit diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt new file mode 100644 index 0000000000..f576756873 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt @@ -0,0 +1,239 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.width +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.input.InputModeManager +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.click +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe +import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performSemanticsAction +import androidx.compose.ui.test.pressKey +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.Lossless +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@OptIn(ExperimentalTestApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w360dp-h640dp-port", application = android.app.Application::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class SessionControlDesignTest { + @get:Rule val compose = createRobolectricComposeRule() + + private val engineAnchor get() = compose.onNodeWithTag("setting-frame-generation-engine") + private fun engine(name: String) = compose.onNodeWithTag("framegen-engine:$name") + private fun zoom(name: String) = compose.onNodeWithTag("game-zoom-$name") + private fun zoomValue(value: Int) = zoom("value").assertTextEquals("$value%") + + // Popup focus transfers after the other window attaches or finishes exiting. + private fun settlePopupFocus() { + compose.runOnIdle { resumeDroppedUiDispatch() } + compose.mainClock.advanceTimeBy(500) + compose.waitForIdle() + } + + @Test + fun enginePickerStartsOnSelectionSkipsUnavailableEngineAndRestoresFocus() { + val mode = mutableStateOf(FrameGen.Mode(FrameGen.ENGINE_DDFG, 3)) + lateinit var input: InputModeManager + compose.setContent { + DroidDeckTheme { + input = LocalInputModeManager.current + Box(Modifier.width(300.dp)) { + FrameGenMenu(mode.value, Lossless.State.NONE, { mode.value = it }, sessionHost = rememberMenuHost()) + } + } + } + + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + engineAnchor.performSemanticsAction(SemanticsActions.RequestFocus) + engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + settlePopupFocus() + engine(FrameGen.ENGINE_LSFG).assertIsNotEnabled() + engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + engine(FrameGen.ENGINE_OFF).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + settlePopupFocus() + engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist() + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value) + engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + settlePopupFocus() + engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonB) } + settlePopupFocus() + engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist() + assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value) + engineAnchor.assertIsFocused() + } + + @Test + fun gameOverrideCanReturnToGlobalWithoutLosingControllerFocus() { + val override = mutableStateOf(true) + lateinit var input: InputModeManager + compose.setContent { + DroidDeckTheme { + input = LocalInputModeManager.current + FrameGenMenu( + mode = if (override.value) FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 2) else FrameGen.Mode.OFF, + lossless = Lossless.State.NONE, + onPick = {}, + gameProfileId = "8400", + hasGameOverride = override.value, + onResetGame = { override.value = false }, + sessionHost = rememberMenuHost(), + ) + } + } + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + val reset = compose.onNodeWithTag("framegen-use-global") + reset.assertTextEquals("Use global setting").performSemanticsAction(SemanticsActions.RequestFocus) + reset.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } + reset.assertDoesNotExist() + engineAnchor.assertIsFocused() + } + + @Test + fun frameGenButtonsMoveTheDrawerFocusRing() { + lateinit var input: InputModeManager + lateinit var glide: FocusGlide + compose.setContent { + DroidDeckTheme { + FocusGlideHost { + input = LocalInputModeManager.current + glide = checkNotNull(LocalFocusGlide.current) + FrameGenMenu( + mode = FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 2), + lossless = Lossless.State.NONE, + onPick = {}, + gameProfileId = "8400", + hasGameOverride = true, + sessionHost = rememberMenuHost(), + ) + } + } + } + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + var previous: GlideSource? = null + for (label in listOf("2×", "3×", "4×", "ZeroPacer", "Use global setting")) { + val button = if (label == "ZeroPacer") compose.onNodeWithText(label, substring = true) + else compose.onNodeWithText(label) + button.performSemanticsAction(SemanticsActions.RequestFocus).assertIsFocused() + compose.runOnIdle { + assertNotNull("Missing focus ring for $label", glide.current) + assertNotSame("Focus ring did not move to $label", previous, glide.current) + previous = glide.current + } + } + } + + @Test + fun legacyFrameGenerationStillUsesTheFlatOptions() { + compose.setContent { + DroidDeckTheme { + FrameGenMenu(FrameGen.Mode.OFF, Lossless.State.NONE, {}, legacyButtons = true) + } + } + engineAnchor.assertDoesNotExist() + compose.onNodeWithText("ZeroFG 2×").assertExists() + } + + @Test + fun zoomStepsBy25PercentAndDpadCanLeaveIt() { + val value = mutableStateOf(1f) + val changes = mutableListOf() + lateinit var input: InputModeManager + compose.setContent { + DroidDeckTheme { + input = LocalInputModeManager.current + Column(Modifier.width(300.dp)) { + OutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth().testTag("above")) { Text("Above") } + GameZoomRow(value.value, { Modifier }) { changes += it; value.value = it } + OutlinedButton(onClick = {}, modifier = Modifier.fillMaxWidth().testTag("below")) { Text("Below") } + } + } + } + + compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } + val slider = zoom("slider") + zoomValue(100) + zoom("reset").assertDoesNotExist() + slider.performSemanticsAction(SemanticsActions.RequestFocus) + slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionLeft) } + zoomValue(100) + assertEquals(emptyList(), changes) + slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + compose.onNodeWithTag("above").assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + slider.assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } + compose.onNodeWithTag("below").assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + slider.assertIsFocused() + + for (percent in 125..300 step 25) { + slider.performKeyInput { pressKey(Key.DirectionRight) } + zoomValue(percent) + slider.assertIsFocused() + } + slider.performKeyInput { pressKey(Key.DirectionRight) } + zoomValue(300) + assertEquals((125..300 step 25).map { it / 100f }, changes) + slider.performKeyInput { pressKey(Key.DirectionLeft) } + zoomValue(275) + zoom("reset").assertDoesNotExist() + slider.performKeyInput { pressKey(Key.DirectionDown) } + compose.onNodeWithTag("below").assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } + slider.assertIsFocused() + for (percent in 250 downTo 100 step 25) { + slider.performKeyInput { pressKey(Key.DirectionLeft) } + zoomValue(percent) + } + } + + @Test + fun touchTapAndDragSnapToTheNineValues() { + val value = mutableStateOf(1f) + val changes = mutableListOf() + compose.setContent { + DroidDeckTheme { + Box(Modifier.width(300.dp)) { + GameZoomRow(value.value, { Modifier }) { changes += it; value.value = it } + } + } + } + val slider = zoom("slider").assertIsDisplayed() + slider.performTouchInput { click(center) } + zoomValue(200) + slider.performTouchInput { swipe(center, Offset(width - 2f, center.y)) } + zoomValue(300) + slider.performTouchInput { click(Offset(2f, center.y)) } + zoomValue(100) + val allowed = (100..300 step 25).map { it / 100f }.toSet() + assertEquals(true, changes.all { it in allowed }) + } +} From 01c8991049346b8852bd0602acdfa579f1e96977 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:43:45 -0500 Subject: [PATCH 42/80] Fix initial controller focus in the frame generation picker (#3689) Keep engine choices in the session drawer focus tree so the selected engine receives focus on open and the Engine control regains focus on close. --- .../com/droiddeck/launcher/ui/FrameGenMenu.kt | 82 +++++++++---------- .../droiddeck/launcher/ui/SettingsWidgets.kt | 13 ++- .../launcher/ui/SessionControlDesignTest.kt | 15 +--- 3 files changed, 49 insertions(+), 61 deletions(-) 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 eb6f1854f0..bc8576b287 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrameGenMenu.kt @@ -1,7 +1,6 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row @@ -318,55 +317,52 @@ private fun SessionFrameGenEngine( val open = host.open == key val input = LocalInputModeManager.current var anchorFocused by remember { mutableStateOf(false) } - var restoreFocus by remember { mutableStateOf(false) } + val selectedOption = remember { FocusRequester() } + var keyboardOpened by remember { mutableStateOf(false) } + val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first + ?: FrameGen.ENGINE_OFF + val close = { if (host.open == key) host.open = null } - // The menu has its own focusable window; wait for its exit transition before restoring the anchor. + // Keep the options in the drawer's focus tree. A separate popup window can + // steal focus from the controller before Compose can focus the selected row. LaunchedEffect(open) { - if (!open && restoreFocus && host.open == null) { - repeat(24) { - withFrameNanos { } - runCatching { anchor.requestFocus() } - if (anchorFocused) { - restoreFocus = false - return@LaunchedEffect - } - } - restoreFocus = false - } + if (!keyboardOpened || (!open && host.open != null)) return@LaunchedEffect + val target = if (open) selectedOption else anchor + withFrameNanos { } + target.requestFocus() + if (!open) keyboardOpened = false } val blockedSelection = !losslessReady && mode.engine == FrameGen.ENGINE_LSFG SettingsRow(label, losslessNote.takeIf { blockedSelection && !open }, highlighted = open) { - Box { - ValueChip( - selectedLabel, open, - modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused } - .heightIn(min = 48.dp).testTag("setting-$key") - .semantics { contentDescription = label; stateDescription = selectedLabel }, - ) { - if (open) host.open = null - else { - restoreFocus = anchorFocused || input.inputMode == InputMode.Keyboard - host.open = key - } + ValueChip( + selectedLabel, open, + modifier = focusModifier.focusRequester(anchor).onFocusChanged { anchorFocused = it.isFocused } + .heightIn(min = 48.dp).testTag("setting-$key") + .semantics { contentDescription = label; stateDescription = selectedLabel }, + ) { + if (open) close() + else { + keyboardOpened = anchorFocused || input.inputMode == InputMode.Keyboard + host.open = key } - AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, keyboardFocus = restoreFocus) { firstFocus -> - val initial = options.firstOrNull { (engine, _) -> engine == mode.engine }?.first - ?: FrameGen.ENGINE_OFF - options.forEach { (engine, text) -> - val selected = engine == mode.engine - val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady - MenuItem( - label = text, checked = selected, enabled = enabled, - detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady }, - focusRequester = firstFocus.takeIf { engine == initial }, - modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"), - ) { - host.open = null - if (!selected) { - onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) - else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) - } + } + } + if (open) { + Column(Modifier.fillMaxWidth().padding(horizontal = 8.dp).controllerBack(close)) { + options.forEach { (engine, text) -> + val selected = engine == mode.engine + val enabled = selected || engine != FrameGen.ENGINE_LSFG || losslessReady + MenuItem( + label = text, checked = selected, enabled = enabled, + detail = losslessNote.takeIf { engine == FrameGen.ENGINE_LSFG && !losslessReady }, + focusRequester = selectedOption.takeIf { engine == initial }, + modifier = Modifier.heightIn(min = 48.dp).testTag("framegen-engine:$engine"), + ) { + close() + if (!selected) { + onPick(if (engine == FrameGen.ENGINE_OFF) FrameGen.Mode.OFF.copy(multiplier = mode.multiplier) + else FrameGen.Mode(engine, mode.multiplier.coerceIn(2, 4))) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 16712ad3b8..5d09490e39 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -322,7 +322,6 @@ private fun PassTriggerMotion(host: android.view.View) { fun AnchoredMenu( open: Boolean, onDismiss: () -> Unit, title: String? = null, note: String? = null, compact: Boolean = false, minWidth: androidx.compose.ui.unit.Dp = 120.dp, - keyboardFocus: Boolean = false, content: @Composable ColumnScope.(FocusRequester) -> Unit, ) { val state = remember { MutableTransitionState(false) } @@ -336,9 +335,9 @@ fun AnchoredMenu( } val hostView = androidx.compose.ui.platform.LocalView.current val firstItemFocus = remember { FocusRequester() } - val requestKeyboardFocus = keyboardFocus || LocalInputModeManager.current.inputMode == InputMode.Keyboard - LaunchedEffect(open, requestKeyboardFocus) { - if (open && requestKeyboardFocus) { + val inputMode = LocalInputModeManager.current.inputMode + LaunchedEffect(open, inputMode) { + if (open && inputMode == InputMode.Keyboard) { repeat(2) { androidx.compose.runtime.withFrameNanos { } } runCatching { firstItemFocus.requestFocus() } android.util.Log.i("AnchoredMenu", "requested first option focus") @@ -354,10 +353,10 @@ fun AnchoredMenu( TrackKeyWindow() PassTriggerMotion(hostView) val popupInput = LocalInputModeManager.current - LaunchedEffect(open, requestKeyboardFocus) { - if (!open || !requestKeyboardFocus) return@LaunchedEffect + LaunchedEffect(open, inputMode) { + if (!open || inputMode != InputMode.Keyboard) return@LaunchedEffect popupInput.requestInputMode(InputMode.Keyboard) - repeat(if (keyboardFocus) 24 else 8) { + repeat(8) { androidx.compose.runtime.withFrameNanos { } if (runCatching { firstItemFocus.captureFocus() }.getOrDefault(false)) { firstItemFocus.freeFocus() diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt index f576756873..0de1726e21 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionControlDesignTest.kt @@ -53,13 +53,6 @@ class SessionControlDesignTest { private fun zoom(name: String) = compose.onNodeWithTag("game-zoom-$name") private fun zoomValue(value: Int) = zoom("value").assertTextEquals("$value%") - // Popup focus transfers after the other window attaches or finishes exiting. - private fun settlePopupFocus() { - compose.runOnIdle { resumeDroppedUiDispatch() } - compose.mainClock.advanceTimeBy(500) - compose.waitForIdle() - } - @Test fun enginePickerStartsOnSelectionSkipsUnavailableEngineAndRestoresFocus() { val mode = mutableStateOf(FrameGen.Mode(FrameGen.ENGINE_DDFG, 3)) @@ -76,19 +69,19 @@ class SessionControlDesignTest { compose.runOnIdle { input.requestInputMode(InputMode.Keyboard) } engineAnchor.performSemanticsAction(SemanticsActions.RequestFocus) engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } - settlePopupFocus() + compose.mainClock.advanceTimeByFrame() engine(FrameGen.ENGINE_LSFG).assertIsNotEnabled() engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionUp) } engine(FrameGen.ENGINE_OFF).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } engine(FrameGen.ENGINE_DDFG).assertIsFocused().performKeyInput { pressKey(Key.DirectionDown) } engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } - settlePopupFocus() + compose.mainClock.advanceTimeByFrame() engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist() assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value) engineAnchor.assertIsFocused().performKeyInput { pressKey(Key.ButtonA) } - settlePopupFocus() + compose.mainClock.advanceTimeByFrame() engine(FrameGen.ENGINE_ZEROFG).assertIsFocused().performKeyInput { pressKey(Key.ButtonB) } - settlePopupFocus() + compose.mainClock.advanceTimeByFrame() engine(FrameGen.ENGINE_ZEROFG).assertDoesNotExist() assertEquals(FrameGen.Mode(FrameGen.ENGINE_ZEROFG, 3), mode.value) engineAnchor.assertIsFocused() From b61f766b66604222c7e5ef159e76674c5afa098e Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:54:51 -0500 Subject: [PATCH 43/80] fix(session): sleep freezes the programs that run in worker processes (#3665) With the native session, gamescope, Xwayland, wineserver and the game each run in a worker process of their own: none descends from the session root, so the freeze on sleep left them running. On wake the resume still added the frozen time to the guest clock shift, and every one of them saw its monotonic clock jump back by the length of the sleep. Unreal games abort on that: KINGDOM HEARTS III failed with "Detected negative delta time" (DeltaTime -10.05 s after a 13 s sleep). The freeze now treats the session's worker programs as helper roots, as the teardown already does. --- .../java/com/droiddeck/launcher/session/SessionService.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 9ef1456616..67992024db 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -945,11 +945,15 @@ class SessionService : Service() { return } if (gen == sessionGen && SessionState.running) { + val workers = ownWorkers suspendController = SessionSuspendController( sessionRoot = { sessionPid }, + // Programs handed off to worker processes are not descendants of the session root, and + // the clock shift applied at resume would move their monotonic time backwards. helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } + - listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 }) + listOfNotNull(BottomDesktop.suspendPid.takeIf { it > 1 }) + + (if (workers > 0) com.droiddeck.launcher.runtime.GuestWorkers.guestPids(workers) else emptyList()) }, suspendAudio = { if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink") From b6efc4d44a741e59fbce124de6d28c3e629ce3ba Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:55:44 -0500 Subject: [PATCH 44/80] Updates: Lab builds under the installed build, two panes in landscape (#3667) * feat(updates): Lab builds under the installed build, two panes in landscape Lab builds sit under the installed build instead of below the test list, with kept builds folded behind a toggle while one runs. In landscape the page splits into two panes that scroll on their own: the installed build, checks, Lab builds and tester options on the left, the channel picker and its status on the right. The selected test build expands in place with its status, notes and install button. * fix(updates): stack the fallback status above the test list --- .../com/droiddeck/launcher/ui/LabBuilds.kt | 37 +++- .../com/droiddeck/launcher/ui/UpdatesPage.kt | 160 ++++++++++-------- app/src/main/res/values/strings.xml | 4 + 3 files changed, 131 insertions(+), 70 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt b/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt index 8bfc59306b..c813b4fa1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LabBuilds.kt @@ -3,6 +3,9 @@ package com.droiddeck.launcher.ui import android.text.format.DateUtils import androidx.compose.foundation.background import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -26,8 +29,11 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -41,7 +47,7 @@ import com.droiddeck.launcher.lab.LabOverlay * [onRebuild] offers to build a kept one again for this install, when something can. */ @Composable -internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay.Info) -> Unit)? = null) { +internal fun LabBuilds(sessionRunning: Boolean = false, header: (@Composable () -> Unit)? = null, onRebuild: ((LabOverlay.Info) -> Unit)? = null) { val context = LocalContext.current var version by remember { mutableIntStateOf(0) } var busy by remember { mutableStateOf(false) } @@ -54,6 +60,7 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay. val paused = active == null && current != null && LabOverlay.skipped == LabOverlay.SKIPPED_APP_IMAGE val restartFailed = stringResource(R.string.lab_restart_failed) val canRestart = !busy && !sessionRunning + var showKept by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(false) } /** Android may have given the APK an app image again, which a Lab build cannot load over. */ fun restart() { @@ -73,8 +80,8 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay. val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth().padding(top = 18.dp)) { - Text( + Column(Modifier.fillMaxWidth().padding(top = if (header == null) 18.dp else 0.dp)) { + if (header != null) header() else Text( stringResource(R.string.lab_builds).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp, bottom = 10.dp), ) @@ -99,7 +106,29 @@ internal fun LabBuilds(sessionRunning: Boolean = false, onRebuild: ((LabOverlay. PrimaryButton(stringResource(R.string.lab_restart), compact = true, enabled = canRestart) { restart() } } } - for (build in saved) rows += { + val foldKept = (current != null || pending != null) && saved.isNotEmpty() + if (foldKept) rows += { + val src = remember { MutableInteractionSource() } + val toggle = { showKept = !showKept } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().paneItem("lab:kept") + .background(if (rememberHot(src)) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle) + .controllerConfirm(onClick = toggle) + .padding(horizontal = 14.dp, vertical = 12.dp), + ) { + Text( + pluralStringResource(R.plurals.lab_kept_count, saved.size, saved.size), fontSize = 14.sp, + color = colors.onSurfaceVariant, modifier = Modifier.weight(1f), + ) + Text( + stringResource(if (showKept) R.string.common_hide else R.string.common_show), fontSize = 13.5.sp, + fontWeight = FontWeight.SemiBold, color = pal.signal, + ) + } + } + if (!foldKept || showKept) for (build in saved) rows += { var armed by remember(build.dir) { mutableStateOf(false) } val info = build.info BuildRow( 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 c454dfe2db..7a5510360e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -20,6 +20,7 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -114,36 +115,49 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie Column(modifier = modifier) { BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { val stacked = LocalNarrowPane.current || maxWidth < 600.dp - Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + 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)) + val installed: @Composable () -> Unit = { 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) - } else { - Row(horizontalArrangement = Arrangement.spacedBy(18.dp)) { - Box(Modifier.weight(1f)) { ChannelPicker(u, ua) } - Box(Modifier.weight(1.15f)) { StatusPanel(s, u, ua, me) } - } - } - 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 -> + LabBuilds(s.sessionRunning, header = { SectionLabel(stringResource(R.string.lab_builds)) }, 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) } + val channel: @Composable () -> Unit = { + SectionLabel(stringResource(R.string.upd_channel)) + ChannelPicker(u, ua) { StatusPanel(s, u, ua, me, embedded = it) } + } + val testers: @Composable () -> Unit = { + 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() } + } + if (stacked) { + Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + installed() + Box(Modifier.height(18.dp)) + channel() + testers() + } + } else { + Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(24.dp)) { + Column(Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + installed() + testers() + } + Column(Modifier.weight(1.15f).fillMaxHeight().verticalScroll(rememberScrollState()).padding(bottom = 16.dp)) { + channel() + } + } + } } } if (u.askPermission) AlertDialog( @@ -266,7 +280,7 @@ private fun CheckRow(u: UpdatesState, ua: UpdatesActions) { } @Composable -private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed) { +private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, me: AppUpdates.Installed, embedded: Boolean = false) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val catalog = u.catalog @@ -292,13 +306,14 @@ private fun StatusPanel(s: FrontEndState, u: UpdatesState, ua: UpdatesActions, m else -> Look(pal.good, stringResource(R.string.upd_current_status), stringResource(R.string.upd_current_headline, name), null) } Column( - modifier = Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp), + modifier = if (embedded) Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 14.dp) + else Modifier.fillMaxWidth().clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(18.dp), ) { 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) } - Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp)) + if (!embedded) Text(look.headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.padding(top = 4.dp)) if (offered) { val size = release!!.apk?.size?.takeIf { it > 0 }?.let { megabytes(it) } Text( @@ -419,7 +434,7 @@ 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 ChannelPicker(u: UpdatesState, ua: UpdatesActions) { +private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val catalog = u.catalog @@ -455,8 +470,9 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) { } 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) + if (!listing) status(false) 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) + TestList(tests, me, u, ua, status) } } } @@ -675,7 +691,7 @@ private fun LinkPill(label: String, url: String) { } @Composable -private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions) { +private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesState, ua: UpdatesActions, status: @Composable (embedded: Boolean) -> Unit) { val colors = MaterialTheme.colorScheme var query by rememberSaveable { mutableStateOf("") } val needle = query.trim().removePrefix("#").removePrefix("@") @@ -686,18 +702,24 @@ private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesS val (ready, old) = matches.partition { it.versionCode >= me.versionCode } val followedOld = u.follow.channel == Channel.TEST && old.any { it.pr == u.follow.pr } var showOld by rememberSaveable { mutableStateOf(false) } - Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { - if (tests.size > 5 || query.isNotEmpty()) AdbTextField( - value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find), - keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false, - placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(), - ) - if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp)) - ready.forEach { t -> TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST) { ua.onFollow(Follow(Channel.TEST, t.pr)) } } - if (old.isNotEmpty()) { - MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld } - if (showOld || followedOld || needle.isNotEmpty()) old.forEach { t -> - TestRow(t, u.follow.pr == t.pr && u.follow.channel == Channel.TEST, tooOld = true) { ua.onFollow(Follow(Channel.TEST, t.pr)) } + val oldShown = showOld || followedOld || needle.isNotEmpty() + val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST } + val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed })) + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + if (!rowShown) status(false) + Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + if (tests.size > 5 || query.isNotEmpty()) AdbTextField( + value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find), + keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, compact = true, showLabel = false, + placeholder = stringResource(R.string.upd_tests_find), modifier = Modifier.fillMaxWidth(), + ) + if (matches.isEmpty()) Text(stringResource(R.string.upd_tests_no_match), fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(4.dp)) + ready.forEach { t -> TestRow(t, followed == t.pr, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) } } + if (old.isNotEmpty()) { + MoreLink(stringResource(R.string.upd_tests_old, old.size, me.versionCode), "tests:old") { showOld = !showOld } + if (oldShown) old.forEach { t -> + TestRow(t, followed == t.pr, tooOld = true, status = status) { ua.onFollow(Follow(Channel.TEST, t.pr)) } + } } } } @@ -712,40 +734,46 @@ private fun RadioDot(selected: Boolean, size: androidx.compose.ui.unit.Dp = 22.d } @Composable -private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, onClick: () -> Unit) { +private fun TestRow(t: Release, selected: Boolean, tooOld: Boolean = false, status: @Composable (embedded: Boolean) -> Unit, 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(12.dp), - modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}") - .heightIn(min = 52.dp) - .clip(Shape12) - .background(colors.surface).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) - .glideBorder(hot, Shape12, pal.signal, pal.line) - .alpha(if (tooOld && !selected) 0.6f else 1f) - .hoverable(src) - .clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick) - .controllerConfirm(onClick = onClick) - .padding(horizontal = 12.dp, vertical = 8.dp), + Column( + Modifier.fillMaxWidth().clip(Shape12).background(colors.surface) + .glideBorder(hot, Shape12, pal.signal, if (selected) pal.signal.copy(alpha = 0.5f) else pal.line), ) { - Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant) - Column(Modifier.weight(1f)) { - Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) - val detail = when { - t.apk == null -> stringResource(R.string.upd_not_built) - tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode) - else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = Modifier.fillMaxWidth().paneItem("test:${t.pr}") + .heightIn(min = 52.dp) + .background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + .alpha(if (tooOld && !selected) 0.6f else 1f) + .hoverable(src) + .clickable(interactionSource = src, indication = null, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(onClick = onClick) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) { + Text("#${t.pr}", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = if (selected) pal.signal else colors.onSurfaceVariant) + Column(Modifier.weight(1f)) { + Text(changeTitle(t.title.ifBlank { stringResource(R.string.upd_pr, t.pr) }), fontSize = 13.5.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + val detail = when { + t.apk == null -> stringResource(R.string.upd_not_built) + tooOld -> stringResource(R.string.upd_tests_old_row, t.versionCode) + else -> stringResource(R.string.upd_updated, ago(t.builtAt.takeIf { it > 0 } ?: t.publishedAt)) + } + Text( + listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "), + fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis) } - Text( - listOfNotNull(detail, t.author.takeIf { it.isNotEmpty() }?.let { "@$it" }, t.shortCommit).joinToString(" · "), - fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - ) - if (t.newerCommitPushed) Text(stringResource(R.string.upd_newer_commit_short), fontSize = 12.sp, color = AttentionAmber, maxLines = 1, overflow = TextOverflow.Ellipsis) + RadioDot(selected, 20.dp) + } + AnimatedVisibility(selected, enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) { + status(true) } - RadioDot(selected, 20.dp) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 158461750a..ed8b435d3f 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1224,6 +1224,10 @@ Not loaded: %1$s Waiting for a restart Kept + + %d kept build + %d kept builds + For another version Rebuild Deletes this build from the device From c514c59018046600c49c67de7e2ea7537577e115 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:56:05 -0500 Subject: [PATCH 45/80] Settings search: open the result's row, scroll to it and flash it (#3657) * Settings search: open the result's row, scroll to it and flash it * Opt in to the foundation API the search target uses --- .../com/droiddeck/launcher/ui/SettingsJump.kt | 62 +++++++++++++++++++ .../droiddeck/launcher/ui/SettingsSearch.kt | 7 ++- .../droiddeck/launcher/ui/SettingsWidgets.kt | 8 +-- 3 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/SettingsJump.kt diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsJump.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsJump.kt new file mode 100644 index 0000000000..cf50f10701 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsJump.kt @@ -0,0 +1,62 @@ +package com.droiddeck.launcher.ui + +import android.os.SystemClock +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.tween +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.staticCompositionLocalOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind + +/** The row a settings search result opens, so the page it lands on can scroll to it and flash it. */ +internal object SettingsJump { + class Target(val label: String, val at: Long = SystemClock.uptimeMillis()) + + var target: Target? by mutableStateOf(null) + + fun to(label: String) { target = Target(label) } +} + +private const val JUMP_WINDOW_MS = 5_000L + +/** False in the search results, whose rows carry the same labels as the rows they open. */ +internal val LocalSearchTargets = staticCompositionLocalOf { true } + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +internal fun Modifier.searchTarget(label: String): Modifier { + val pal = LocalPalette.current + val flash = remember { Animatable(0f) } + val reveal = remember { BringIntoViewRequester() } + var claimed by remember { mutableStateOf(null) } + val target = SettingsJump.target.takeIf { LocalSearchTargets.current } + if (target != null && target.label == label) SideEffect { + if (SettingsJump.target === target) { + SettingsJump.target = null + if (SystemClock.uptimeMillis() - target.at <= JUMP_WINDOW_MS) claimed = target + } + } + claimed?.let { mine -> + LaunchedEffect(mine) { + withFrameNanos { } + reveal.bringIntoView() + repeat(2) { + flash.animateTo(1f, tween(220)) + flash.animateTo(0f, tween(420)) + } + claimed = null + } + } + return bringIntoViewRequester(reveal).drawBehind { + if (flash.value > 0f) drawRect(pal.signal.copy(alpha = 0.28f * flash.value)) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt index e195b4ee8e..b76a5157f9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -103,7 +103,7 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti Note(stringResource(R.string.settings_search_none, query.trim())) return } - Column { + androidx.compose.runtime.CompositionLocalProvider(LocalSearchTargets provides false) { Column { found.groupBy { it.place }.forEach { (place, entries) -> SettingsGroup(stringResource(place.title)) { entries.forEach { entry -> @@ -112,9 +112,10 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti val section = entry.section val tab = entry.tab if (section != null) { - ActionRow(title, within, stringResource(R.string.store_open), onClick = { onOpen(section) }) + ActionRow(title, within, stringResource(R.string.store_open), onClick = { SettingsJump.to(title); onOpen(section) }) } else if (tab != null) { ActionRow(title, within, stringResource(R.string.store_open), onClick = { + SettingsJump.to(title) if (tab == NavTabs.MORE) MoreTabs.editing = true if (tab == "downloads") DownloadsNav.showSettings = true RailRequest.key = tab @@ -125,5 +126,5 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (Setti } } } - } + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 5d09490e39..52ba78a7d6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -536,7 +536,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis) } if (compact && !stacked) Column( - modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp), + modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 10.dp, vertical = 6.dp), ) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Text(label, fontSize = 13.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, @@ -545,7 +545,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint } if (hint != null || hintLines != null) hintText(11.sp) } else if (stacked || LocalNarrowPane.current) Column( - modifier = Modifier.fillMaxWidth().background(bg).padding( + modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding( horizontal = if (compact) 10.dp else 14.dp, vertical = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 12.dp), ) { @@ -556,7 +556,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hint Box(Modifier.padding(top = if (tightControlSpacing) 2.dp else if (compact) 6.dp else 8.dp)) { control() } } else Row( verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp), + modifier = Modifier.searchTarget(label).fillMaxWidth().background(bg).padding(horizontal = 14.dp, vertical = 11.dp), ) { Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) @@ -660,7 +660,7 @@ fun SliderRow( ) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Column(Modifier.fillMaxWidth()) { + Column(Modifier.searchTarget(label).fillMaxWidth()) { ValueSlider(value, range, step, enabled, label, format, modifier = modifier.padding(horizontal = 6.dp, vertical = 3.dp), onChange = onChange) if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, From ecbda604e20db111f729ad34604b8b41dfd70b1c Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:56:53 -0500 Subject: [PATCH 46/80] ci: save the Robolectric jar cache from main only (#3604) A pull request's cache entry is visible only to that pull request, so each PR stored its own ~830 MB copy that no other PR could restore, while new PRs started from main's incomplete set and downloaded the rest from Maven Central, where the 429s come from. The copies also kept the repository at its 10 GB cache limit and pushed out other caches. --- .github/workflows/unit-tests.yml | 4 +++- tools/tests/test_ci_checks.py | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index a2ef6cfe8e..663bd30e6a 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -178,8 +178,10 @@ jobs: PY after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l) [ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true + # A pull request's cache is visible only to that pull request, and each copy is hundreds of megabytes against the + # repository's 10 GB cache limit. Only main saves, so every pull request restores main's set. - name: Store Robolectric's Android jars - if: always() && steps.robolectric-jars-final.outputs.save == 'true' + if: always() && github.event_name != 'pull_request' && steps.robolectric-jars-final.outputs.save == 'true' uses: actions/cache/save@v4 with: path: ${{ steps.robolectric-jars.outputs.path }} diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index 8e3b7e9880..1e7995a3d2 100644 --- a/tools/tests/test_ci_checks.py +++ b/tools/tests/test_ci_checks.py @@ -33,6 +33,13 @@ class CiChecksTest(unittest.TestCase): robolectric = [cache['path'] for cache in caches if cache['key'].startswith('robolectric-')] self.assertEqual(robolectric, ['${{ steps.robolectric-jars.outputs.path }}'] * 2) + def test_only_main_saves_the_robolectric_cache(self): + steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] + saves = [step for step in steps if step.get('uses', '').startswith('actions/cache/save') + and step['with']['key'].startswith('robolectric-')] + self.assertEqual(len(saves), 1) + self.assertIn("github.event_name != 'pull_request'", saves[0]['if']) + def test_unit_test_retry_requires_maven_exception(self): steps = yaml.safe_load((ROOT / '.github/workflows/unit-tests.yml').read_text())['jobs']['unit-tests']['steps'] run = next(step['run'] for step in steps if step.get('id') == 'unit-tests') From ed763ecb9b1c3f1c7183acb1c6594eb1c429b84c Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:22:27 -0500 Subject: [PATCH 47/80] Let the session drawer expand to the screen's left edge (#3691) Keep the resize grip usable at full width and reserve its touch area from Android Back gestures. --- .../main/java/com/droiddeck/launcher/ui/SessionOverlay.kt | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) 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 2430aa45f9..26524d326e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -84,6 +84,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.systemGestureExclusion import androidx.compose.foundation.ScrollState import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.rememberScrollState @@ -548,8 +549,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.fillMaxSize().exposeTestTags(), contentAlignment = Alignment.CenterEnd) { val short = maxHeight < 440.dp - // The handle keeps a strip on the left free, so a sheet dragged wide can always be dragged back. - val maxSheet = (maxWidth - DRAWER_EDGE_GAP).coerceAtLeast(0.dp) + // At full width the handle's strip sits on the screen's left edge, so the sheet can still be dragged back. + val maxSheet = (maxWidth - DRAWER_HANDLE_STRIP).coerceAtLeast(0.dp) val minSheet = minOf(DRAWER_MIN_WIDTH, maxSheet) val defaultSheet = minOf(420.dp, maxWidth * 0.92f) val sheetWidth = if (docked) maxWidth else (savedWidth?.dp ?: defaultSheet).coerceIn(minSheet, maxSheet) @@ -1556,7 +1557,6 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole private val DRAWER_MIN_WIDTH = 300.dp private val DRAWER_HANDLE_STRIP = 24.dp -private val DRAWER_EDGE_GAP = 80.dp /** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */ @Composable @@ -1578,6 +1578,8 @@ private fun DrawerResizeHandle(width: Dp, min: Dp, max: Dp, onWidth: (Dp) -> Uni contentAlignment = Alignment.Center, modifier = modifier.width(24.dp).height(96.dp) .onGloballyPositioned { coords = it } + // On the screen's edge, Android's back swipe would take the drag. + .systemGestureExclusion() .focusable(true, source) .onPreviewKeyEvent { event -> val key = event.nativeKeyEvent From be98982cfc82f8ed573ea060d1ae93e68f831173 Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:29:44 -0400 Subject: [PATCH 48/80] Feat:Add Snapdragon X Elite and Adreno X1 GPU detection (#3671) * feat(gpu): add Snapdragon X and Adreno X1 detection * fix: resolve Snapdragon X PR conflicts and review findings * fix: resolve Snapdragon X PR conflicts and review findings * fix: resolve Snapdragon X PR conflicts and review findings * fix: resolve Snapdragon X PR conflicts and review findings * fix: resolve Snapdragon X PR conflicts and review findings * fix: resolve Snapdragon X PR conflicts and review findings * test: preserve current SoC mappings and cover QTI X1 fallback * test: preserve current SoC mappings and cover QTI X1 fallback * test: preserve current SoC mappings and cover QTI X1 fallback * fix: keep session TU_DEBUG policy authoritative * test: preserve explicit TU_DEBUG environment overrides * chore: remove unused GPU detection import * test: verify TU_DEBUG defaults stay session-owned * chore: restart PR CI * fix: remove duplicate game environment resolver * fix: preserve session TU_DEBUG defaults for Flatpak and Snap * fix: only export explicit game TU_DEBUG overrides * test: correct SoC platform fallback assertions * test: cover inherited session TU_DEBUG defaults * test: remove redundant GameEnvironment comment * fix: preserve Venus game sysmem setting * test: cover persisted Venus sysmem setting --- .../droiddeck/launcher/core/DeviceSupport.kt | 3 +- .../com/droiddeck/launcher/gpu/GpuInfo.kt | 44 +++++++++++++++---- .../com/droiddeck/launcher/gpu/SocNames.kt | 7 +++ .../launcher/session/SessionService.kt | 29 +++++++++++- .../launcher/session/TurnipEnvironment.kt | 4 +- .../launcher/core/GameEnvironmentTest.kt | 7 +++ .../launcher/gpu/GpuModelFallbackTest.kt | 30 +++++++++++++ .../droiddeck/launcher/gpu/SocNamesTest.kt | 8 ++++ .../launcher/session/SessionTuDebugTest.kt | 33 ++++++++++++++ .../launcher/session/TurnipEnvironmentTest.kt | 20 ++++----- 10 files changed, 160 insertions(+), 25 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index a063f251da..48c4ca3861 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -8,7 +8,8 @@ import java.io.File object DeviceSupport { private val adrenoGpu by lazy { - File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() + File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() || + runCatching { File("/sys/class/drm/renderD128/device/driver").canonicalFile.name in setOf("msm", "msm_drm") }.getOrDefault(false) } fun adreno(): Boolean = adrenoGpu diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index 77cbdf55cf..d6168b2480 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -102,27 +102,35 @@ data class GpuInfo( private const val UNNAMED = "this GPU" fun detect(): GpuInfo { - val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() + val adreno = com.droiddeck.launcher.core.DeviceSupport.adreno() val raw = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_model"))?.trim() val chipId = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))?.trim().orEmpty() val soc = if (adreno) SocNames.label() else "" - val platformGpuModel = if (adreno) platformModel() else 0 + val platform = systemProperty("ro.board.platform") + val qtiSoc = systemProperty("ro.vendor.qti.soc_name") + val platformGpuModel = if (adreno) platformModel(platform = platform).takeIf { it > 0 } ?: platformModel(platform = qtiSoc) else 0 + val vulkan = VulkanInfo.cachedOrNull()?.get("device") val (model, source) = if (adreno) modelFromNames( raw, - { VulkanInfo.cachedOrNull()?.get("device") }, + { vulkan }, { platformGpuModel }, ) else 0 to "" // Mali, named by the vendor's Vulkan driver ("Mali-G720-Immortalis MC12") or by kbase. val mali = if (adreno || !File("/dev/mali0").exists()) null else maliName() val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr(), mali) val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) + val isX1 = model == 741 || Regex("""(?i)X1[-_](?:85|45)""").containsMatchIn(raw.orEmpty()) + val gpuDisplayName = when { + !adreno -> (Build.HARDWARE ?: "").ifBlank { UNNAMED } + isX1 -> x1Name(raw, vulkan, platform, qtiSoc) + model > 0 -> "Adreno $model" + else -> "Adreno" + } return GpuInfo( name = when { family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull()) mali != null && mali.isNotEmpty() -> mali - !adreno -> Build.HARDWARE.ifBlank { UNNAMED } - model > 0 -> "Adreno $model" - else -> "Adreno" + else -> gpuDisplayName }, model = model, family = family, soc = soc, oneUi8Gen2 = samsung && model == 740, @@ -137,6 +145,25 @@ data class GpuInfo( internal fun verifiedOn(model: Int, device: String): Boolean = model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true) + internal fun parseModel(text: String): Int { + if (Regex("""(?i)X1[-_]85|X1[-_]45|Adreno\s*741""").containsMatchIn(text)) return 741 + return threeDigits(text) + } + + internal fun x1Name( + raw: String? = null, + vulkan: String? = null, + platform: String = "", + qtiSoc: String = "", + ): String { + val names = listOfNotNull(raw, vulkan).joinToString(" ") + val p = platform.lowercase() + return when { + Regex("""(?i)X1[-_]45""").containsMatchIn(names) || p == "purwa" || qtiSoc.equals("purwa", ignoreCase = true) -> "Adreno X1-45" + Regex("""(?i)X1[-_]85""").containsMatchIn(names) || p in listOf("hamoa", "sc8380xp", "x1e80100") || qtiSoc.lowercase() in listOf("hamoa", "sc8380xp", "x1e80100") -> "Adreno X1-85" + else -> "Adreno X1" + } + } internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0 @@ -145,14 +172,15 @@ data class GpuInfo( vulkanName: () -> String?, fallback: () -> Int, ): Pair { - kernelName?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "kernel" } - vulkanName()?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "vulkan" } + kernelName?.let { parseModel(it) }?.takeIf { it > 0 }?.let { return it to "kernel" } + vulkanName()?.let { parseModel(it) }?.takeIf { it > 0 }?.let { return it to "vulkan" } return fallback().let { if (it > 0) it to "platform" else 0 to "" } } private val PLATFORMS = mapOf( "msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730, "kalama" to 740, "pineapple" to 750, "sun" to 830, + "hamoa" to 741, "sc8380xp" to 741, "x1e80100" to 741, "purwa" to 741, ) internal fun platformModel( diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt index 7916c01467..8d508dc16f 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt @@ -16,12 +16,19 @@ object SocNames { "SM6375" to "Snapdragon 695", // Handheld parts: AYANEO Pocket FIT (SG8350P), Retroid Pocket Duo (CQ7790S). "SG8350P" to "Snapdragon G3 Gen 3", "CQ7790S" to "Dragonwing Q-7790", + "SC8380XP" to "Snapdragon X Elite", "X1E80100" to "Snapdragon X Elite", "X1E-80-100" to "Snapdragon X Elite", + "X1E84100" to "Snapdragon X Elite", "X1E-84-100" to "Snapdragon X Elite", + "X1E78100" to "Snapdragon X Elite", "X1E-78-100" to "Snapdragon X Elite", + "X1P64100" to "Snapdragon X Plus", "X1P-64-100" to "Snapdragon X Plus", + "X1P42100" to "Snapdragon X Plus", "X1P-42-100" to "Snapdragon X Plus", ) private val PLATFORMS = mapOf( "msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888", "taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2", "pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite", "canoe" to "Snapdragon 8 Elite Gen 5", + "hamoa" to "Snapdragon X Elite", "purwa" to "Snapdragon X Plus", + "sc8380xp" to "Snapdragon X Elite", "x1e80100" to "Snapdragon X Elite", ) fun model(prop: (String) -> String = GpuInfo::systemProperty): String { 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 67992024db..a416c360dc 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.core.AddonPack +import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager import com.droiddeck.launcher.gpu.SystemVulkanDriver @@ -1128,7 +1129,7 @@ class SessionService : Service() { } val tuOverride = tuDebugOverride() val tuDriver = sysmemDriver(linuxDriverId) - if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") } + if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) tuDebugFor(tuOverride, SessionPrefs.tuSysmem(this), if (tuDriver) "710-720" else "", GpuInfo.detect().model)?.let { guest.add("TU_DEBUG=$it") } if (SessionPrefs.zinkLazy(this)) { guest.add("ZINK_DESCRIPTORS=lazy") guest.add("ZINK_DEBUG=compact") @@ -1165,7 +1166,12 @@ class SessionService : Service() { } guest.add("AUDIO_DIRECT_DECAY=0") val extra = customEnvironment + agentEnvironment - guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra)) + val gameTuOverride = if (venus) { + tuDebugFor(tuOverride, SessionPrefs.tuSysmem(this), if (tuDriver) "710-720" else "", GpuInfo.detect().model) + } else { + tuOverride + } + guest.addAll(TurnipEnvironment.gameEnvironment(gameTuOverride, extra)) if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=") extra.forEach { guest.add(it) } com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") } @@ -2720,6 +2726,25 @@ class SessionService : Service() { private const val MIC_RELEASE_TIMEOUT_MS = 5_000L private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug" private const val GAME_PREFIX = "DROIDDECK_GAME_" + internal fun tuDebugFor( + override: String?, + tuSysmem: Boolean, + driverName: String, + gpuModel: Int = GpuInfo.detect().model + ): String? { + if (!override.isNullOrEmpty()) return override + val flags = mutableListOf() + if (tuSysmem || driverName.contains("710-720") || driverName.contains("710_720")) { + flags.add("sysmem") + } + if (gpuModel == 741) { + flags.add("nolrz") + flags.add("nolrzfc") + } + return if (flags.isNotEmpty()) flags.joinToString(",") else null + } + + private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG" private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env" private const val ENV_SWITCH_NAME = "droiddeck-env" diff --git a/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt index 7fc460b3f6..d2c4be588f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt @@ -5,11 +5,9 @@ internal object TurnipEnvironment { fun gameEnvironment( tuOverride: String?, - tuDriver: Boolean, - tuSysmem: Boolean, extra: List, ): List = if (extra.none { it.startsWith("TU_DEBUG=") }) { - listOf("$GAME_TU_DEBUG=${tuOverride ?: if (tuDriver || tuSysmem) "sysmem" else ""}") + tuOverride?.let { listOf("$GAME_TU_DEBUG=$it") }.orEmpty() } else { emptyList() } diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt index f4a27ea825..e991e7bd30 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -122,6 +122,13 @@ class GameEnvironmentTest { for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope)) } + @Test fun sessionOwnsGpuSpecificTuDebugDefaults() { + assertNull(GameEnvironment.defaults("")["TU_DEBUG"]) + + val config = GameEnvironment.Config(shared = mapOf("TU_DEBUG" to "noubwc")) + assertEquals("noubwc", GameEnvironment.effective(config, "", "42")["TU_DEBUG"]) + } + @Test fun gameFexPresetOverridesGeneralAndCanInheritAgain() { val performance = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "42", "PERFORMANCE") assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(performance, "42")) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt index 24a38bd75a..0a71385331 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt @@ -8,8 +8,38 @@ class GpuModelFallbackTest { assertEquals(750, GpuInfo.platformModel("pineapple")) assertEquals(740, GpuInfo.platformModel("KALAMA")) assertEquals(830, GpuInfo.platformModel("sun")) + assertEquals(741, GpuInfo.platformModel("hamoa")) + assertEquals(741, GpuInfo.platformModel("sc8380xp")) + assertEquals(741, GpuInfo.platformModel("x1e80100")) + assertEquals(741, GpuInfo.platformModel("purwa")) assertEquals(0, GpuInfo.platformModel("somethingelse")) assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple"))) + assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("hamoa"))) + } + + @Test fun alphanumericModelNamesAreParsed() { + assertEquals(741, GpuInfo.parseModel("Adreno X1-85")) + assertEquals(741, GpuInfo.parseModel("Adreno(TM) X1-85")) + assertEquals(741, GpuInfo.parseModel("X1-45")) + assertEquals(741, GpuInfo.parseModel("Adreno 741")) + assertEquals(750, GpuInfo.parseModel("Adreno750")) + assertEquals(0, GpuInfo.parseModel("unknown")) + } + + @Test fun x1VariantNamesAreDistinguished() { + assertEquals("Adreno X1-85", GpuInfo.x1Name(raw = "Adreno X1-85")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(vulkan = "Adreno(TM) X1-85")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "hamoa")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "sc8380xp")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "x1e80100")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(raw = "Adreno X1-45")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(vulkan = "Adreno(TM) X1-45")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(platform = "purwa")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(platform = "unknown", qtiSoc = "purwa")) + assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "unknown", qtiSoc = "hamoa")) + assertEquals("Adreno X1-45", GpuInfo.x1Name(raw = "X1-45", platform = "hamoa")) + assertEquals("Adreno X1", GpuInfo.x1Name(raw = "Adreno 741", platform = "unknown")) + assertEquals("Adreno X1", GpuInfo.x1Name()) } @Test fun sm8975IsTheOnlyNewSocFallback() { assertEquals(850, GpuInfo.platformModel("unknown", "", "SM8975")) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt index 8715069bd7..15a60df8c8 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt @@ -20,6 +20,14 @@ class SocNamesTest { assertNull(SocNames.name("XYZ123", "nowhere")) assertEquals("Snapdragon 8 Gen 2 (QCS8550)", SocNames.label("QCS8550", "")) assertEquals("Snapdragon G3 Gen 3 (SG8350P)", SocNames.label("SG8350P", "pineapple")) + assertEquals("Snapdragon X Elite", SocNames.name("SC8380XP", "")) + assertEquals("Snapdragon X Elite", SocNames.name("X1E80100", "")) + assertEquals("Snapdragon X Elite family", SocNames.name("", "hamoa")) + assertNull(SocNames.name("other", "hamoa")) + assertEquals("other", SocNames.label("other", "hamoa")) + assertEquals("Snapdragon X Plus family", SocNames.name("", "purwa")) + assertEquals("Snapdragon X Elite (SC8380XP)", SocNames.label("SC8380XP", "hamoa")) + assertEquals("Snapdragon X Elite family", SocNames.label("", "hamoa")) assertEquals("XYZ123", SocNames.label("XYZ123", "")) } @Test fun platformFamilyOnlyForPhonePartsOrNoModel() { diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt new file mode 100644 index 0000000000..41402007c2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt @@ -0,0 +1,33 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class SessionTuDebugTest { + @Test fun overrideFileWinsOverEverything() { + assertEquals("noubwc", SessionService.tuDebugFor("noubwc", tuSysmem = true, driverName = "710-720", gpuModel = 741)) + } + + @Test fun x185DefaultsToNolrzAndNolrzfc() { + assertEquals("nolrz,nolrzfc", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "", gpuModel = 741)) + } + + @Test fun a710FamilyGetsSysmem() { + assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "Turnip-v24-710-720", gpuModel = 730)) + assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "Turnip_710_720", gpuModel = 730)) + } + + @Test fun tuSysmemPreferenceAddsSysmem() { + assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = true, driverName = "", gpuModel = 740)) + } + + @Test fun combinesSysmemAndNolrzWhenBothApply() { + assertEquals("sysmem,nolrz,nolrzfc", SessionService.tuDebugFor(override = null, tuSysmem = true, driverName = "", gpuModel = 741)) + } + + @Test fun otherGpusDefaultToNull() { + assertNull(SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "turnip-v24", gpuModel = 740)) + assertNull(SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "turnip-v24", gpuModel = 825)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt index c452f7e64c..33b879a183 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt @@ -4,23 +4,21 @@ import org.junit.Assert.assertEquals import org.junit.Test class TurnipEnvironmentTest { - @Test fun sysmemSettingAppliesToGames() { - assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=sysmem"), TurnipEnvironment.gameEnvironment(null, false, true, emptyList())) + @Test fun noExplicitOverrideLeavesSessionGpuDefaultInPlace() { + assertEquals(emptyList(), TurnipEnvironment.gameEnvironment(null, emptyList())) } - @Test fun disablingSysmemKeepsTheDriverDefault() { - assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG="), TurnipEnvironment.gameEnvironment(null, false, false, emptyList())) + @Test fun overrideIsPassedToGames() { + assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=nolrz"), TurnipEnvironment.gameEnvironment("nolrz", emptyList())) } - @Test fun overrideWinsOverTheSetting() { - assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=nolrz"), TurnipEnvironment.gameEnvironment("nolrz", false, true, emptyList())) - } - - @Test fun sysmemDriverForcesSysmem() { - assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=sysmem"), TurnipEnvironment.gameEnvironment(null, true, false, emptyList())) + @Test fun persistedSysmemIsPassedToVenusGames() { + val venusTuDebug = SessionService.tuDebugFor(null, tuSysmem = true, driverName = "", gpuModel = 0) + assertEquals("sysmem", venusTuDebug) + assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=sysmem"), TurnipEnvironment.gameEnvironment(venusTuDebug, emptyList())) } @Test fun gameEnvironmentOverrideWins() { - assertEquals(emptyList(), TurnipEnvironment.gameEnvironment(null, false, true, listOf("TU_DEBUG=nolrz"))) + assertEquals(emptyList(), TurnipEnvironment.gameEnvironment(null, listOf("TU_DEBUG=nolrz"))) } } From 1d1c29517ae1ea0f85aa8950bd77f8c488d3faac Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:30:22 -0500 Subject: [PATCH 49/80] Revert "Feat:Add Snapdragon X Elite and Adreno X1 GPU detection" (#3695) Revert "Feat:Add Snapdragon X Elite and Adreno X1 GPU detection (#3671)" This reverts commit be98982cfc82f8ed573ea060d1ae93e68f831173. --- .../droiddeck/launcher/core/DeviceSupport.kt | 3 +- .../com/droiddeck/launcher/gpu/GpuInfo.kt | 44 ++++--------------- .../com/droiddeck/launcher/gpu/SocNames.kt | 7 --- .../launcher/session/SessionService.kt | 29 +----------- .../launcher/session/TurnipEnvironment.kt | 4 +- .../launcher/core/GameEnvironmentTest.kt | 7 --- .../launcher/gpu/GpuModelFallbackTest.kt | 30 ------------- .../droiddeck/launcher/gpu/SocNamesTest.kt | 8 ---- .../launcher/session/SessionTuDebugTest.kt | 33 -------------- .../launcher/session/TurnipEnvironmentTest.kt | 20 +++++---- 10 files changed, 25 insertions(+), 160 deletions(-) delete mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt index 48c4ca3861..a063f251da 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceSupport.kt @@ -8,8 +8,7 @@ import java.io.File object DeviceSupport { private val adrenoGpu by lazy { - File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() || - runCatching { File("/sys/class/drm/renderD128/device/driver").canonicalFile.name in setOf("msm", "msm_drm") }.getOrDefault(false) + File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() } fun adreno(): Boolean = adrenoGpu diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index d6168b2480..77cbdf55cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -102,35 +102,27 @@ data class GpuInfo( private const val UNNAMED = "this GPU" fun detect(): GpuInfo { - val adreno = com.droiddeck.launcher.core.DeviceSupport.adreno() + val adreno = File("/sys/class/kgsl/kgsl-3d0").exists() || File("/vendor/lib64/hw/vulkan.adreno.so").exists() val raw = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_model"))?.trim() val chipId = FileUtils.readString(File("/sys/class/kgsl/kgsl-3d0/gpu_chipid"))?.trim().orEmpty() val soc = if (adreno) SocNames.label() else "" - val platform = systemProperty("ro.board.platform") - val qtiSoc = systemProperty("ro.vendor.qti.soc_name") - val platformGpuModel = if (adreno) platformModel(platform = platform).takeIf { it > 0 } ?: platformModel(platform = qtiSoc) else 0 - val vulkan = VulkanInfo.cachedOrNull()?.get("device") + val platformGpuModel = if (adreno) platformModel() else 0 val (model, source) = if (adreno) modelFromNames( raw, - { vulkan }, + { VulkanInfo.cachedOrNull()?.get("device") }, { platformGpuModel }, ) else 0 to "" // Mali, named by the vendor's Vulkan driver ("Mali-G720-Immortalis MC12") or by kbase. val mali = if (adreno || !File("/dev/mali0").exists()) null else maliName() val family = familyOf(adreno, model, SystemVulkanDriver.isPowerVr(), mali) val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) - val isX1 = model == 741 || Regex("""(?i)X1[-_](?:85|45)""").containsMatchIn(raw.orEmpty()) - val gpuDisplayName = when { - !adreno -> (Build.HARDWARE ?: "").ifBlank { UNNAMED } - isX1 -> x1Name(raw, vulkan, platform, qtiSoc) - model > 0 -> "Adreno $model" - else -> "Adreno" - } return GpuInfo( name = when { family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull()) mali != null && mali.isNotEmpty() -> mali - else -> gpuDisplayName + !adreno -> Build.HARDWARE.ifBlank { UNNAMED } + model > 0 -> "Adreno $model" + else -> "Adreno" }, model = model, family = family, soc = soc, oneUi8Gen2 = samsung && model == 740, @@ -145,25 +137,6 @@ data class GpuInfo( internal fun verifiedOn(model: Int, device: String): Boolean = model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true) - internal fun parseModel(text: String): Int { - if (Regex("""(?i)X1[-_]85|X1[-_]45|Adreno\s*741""").containsMatchIn(text)) return 741 - return threeDigits(text) - } - - internal fun x1Name( - raw: String? = null, - vulkan: String? = null, - platform: String = "", - qtiSoc: String = "", - ): String { - val names = listOfNotNull(raw, vulkan).joinToString(" ") - val p = platform.lowercase() - return when { - Regex("""(?i)X1[-_]45""").containsMatchIn(names) || p == "purwa" || qtiSoc.equals("purwa", ignoreCase = true) -> "Adreno X1-45" - Regex("""(?i)X1[-_]85""").containsMatchIn(names) || p in listOf("hamoa", "sc8380xp", "x1e80100") || qtiSoc.lowercase() in listOf("hamoa", "sc8380xp", "x1e80100") -> "Adreno X1-85" - else -> "Adreno X1" - } - } internal fun threeDigits(text: String): Int = Regex("""(?i)\badreno\s*(?:\(TM\)\s*)?(\d{3})(?!\d)""").find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0 @@ -172,15 +145,14 @@ data class GpuInfo( vulkanName: () -> String?, fallback: () -> Int, ): Pair { - kernelName?.let { parseModel(it) }?.takeIf { it > 0 }?.let { return it to "kernel" } - vulkanName()?.let { parseModel(it) }?.takeIf { it > 0 }?.let { return it to "vulkan" } + kernelName?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "kernel" } + vulkanName()?.let { threeDigits(it) }?.takeIf { it > 0 }?.let { return it to "vulkan" } return fallback().let { if (it > 0) it to "platform" else 0 to "" } } private val PLATFORMS = mapOf( "msmnile" to 640, "kona" to 650, "lahaina" to 660, "taro" to 730, "cape" to 730, "kalama" to 740, "pineapple" to 750, "sun" to 830, - "hamoa" to 741, "sc8380xp" to 741, "x1e80100" to 741, "purwa" to 741, ) internal fun platformModel( diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt index 8d508dc16f..7916c01467 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SocNames.kt @@ -16,19 +16,12 @@ object SocNames { "SM6375" to "Snapdragon 695", // Handheld parts: AYANEO Pocket FIT (SG8350P), Retroid Pocket Duo (CQ7790S). "SG8350P" to "Snapdragon G3 Gen 3", "CQ7790S" to "Dragonwing Q-7790", - "SC8380XP" to "Snapdragon X Elite", "X1E80100" to "Snapdragon X Elite", "X1E-80-100" to "Snapdragon X Elite", - "X1E84100" to "Snapdragon X Elite", "X1E-84-100" to "Snapdragon X Elite", - "X1E78100" to "Snapdragon X Elite", "X1E-78-100" to "Snapdragon X Elite", - "X1P64100" to "Snapdragon X Plus", "X1P-64-100" to "Snapdragon X Plus", - "X1P42100" to "Snapdragon X Plus", "X1P-42-100" to "Snapdragon X Plus", ) private val PLATFORMS = mapOf( "msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888", "taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2", "pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite", "canoe" to "Snapdragon 8 Elite Gen 5", - "hamoa" to "Snapdragon X Elite", "purwa" to "Snapdragon X Plus", - "sc8380xp" to "Snapdragon X Elite", "x1e80100" to "Snapdragon X Elite", ) fun model(prop: (String) -> String = GpuInfo::systemProperty): String { 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 a416c360dc..67992024db 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1,7 +1,6 @@ package com.droiddeck.launcher.session import com.droiddeck.launcher.core.AddonPack -import com.droiddeck.launcher.gpu.GpuInfo import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager import com.droiddeck.launcher.gpu.SystemVulkanDriver @@ -1129,7 +1128,7 @@ class SessionService : Service() { } val tuOverride = tuDebugOverride() val tuDriver = sysmemDriver(linuxDriverId) - if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) tuDebugFor(tuOverride, SessionPrefs.tuSysmem(this), if (tuDriver) "710-720" else "", GpuInfo.detect().model)?.let { guest.add("TU_DEBUG=$it") } + if (!venus && com.droiddeck.launcher.core.DeviceSupport.adreno()) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") } if (SessionPrefs.zinkLazy(this)) { guest.add("ZINK_DESCRIPTORS=lazy") guest.add("ZINK_DEBUG=compact") @@ -1166,12 +1165,7 @@ class SessionService : Service() { } guest.add("AUDIO_DIRECT_DECAY=0") val extra = customEnvironment + agentEnvironment - val gameTuOverride = if (venus) { - tuDebugFor(tuOverride, SessionPrefs.tuSysmem(this), if (tuDriver) "710-720" else "", GpuInfo.detect().model) - } else { - tuOverride - } - guest.addAll(TurnipEnvironment.gameEnvironment(gameTuOverride, extra)) + 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) } com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") } @@ -2726,25 +2720,6 @@ class SessionService : Service() { private const val MIC_RELEASE_TIMEOUT_MS = 5_000L private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug" private const val GAME_PREFIX = "DROIDDECK_GAME_" - internal fun tuDebugFor( - override: String?, - tuSysmem: Boolean, - driverName: String, - gpuModel: Int = GpuInfo.detect().model - ): String? { - if (!override.isNullOrEmpty()) return override - val flags = mutableListOf() - if (tuSysmem || driverName.contains("710-720") || driverName.contains("710_720")) { - flags.add("sysmem") - } - if (gpuModel == 741) { - flags.add("nolrz") - flags.add("nolrzfc") - } - return if (flags.isNotEmpty()) flags.joinToString(",") else null - } - - private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG" private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env" private const val ENV_SWITCH_NAME = "droiddeck-env" diff --git a/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt index d2c4be588f..7fc460b3f6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/TurnipEnvironment.kt @@ -5,9 +5,11 @@ internal object TurnipEnvironment { fun gameEnvironment( tuOverride: String?, + tuDriver: Boolean, + tuSysmem: Boolean, extra: List, ): List = if (extra.none { it.startsWith("TU_DEBUG=") }) { - tuOverride?.let { listOf("$GAME_TU_DEBUG=$it") }.orEmpty() + listOf("$GAME_TU_DEBUG=${tuOverride ?: if (tuDriver || tuSysmem) "sysmem" else ""}") } else { emptyList() } diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt index e991e7bd30..f4a27ea825 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -122,13 +122,6 @@ class GameEnvironmentTest { for (scope in listOf("0", "-1", "01", "+1", "4294967296", "../42")) assertFalse(GameEnvironment.validScope(scope)) } - @Test fun sessionOwnsGpuSpecificTuDebugDefaults() { - assertNull(GameEnvironment.defaults("")["TU_DEBUG"]) - - val config = GameEnvironment.Config(shared = mapOf("TU_DEBUG" to "noubwc")) - assertEquals("noubwc", GameEnvironment.effective(config, "", "42")["TU_DEBUG"]) - } - @Test fun gameFexPresetOverridesGeneralAndCanInheritAgain() { val performance = GameEnvironment.withGameFexPreset(GameEnvironment.Config(), "42", "PERFORMANCE") assertEquals("PERFORMANCE", GameEnvironment.gameFexPreset(performance, "42")) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt index 0a71385331..24a38bd75a 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/GpuModelFallbackTest.kt @@ -8,38 +8,8 @@ class GpuModelFallbackTest { assertEquals(750, GpuInfo.platformModel("pineapple")) assertEquals(740, GpuInfo.platformModel("KALAMA")) assertEquals(830, GpuInfo.platformModel("sun")) - assertEquals(741, GpuInfo.platformModel("hamoa")) - assertEquals(741, GpuInfo.platformModel("sc8380xp")) - assertEquals(741, GpuInfo.platformModel("x1e80100")) - assertEquals(741, GpuInfo.platformModel("purwa")) assertEquals(0, GpuInfo.platformModel("somethingelse")) assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("pineapple"))) - assertEquals(GpuInfo.Family.A7XX, GpuInfo.familyOf(true, GpuInfo.platformModel("hamoa"))) - } - - @Test fun alphanumericModelNamesAreParsed() { - assertEquals(741, GpuInfo.parseModel("Adreno X1-85")) - assertEquals(741, GpuInfo.parseModel("Adreno(TM) X1-85")) - assertEquals(741, GpuInfo.parseModel("X1-45")) - assertEquals(741, GpuInfo.parseModel("Adreno 741")) - assertEquals(750, GpuInfo.parseModel("Adreno750")) - assertEquals(0, GpuInfo.parseModel("unknown")) - } - - @Test fun x1VariantNamesAreDistinguished() { - assertEquals("Adreno X1-85", GpuInfo.x1Name(raw = "Adreno X1-85")) - assertEquals("Adreno X1-85", GpuInfo.x1Name(vulkan = "Adreno(TM) X1-85")) - assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "hamoa")) - assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "sc8380xp")) - assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "x1e80100")) - assertEquals("Adreno X1-45", GpuInfo.x1Name(raw = "Adreno X1-45")) - assertEquals("Adreno X1-45", GpuInfo.x1Name(vulkan = "Adreno(TM) X1-45")) - assertEquals("Adreno X1-45", GpuInfo.x1Name(platform = "purwa")) - assertEquals("Adreno X1-45", GpuInfo.x1Name(platform = "unknown", qtiSoc = "purwa")) - assertEquals("Adreno X1-85", GpuInfo.x1Name(platform = "unknown", qtiSoc = "hamoa")) - assertEquals("Adreno X1-45", GpuInfo.x1Name(raw = "X1-45", platform = "hamoa")) - assertEquals("Adreno X1", GpuInfo.x1Name(raw = "Adreno 741", platform = "unknown")) - assertEquals("Adreno X1", GpuInfo.x1Name()) } @Test fun sm8975IsTheOnlyNewSocFallback() { assertEquals(850, GpuInfo.platformModel("unknown", "", "SM8975")) diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt index 15a60df8c8..8715069bd7 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/SocNamesTest.kt @@ -20,14 +20,6 @@ class SocNamesTest { assertNull(SocNames.name("XYZ123", "nowhere")) assertEquals("Snapdragon 8 Gen 2 (QCS8550)", SocNames.label("QCS8550", "")) assertEquals("Snapdragon G3 Gen 3 (SG8350P)", SocNames.label("SG8350P", "pineapple")) - assertEquals("Snapdragon X Elite", SocNames.name("SC8380XP", "")) - assertEquals("Snapdragon X Elite", SocNames.name("X1E80100", "")) - assertEquals("Snapdragon X Elite family", SocNames.name("", "hamoa")) - assertNull(SocNames.name("other", "hamoa")) - assertEquals("other", SocNames.label("other", "hamoa")) - assertEquals("Snapdragon X Plus family", SocNames.name("", "purwa")) - assertEquals("Snapdragon X Elite (SC8380XP)", SocNames.label("SC8380XP", "hamoa")) - assertEquals("Snapdragon X Elite family", SocNames.label("", "hamoa")) assertEquals("XYZ123", SocNames.label("XYZ123", "")) } @Test fun platformFamilyOnlyForPhonePartsOrNoModel() { diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt deleted file mode 100644 index 41402007c2..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionTuDebugTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.droiddeck.launcher.session - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Test - -class SessionTuDebugTest { - @Test fun overrideFileWinsOverEverything() { - assertEquals("noubwc", SessionService.tuDebugFor("noubwc", tuSysmem = true, driverName = "710-720", gpuModel = 741)) - } - - @Test fun x185DefaultsToNolrzAndNolrzfc() { - assertEquals("nolrz,nolrzfc", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "", gpuModel = 741)) - } - - @Test fun a710FamilyGetsSysmem() { - assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "Turnip-v24-710-720", gpuModel = 730)) - assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "Turnip_710_720", gpuModel = 730)) - } - - @Test fun tuSysmemPreferenceAddsSysmem() { - assertEquals("sysmem", SessionService.tuDebugFor(override = null, tuSysmem = true, driverName = "", gpuModel = 740)) - } - - @Test fun combinesSysmemAndNolrzWhenBothApply() { - assertEquals("sysmem,nolrz,nolrzfc", SessionService.tuDebugFor(override = null, tuSysmem = true, driverName = "", gpuModel = 741)) - } - - @Test fun otherGpusDefaultToNull() { - assertNull(SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "turnip-v24", gpuModel = 740)) - assertNull(SessionService.tuDebugFor(override = null, tuSysmem = false, driverName = "turnip-v24", gpuModel = 825)) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt index 33b879a183..c452f7e64c 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/TurnipEnvironmentTest.kt @@ -4,21 +4,23 @@ import org.junit.Assert.assertEquals import org.junit.Test class TurnipEnvironmentTest { - @Test fun noExplicitOverrideLeavesSessionGpuDefaultInPlace() { - assertEquals(emptyList(), TurnipEnvironment.gameEnvironment(null, emptyList())) + @Test fun sysmemSettingAppliesToGames() { + assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=sysmem"), TurnipEnvironment.gameEnvironment(null, false, true, emptyList())) } - @Test fun overrideIsPassedToGames() { - assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=nolrz"), TurnipEnvironment.gameEnvironment("nolrz", emptyList())) + @Test fun disablingSysmemKeepsTheDriverDefault() { + assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG="), TurnipEnvironment.gameEnvironment(null, false, false, emptyList())) } - @Test fun persistedSysmemIsPassedToVenusGames() { - val venusTuDebug = SessionService.tuDebugFor(null, tuSysmem = true, driverName = "", gpuModel = 0) - assertEquals("sysmem", venusTuDebug) - assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=sysmem"), TurnipEnvironment.gameEnvironment(venusTuDebug, emptyList())) + @Test fun overrideWinsOverTheSetting() { + assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=nolrz"), TurnipEnvironment.gameEnvironment("nolrz", false, true, emptyList())) + } + + @Test fun sysmemDriverForcesSysmem() { + assertEquals(listOf("DROIDDECK_GAME_TU_DEBUG=sysmem"), TurnipEnvironment.gameEnvironment(null, true, false, emptyList())) } @Test fun gameEnvironmentOverrideWins() { - assertEquals(emptyList(), TurnipEnvironment.gameEnvironment(null, listOf("TU_DEBUG=nolrz"))) + assertEquals(emptyList(), TurnipEnvironment.gameEnvironment(null, false, true, listOf("TU_DEBUG=nolrz"))) } } From bc8a970520a9e64a515b0fe61bfa54420abd26d5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:41:39 -0500 Subject: [PATCH 50/80] Stop re-arming frame generation after repeated GPU loss (#3659) Disable frame generation after repeated startup device losses, while preserving recovery for engines that had been working. Keep the current ZeroFG-compatible submission path. --- .../cpp/waylandcomp/src/framegen_bridge.c | 37 +++++++++- tools/tests/test_framegen_hang_breaker.py | 69 +++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 tools/tests/test_framegen_hang_breaker.py diff --git a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c index 7745c3ddc0..b3badeea27 100644 --- a/app/src/main/cpp/waylandcomp/src/framegen_bridge.c +++ b/app/src/main/cpp/waylandcomp/src/framegen_bridge.c @@ -79,6 +79,24 @@ static int format_refused(VkFormat f) { static _Atomic unsigned g_stat_generated; static uint64_t g_total_generated; + +#define FG_PROVEN_FRAMES 120 +#define FG_HANG_STRIKES 2 +static _Atomic int g_hang_strikes; +static int g_submitted_since_ready; +static uint64_t g_generated_at_ready; + +// A driver that hangs on the engine's shaders loses the device on its first generated frame after every +// recovery, so the compositor would recover and hang again for as long as frame generation stays armed. +static int framegen_loss_strike(int submitted, uint64_t completed_since_ready) { + if (!submitted || completed_since_ready >= FG_PROVEN_FRAMES) { + atomic_store(&g_hang_strikes, 0); + return 0; + } + if (atomic_fetch_add(&g_hang_strikes, 1) + 1 < FG_HANG_STRIKES) return 0; + atomic_store(&g_hang_strikes, 0); + return 1; +} static float g_presented_rate, g_source_rate; static uint32_t g_present_accum, g_source_accum; static int64_t g_window_start_ns; @@ -129,6 +147,7 @@ void vkp_framegen_set_engine(int kind) { atomic_store(&g_kind, kind); atomic_store(&g_failed_kind, -1); atomic_store(&g_cfg_dirty, 1); + atomic_store(&g_hang_strikes, 0); } void vkp_framegen_set_armed(int armed, int multiplier, int target_fps) { @@ -230,6 +249,8 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f atomic_store(&g_caps_ddfg_ok, fge_caps_ok(VKP_FG_ENGINE_DDFG)); atomic_store(&g_caps_zero_ok, fge_caps_ok(VKP_FG_ENGINE_ZEROFG)); atomic_store(&g_dev_lost, 0); + g_submitted_since_ready = 0; + g_generated_at_ready = g_total_generated; atomic_store(&g_dev_ready, vk.CreateImage && vk.CreateImageView && vk.CmdPipelineBarrier); FGLOG("engines ready on compositor device: LSFG %s, DD-FG %s, ZeroFG %s", @@ -238,8 +259,21 @@ void vkp_framegen_device_ready(VkDevice dev, VkQueue queue, uint32_t qfam, int f fge_caps_ok(VKP_FG_ENGINE_ZEROFG) ? "available" : "unavailable"); } +// The compositor reports one loss twice: when it happens and again while releasing the lost device. +static int framegen_count_loss(void) { + if (atomic_exchange(&g_dev_lost, 1)) return 0; + int failed = framegen_loss_strike(g_submitted_since_ready, g_total_generated - g_generated_at_ready); + g_submitted_since_ready = 0; + return failed; +} + void vkp_framegen_device_lost(void) { - atomic_store(&g_dev_lost, 1); + if (framegen_count_loss()) { + int kind = atomic_load(&g_kind); + mark_failed(kind); + FGLOG("%s lost the GPU %d times in a row before its frames completed; frame generation stays off " + "until it is set again", fge_engine_name(kind), FG_HANG_STRIKES); + } atomic_store(&g_dev_ready, 0); fge_device_lost(); if (g_dev) { @@ -523,6 +557,7 @@ int vkp_framegen_run(VkCommandBuffer cmd, VkImage scene, VkImageView scene_view, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, NULL, 0, NULL, nb, bars); + if (n_gen) g_submitted_since_ready = 1; fge_process(cmd, scene, scene_view, (uint32_t)w, (uint32_t)h, fmt, planning_sequence, n_gen); for (uint32_t g = 0; g < n_gen; g++) { fge_generate(cmd, g, n_gen, g_ring[g].img, g_ring[g].view, (uint32_t)w, (uint32_t)h); diff --git a/tools/tests/test_framegen_hang_breaker.py b/tools/tests/test_framegen_hang_breaker.py new file mode 100644 index 0000000000..d49626d444 --- /dev/null +++ b/tools/tests/test_framegen_hang_breaker.py @@ -0,0 +1,69 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_vk_pending_completion import function + + +class FramegenHangBreakerTest(unittest.TestCase): + def run_c(self, body): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if not compiler: + self.skipTest('A host C compiler is required') + root = Path(__file__).resolve().parents[2] + source = (root / 'app/src/main/cpp/waylandcomp/src/framegen_bridge.c').read_text() + code = '#include \n#include \n#include \n' + code += '#define FG_PROVEN_FRAMES 120\n#define FG_HANG_STRIKES 2\n' + code += 'static _Atomic int g_hang_strikes, g_dev_lost;\n' + code += 'static int g_submitted_since_ready;\nstatic uint64_t g_total_generated, g_generated_at_ready;\n' + code += function(source, 'framegen_loss_strike') + code += function(source, 'framegen_count_loss') + code += 'int main(void) {\n' + body + '\n}\n' + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + probe = folder / 'breaker.c' + binary = folder / 'breaker' + probe.write_text(code) + subprocess.run([compiler, '-std=c11', str(probe), '-o', str(binary)], check=True, + capture_output=True, text=True) + subprocess.run([str(binary)], check=True, capture_output=True, timeout=10) + + def test_losses_before_any_generated_frame_completes_switch_generation_off(self): + self.run_c(''' + assert(framegen_loss_strike(1, 0) == 0); + assert(framegen_loss_strike(1, 0) == 1); + assert(framegen_loss_strike(1, 0) == 0); +''') + + def test_a_loss_after_generation_worked_keeps_it_armed(self): + self.run_c(''' + assert(framegen_loss_strike(1, 0) == 0); + assert(framegen_loss_strike(1, 500) == 0); + assert(framegen_loss_strike(1, 0) == 0); +''') + + def test_a_loss_without_generation_work_is_not_a_strike(self): + self.run_c(''' + assert(framegen_loss_strike(1, 0) == 0); + assert(framegen_loss_strike(0, 0) == 0); + assert(framegen_loss_strike(1, 0) == 0); +''') + + def test_a_loss_reported_twice_counts_once(self): + self.run_c(''' + for (int loss = 0; loss < 2; loss++) { + g_dev_lost = 0; + g_submitted_since_ready = 1; + int first = framegen_count_loss(); + int again = framegen_count_loss(); + assert(again == 0); + assert(first == (loss == 1)); + } +''') + + +if __name__ == '__main__': + unittest.main() From a9f2017aa3dab296a764b83cd13d40cf90d5716d Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:25:37 -0500 Subject: [PATCH 51/80] Draw the outline of enabled secondary buttons under the agent's latest reply (#3697) * Draw the outline of enabled secondary buttons under the agent's latest reply * Count only the index fetch's own connections in DesktopLanguageIndexSourceTest --- .../droiddeck/launcher/ui/FrontEndWidgets.kt | 3 ++- .../runtime/DesktopLanguageIndexSourceTest.kt | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index 4245236747..adfa9eebcd 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -308,7 +308,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boo Box( contentAlignment = Alignment.Center, modifier = modifier.paneItem("btn:$text").downToFirstTile().heightIn(min = if (pill) 40.dp else if (compact) 44.dp else 48.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape).background(fill).glideBorder(hot, shape, pal.signal, if (pill) Color.White.copy(alpha = 0.14f) else pal.line2) - .alpha(if (enabled) 1f else 0.5f) + // The label always gets a layer of its own: sharing one with the fill and outline, they did not draw under the agent's latest reply. + .graphicsLayer { alpha = if (enabled) 1f else 0.5f } .hoverable(src).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick) .controllerConfirm(enabled = enabled, onClick = onClick) .padding(horizontal = if (pill) 16.dp else if (compact) 10.dp else 16.dp, vertical = if (pill) 8.dp else if (compact) 7.dp else 11.dp), diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt index 3b4b008c50..03bd7746da 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DesktopLanguageIndexSourceTest.kt @@ -41,7 +41,18 @@ class DesktopLanguageIndexSourceTest { context = ApplicationProvider.getApplicationContext() DownloadSource.init(context) DownloadSource.setMode(context, DownloadSource.MODE_MIRROR) + } + + // Downloads other tests leave running also go through this proxy while it is set, so it is set only around [block]. + private fun tunnelsDuring(block: () -> Unit): List { DownloadSource.setProxy(context, "127.0.0.1:${proxy.localPort}") + tunnels.clear() + try { + block() + } finally { + DownloadSource.setProxy(context, "") + } + return tunnels.toList() } @After fun tearDown() { @@ -51,12 +62,12 @@ class DesktopLanguageIndexSourceTest { } @Test fun mirrorModeWouldOtherwiseSendTheIndexThroughAMirror() { - Downloader.downloadString(base + "desktop-kde.i18n.txt") - assertTrue(tunnels.toString(), tunnels.any { host -> DownloadSource.MIRRORS.any { it.host == host } }) + val seen = tunnelsDuring { Downloader.downloadString(base + "desktop-kde.i18n.txt") } + assertTrue(seen.toString(), seen.any { host -> DownloadSource.MIRRORS.any { it.host == host } }) } @Test fun indexIsFetchedOnlyFromGithubInMirrorMode() { - assertNull(DesktopLanguage.fetchIndex(base)) - assertEquals(listOf("github.com"), tunnels.toList()) + val seen = tunnelsDuring { assertNull(DesktopLanguage.fetchIndex(base)) } + assertEquals(listOf("github.com"), seen) } } From 26b11c6838ffe242f31865ebeb83dfd99b6a47fa Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:00:09 -0500 Subject: [PATCH 52/80] Keep the session drawer open while the agent's file picker is up (#3696) Preserve the Agent page and its result handler while the system picker covers the session, including on a docked second screen. --- .../com/droiddeck/launcher/SessionActivity.kt | 11 +++++++++-- .../droiddeck/launcher/agent/AgentAttachments.kt | 3 +++ .../launcher/session/SessionVisibilityPolicy.kt | 6 ++++++ .../java/com/droiddeck/launcher/ui/AgentPage.kt | 4 +++- .../session/SessionVisibilityPolicyTest.kt | 15 +++++++++++++++ 5 files changed, 36 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 6cf2f43a9f..d371dd5491 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -6495,7 +6495,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde displayManager.unregisterDisplayListener(displayListener) com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) contentResolver.unregisterContentObserver(refreshSettingObserver) - if (!screenIsOff()) closeSecondScreen(reset = false) + // Closing the presentation removes the docked Agent page and unregisters its picker. + if (com.droiddeck.launcher.session.SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = screenIsOff(), + dockedDrawerOpen = menuShownOnBottom(), + attachmentPickerOpen = com.droiddeck.launcher.agent.AgentAttachments.picking, + ) + ) closeSecondScreen(reset = false) sessionTextInput.stop() startedScreens = (startedScreens - 1).coerceAtLeast(0) updateGlassesScreen() @@ -6532,6 +6538,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() + com.droiddeck.launcher.agent.AgentAttachments.picking = false drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } @@ -6645,7 +6652,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde heldButtons.clear() if (!screenOff) { val menuUp = menuShownOnBottom() - drawerOpen = false + if (!com.droiddeck.launcher.agent.AgentAttachments.picking) drawerOpen = false if (menuUp) SessionState.bottomMenu = true pcKeyboardOpen = false achievementsOpen = false diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt index b4f9a09dff..96ddf0057a 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt @@ -19,6 +19,9 @@ object AgentAttachments { /** Guest paths waiting to go with the next message. */ val pending = mutableStateListOf() + /** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */ + @Volatile var picking = false + private const val NEW = "new" private const val GUEST_DIR = "/root/.cache/droiddeck/attachments" private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp") diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt index 90630ebbcd..79cc595af9 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibilityPolicy.kt @@ -1,6 +1,12 @@ package com.droiddeck.launcher.session internal object SessionVisibilityPolicy { + fun shouldCloseSecondScreenOnStop( + screenOff: Boolean, + dockedDrawerOpen: Boolean, + attachmentPickerOpen: Boolean, + ): Boolean = !screenOff && !(dockedDrawerOpen && attachmentPickerOpen) + fun isHidden( activityStarted: Boolean, defaultDisplayOn: Boolean, 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 439422fee7..44f4d4bc90 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -1007,6 +1007,7 @@ private fun AttachButton() { val context = LocalContext.current val pal = LocalPalette.current val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> + AgentAttachments.picking = false if (uris.isEmpty()) return@rememberLauncherForActivityResult val chat = AgentHost.chat Thread({ @@ -1017,7 +1018,8 @@ private fun AttachButton() { }, "agent-attach").start() } RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") { - runCatching { picker.launch(arrayOf("*/*")) } + AgentAttachments.picking = true + if (runCatching { picker.launch(arrayOf("*/*")) }.isFailure) AgentAttachments.picking = false } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt index 708241662e..5bbf3bcc19 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityPolicyTest.kt @@ -5,6 +5,21 @@ import org.junit.Assert.assertTrue import org.junit.Test class SessionVisibilityPolicyTest { + @Test fun attachmentPickerKeepsTheDockedDrawerAliveDuringActivityStop() { + assertFalse(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = false, dockedDrawerOpen = true, attachmentPickerOpen = true, + )) + assertTrue(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = false, dockedDrawerOpen = true, attachmentPickerOpen = false, + )) + assertTrue(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = false, dockedDrawerOpen = false, attachmentPickerOpen = true, + )) + assertFalse(SessionVisibilityPolicy.shouldCloseSecondScreenOnStop( + screenOff = true, dockedDrawerOpen = false, attachmentPickerOpen = false, + )) + } + @Test fun handsetScreenStateControlsActivityOnDefaultDisplay() { assertFalse(SessionVisibilityPolicy.isHidden(true, true, true, false)) assertTrue(SessionVisibilityPolicy.isHidden(true, false, true, true)) From fe6f8638c6b5779073952343b4396bfbd954ac99 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:15:50 -0500 Subject: [PATCH 53/80] Lay wide session drawer pages out in two columns (#3694) Keep drawer content composed when changing width, and keep component notes within their groups so columns stay balanced. --- .../droiddeck/launcher/ui/SessionOverlay.kt | 67 +++++++++++++++---- .../ui/ComponentDownloadsDrawerTest.kt | 54 +++++++++++++-- .../launcher/ui/DrawerColumnsTest.kt | 48 +++++++++++++ tools/agent/AGENTS.md | 4 ++ 4 files changed, 154 insertions(+), 19 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/DrawerColumnsTest.kt 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 26524d326e..e4637355ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -16,6 +16,8 @@ import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.unit.Constraints +import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLayoutDirection @@ -75,6 +77,7 @@ import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight @@ -666,6 +669,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont val track: (String) -> Modifier = { key -> focus.track(page, key) } val sections = remember(page) { DrawerSections(drawerContext, track) } CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) { + DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) { when (page) { SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track) SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track) @@ -682,6 +686,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont SessionDrawerPage.ACHIEVEMENTS -> a.achievementsGame?.let { DrawerAchievementsPage(it, a.achievementsTitle, track) } SessionDrawerPage.AGENT -> Unit } + } } } } } @@ -1557,6 +1562,44 @@ internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boole private val DRAWER_MIN_WIDTH = 300.dp private val DRAWER_HANDLE_STRIP = 24.dp +private val DRAWER_COLUMN_GAP = 10.dp +// Two columns once each would be as wide as the narrowest single-column sheet. +private val DRAWER_TWO_COLUMN_WIDTH = DRAWER_MIN_WIDTH * 2 + DRAWER_COLUMN_GAP + +private val SessionDrawerPage.inColumns: Boolean + get() = this != SessionDrawerPage.MORE && this != SessionDrawerPage.ACHIEVEMENTS + +/** + * On a wide sheet, lays a page's groups out in two columns, the first half on the left. The split is by count, not + * height, so a group keeps its column while others fold and unfold. + */ +@Composable +internal fun DrawerColumns(two: Boolean, content: @Composable () -> Unit) { + // Keep a single composition so resizing only remeasures existing children. + Layout(content, Modifier.fillMaxWidth()) { measurables, constraints -> + val width = constraints.maxWidth + if (!two || measurables.size < 2) { + val placeables = measurables.map { it.measure(constraints.copy(minWidth = 0, minHeight = 0)) } + return@Layout layout(width, placeables.sumOf { it.height }) { + var y = 0 + placeables.forEach { it.placeRelative(0, y); y += it.height } + } + } + val gap = DRAWER_COLUMN_GAP.roundToPx() + val column = ((width - gap) / 2).coerceAtLeast(0) + val child = Constraints(maxWidth = column) + val placeables = measurables.map { it.measure(child) } + val half = (placeables.size + 1) / 2 + val left = placeables.take(half) + val right = placeables.drop(half) + layout(width, maxOf(left.sumOf { it.height }, right.sumOf { it.height })) { + var y = 0 + left.forEach { it.placeRelative(0, y); y += it.height } + y = 0 + right.forEach { it.placeRelative(column + gap, y); y += it.height } + } + } +} /** A grip on the sheet's left edge: dragging it, or pressing left and right on a controller, resizes the sheet. */ @Composable @@ -1893,7 +1936,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin } return } - SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { + DrawerComponentSettingsGroup(stringResource(R.string.drawer_game_components_note, gameProfile.name)) { DrawerStackedChoice( host = host, key = "game-cmp-proton", @@ -1936,12 +1979,6 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin ) } } - Text( - stringResource(R.string.drawer_game_components_note, gameProfile.name), - fontSize = 12.sp, - color = colors.onSurfaceVariant, - modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp), - ) return } val running = snap.protons.filter { it.inUseByGame } @@ -1982,7 +2019,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin return } val p = view.proton - SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components") { + DrawerComponentSettingsGroup(stringResource(R.string.drawer_components_note)) { DrawerStackedChoice( host, "cmp-proton", stringResource(R.string.comp_proton), listOfNotNull( @@ -2018,10 +2055,16 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin ) } } - Text( - stringResource(R.string.drawer_components_note), - fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp), - ) +} + +@Composable +internal fun DrawerComponentSettingsGroup(note: String, content: @Composable ColumnScope.() -> Unit) { + // The note stays visible when collapsed, but both belong to one drawer column item. + Column(Modifier.fillMaxWidth()) { + SettingsGroup(stringResource(R.string.drawer_page_components), key = "game-components", content = content) + Text(note, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp)) + } } @Composable diff --git a/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt index 4d3f1852a5..f52ae99690 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/ComponentDownloadsDrawerTest.kt @@ -3,24 +3,31 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text +import androidx.compose.runtime.State +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.Modifier import androidx.compose.ui.input.InputMode import androidx.compose.ui.input.InputModeManager import androidx.compose.ui.input.key.Key import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.SemanticsActions import androidx.compose.ui.test.assertIsFocused import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performKeyInput +import androidx.compose.ui.test.performSemanticsAction import androidx.compose.ui.test.pressKey import androidx.compose.ui.test.requestFocus import com.droiddeck.launcher.R import com.droiddeck.launcher.session.ComponentsManager import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -67,6 +74,29 @@ class ComponentDownloadsDrawerTest { assertEquals(listOf(nightly), requested) } + @Config(qualifiers = "w800dp-h800dp") + @Test fun nightlySelectionSurvivesCrossingTheColumnThreshold() { + val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test") + val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test") + val twoColumns = mutableStateOf(false) + lateinit var menu: MenuHost + show(catalog = listOf(stable, nightly), twoColumns = twoColumns, captureHost = { menu = it }) + val chooser = compose.onNodeWithTag("cmp-download-dxvk") + val nightlyRow = compose.onNodeWithText(nightly.file.removeSuffix(".wcp")) + val narrowLeft = chooser.getUnclippedBoundsInRoot().left + chooser.performSemanticsAction(SemanticsActions.OnClick) + compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.comp_channel_nightly)).performClick() + nightlyRow.assertExists() + compose.runOnIdle { menu.open = null; twoColumns.value = true } + assertTrue(chooser.getUnclippedBoundsInRoot().left > narrowLeft) + chooser.performSemanticsAction(SemanticsActions.OnClick) + nightlyRow.assertExists() + compose.runOnIdle { menu.open = null; twoColumns.value = false } + assertEquals(narrowLeft, chooser.getUnclippedBoundsInRoot().left) + chooser.performSemanticsAction(SemanticsActions.OnClick) + nightlyRow.assertExists() + } + @Test fun controllerPicksNightlyOnItsTabThenDownloadsItFromTheRow() { val stable = ComponentsManager.CatalogItem("dxvk-3.1.1-linux.wcp", "dxvk", "Dxvk-Linux", "https://github.com/example/s", 100, "sha256:test") val nightly = ComponentsManager.CatalogItem("DD-dxvk-3.1.1+153-nightly.wcp", "dxvk", ComponentsManager.DD_NIGHTLY, "https://github.com/example/n", 100, "sha256:test") @@ -107,18 +137,28 @@ class ComponentDownloadsDrawerTest { checking: Boolean = false, onRefresh: () -> Unit = {}, onDownload: (ComponentsManager.CatalogItem) -> Unit = {}, + twoColumns: State? = null, + captureHost: (MenuHost) -> Unit = {}, ) { compose.setContent { inputMode = LocalInputModeManager.current DroidDeckTheme { Column(Modifier.verticalScroll(rememberScrollState())) { - ComponentDownloadsDrawerGroup( - host = rememberMenuHost(), catalog = catalog, catalogAt = 0, - checking = checking, - packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)), - downloads = downloads, onRefresh = onRefresh, onDownload = onDownload, - track = { Modifier.testTag(it) }, - ) + val host = rememberMenuHost() + captureHost(host) + val content: @androidx.compose.runtime.Composable () -> Unit = { + ComponentDownloadsDrawerGroup( + host = host, catalog = catalog, catalogAt = 0, + checking = checking, + packages = listOf(ComponentsManager.Package(stored.file, "dxvk", "2.3", "", 100)), + downloads = downloads, onRefresh = onRefresh, onDownload = onDownload, + track = { Modifier.testTag(it) }, + ) + } + if (twoColumns == null) content() else DrawerColumns(twoColumns.value) { + SettingsGroup("Profile") { Text("Profile settings") } + content() + } } } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/DrawerColumnsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/DrawerColumnsTest.kt new file mode 100644 index 0000000000..a5201db5b4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/DrawerColumnsTest.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.height +import androidx.compose.material3.Text +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.dp +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w800dp-h600dp") +class DrawerColumnsTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun theComponentNoteStaysInItsGroupAndSixGroupsSplitEvenly() { + val note = "Component note" + val componentRow = "Component row" + compose.setContent { + DroidDeckTheme { + DrawerColumns(two = true) { + repeat(3) { index -> Box(Modifier.height(32.dp).testTag("left-$index")) } + DrawerComponentSettingsGroup(note) { Text(componentRow) } + repeat(2) { index -> Box(Modifier.height(32.dp).testTag("right-$index")) } + } + } + } + val left = (0..2).map { compose.onNodeWithTag("left-$it").getUnclippedBoundsInRoot() } + val right = (0..1).map { compose.onNodeWithTag("right-$it").getUnclippedBoundsInRoot() } + val group = compose.onNodeWithText(componentRow).getUnclippedBoundsInRoot() + val footer = compose.onNodeWithText(note).getUnclippedBoundsInRoot() + assertTrue(left.all { it.left == left.first().left }) + assertTrue(right.all { it.left == right.first().left && it.left > left.first().left }) + assertTrue(group.left >= right.first().left) + assertTrue(footer.left >= right.first().left) + assertTrue(footer.top >= group.bottom) + assertTrue(right.first().top >= footer.bottom) + assertTrue(left.zipWithNext().all { (first, next) -> first.bottom <= next.top }) + } +} diff --git a/tools/agent/AGENTS.md b/tools/agent/AGENTS.md index d9b7deb09e..709dcbf181 100644 --- a/tools/agent/AGENTS.md +++ b/tools/agent/AGENTS.md @@ -57,6 +57,10 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in the background and keep checking, so the user can talk to you meanwhile. The restart ends your process, and the conversation continues on the new build. +- To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle + compile first only adds time. It refuses changes since the installed build (`apkCommit` in + `droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick + its commits onto a branch from `apkCommit` and build that. - 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 runs on the device once the build tools are set up, but slowly: run the test classes that cover From 86b8ae3c996ac2fd3ad88a5e01040758ece2518b Mon Sep 17 00:00:00 2001 From: JRAlmonte <89419177+JRAlmonte@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:02:07 -0500 Subject: [PATCH 54/80] fix(nativeguest): do not apply a realtime limit of zero (#3704) Flatpak emulators that use SDL (Flycast, Rosalie's Mupen GUI, xemu) were killed with status 137 a second or two after a game started. Without a RealtimeKit, xdg-desktop-portal reports RTTimeUSecMax 0, and SDL sets that as RLIMIT_RTTIME before asking for a realtime thread. The kernel checks the limit on a thread that is realtime or has a CPU-time timer armed, and a limit of 0 is reached at once: SIGKILL at the hard limit. Fixes #3672 --- tools/nativeguest/hook/privileged.c | 10 ++- tools/tests/test_native_hook_rttime_limit.py | 81 ++++++++++++++++++++ 2 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 tools/tests/test_native_hook_rttime_limit.py diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 14ef7c6654..0ca6f97880 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -235,8 +235,16 @@ static int sandbox_only_limit(int resource, const struct rlimit *rlim) { return 0; } +// The kernel checks RLIMIT_RTTIME on a thread that is realtime or has a CPU-time timer armed, and a +// limit of 0 is reached at once: SIGXCPU at the soft limit, SIGKILL at the hard one. SDL sets the +// RTTimeUSecMax it reads from org.freedesktop.portal.Realtime before it asks for a realtime thread, +// and xdg-desktop-portal reports 0 when it reaches no RealtimeKit, as in a session with no system bus. +static int fatal_limit(int resource, const struct rlimit *rlim) { + return rlim && resource == RLIMIT_RTTIME && rlim->rlim_cur == 0; +} + int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) { - if (sandbox_only_limit((int)resource, rlim)) return 0; + if (sandbox_only_limit((int)resource, rlim) || fatal_limit((int)resource, rlim)) return 0; static int (*orig_setrlimit)(__rlimit_resource_t, const struct rlimit *) = NULL; #if defined(__USE_FILE_OFFSET64) && !defined(__LP64__) // With 64-bit file offsets on a 32-bit system this function is setrlimit64 diff --git a/tools/tests/test_native_hook_rttime_limit.py b/tools/tests/test_native_hook_rttime_limit.py new file mode 100644 index 0000000000..5cfe76b155 --- /dev/null +++ b/tools/tests/test_native_hook_rttime_limit.py @@ -0,0 +1,81 @@ +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include +#include +#include + +static void show(const char *name, int ret) { + struct rlimit now; + if (getrlimit(RLIMIT_RTTIME, &now) != 0) exit(2); + printf("%s\t%d\t%lld\t%lld\n", name, ret, (long long)now.rlim_cur, (long long)now.rlim_max); +} + +int main(void) { + struct rlimit zero = {0, 0}, soft_zero = {0, 200000}, usable = {100000, 200000}; + show("start", 0); + show("zero", setrlimit(RLIMIT_RTTIME, &zero)); + show("soft_zero", setrlimit(RLIMIT_RTTIME, &soft_zero)); + show("usable", setrlimit(RLIMIT_RTTIME, &usable)); + return 0; +} +""" + + +class NativeHookRttimeLimitTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory(dir="/tmp") + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + cls.root.mkdir() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def limits(self): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_ROOT")} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(self.probe)], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(0, out.returncode, out.stdout + out.stderr) + return {name: (int(ret), int(cur), int(hard)) + for name, ret, cur, hard in (line.split("\t") for line in out.stdout.splitlines())} + + def test_a_realtime_limit_of_zero_is_reported_set_and_not_applied(self): + limits = self.limits() + self.assertEqual(0, limits["zero"][0]) + self.assertEqual(limits["start"][1:], limits["zero"][1:]) + + def test_a_soft_realtime_limit_of_zero_is_not_applied(self): + limits = self.limits() + self.assertEqual(0, limits["soft_zero"][0]) + self.assertEqual(limits["start"][1:], limits["soft_zero"][1:]) + + def test_a_usable_realtime_limit_is_applied(self): + self.assertEqual((0, 100000, 200000), self.limits()["usable"]) + + +if __name__ == "__main__": + unittest.main() From de3ed8b986a6111b88e4111fe8699b1b1423d480 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:25:24 -0500 Subject: [PATCH 55/80] Keep the followed channel's offer off the Tests list while browsing it (#3707) * Show the followed channel's update offer above the test list only when following a test * Keep install progress and errors on the Tests list while following Stable or Preview --- app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 7a5510360e..f15b69287b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesPage.kt @@ -706,7 +706,8 @@ private fun TestList(tests: List, me: AppUpdates.Installed, u: UpdatesS val followed = u.follow.pr.takeIf { u.follow.channel == Channel.TEST } val rowShown = followed != null && (ready.any { it.pr == followed } || (oldShown && old.any { it.pr == followed })) Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - if (!rowShown) status(false) + // A followed test's row carries the status; browsing Tests while following Stable or Preview shows it only for an install running or failed. + if (if (followed != null) !rowShown else u.stage != null || u.error != null) status(false) Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { if (tests.size > 5 || query.isNotEmpty()) AdbTextField( value = query, onValueChange = { query = it }, label = stringResource(R.string.upd_tests_find), From 77fffa7592fcdf5cf2a1bb14912a859f5515688c Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:42:17 -0500 Subject: [PATCH 56/80] Show recent photos in place of the keyboard when attaching to the agent (#3702) * Show recent photos in place of the keyboard in the agent composer The attach button opens a tray, at the keyboard's height, of the device's recent pictures; a tap attaches or detaches one. The tray also opens the system file picker and asks for photo access when the app has none. * Agent instructions: manifest needs an APK; the agent resumes after a Lab build restart * Skip the tray's back handler where the host has no back dispatcher * Offer the photo tray in windows that cannot open pickers, such as the floating pet * Fix the tray's permission request for windows without a registry * Move the game screenshot button into the photo tray * Name only the model in the agent's compact chip * Keep the session drawer open while the tray's picker or photo permission prompt is up * Address review: tray height on short screens, denied photo access, kept photo marks, tile labels, Lab build refusals * Keep tray photos being copied across the tray closing * Let a tray photo copy clear only its own in-progress marker * Review: one attachment file per copy, photo tile labels, superseded copies attach nothing * Drop tray photo copies still running when the message is sent --- app/src/main/AndroidManifest.xml | 2 + .../launcher/agent/AgentAttachments.kt | 19 +- .../com/droiddeck/launcher/ui/AgentPage.kt | 112 +++---- .../droiddeck/launcher/ui/AgentPhotoTray.kt | 280 ++++++++++++++++++ app/src/main/res/values-ar/strings.xml | 5 + app/src/main/res/values-b+es+419/strings.xml | 5 + app/src/main/res/values-bg/strings.xml | 5 + app/src/main/res/values-cs/strings.xml | 5 + app/src/main/res/values-da/strings.xml | 5 + app/src/main/res/values-de/strings.xml | 5 + app/src/main/res/values-el/strings.xml | 5 + app/src/main/res/values-es/strings.xml | 5 + app/src/main/res/values-fi/strings.xml | 5 + app/src/main/res/values-fr/strings.xml | 5 + app/src/main/res/values-hi/strings.xml | 5 + app/src/main/res/values-hu/strings.xml | 5 + app/src/main/res/values-in/strings.xml | 5 + app/src/main/res/values-it/strings.xml | 5 + app/src/main/res/values-ja/strings.xml | 5 + app/src/main/res/values-ko/strings.xml | 5 + app/src/main/res/values-ms/strings.xml | 5 + app/src/main/res/values-nb/strings.xml | 5 + app/src/main/res/values-nl/strings.xml | 5 + app/src/main/res/values-pl/strings.xml | 5 + app/src/main/res/values-pt-rPT/strings.xml | 5 + app/src/main/res/values-pt/strings.xml | 5 + app/src/main/res/values-ro/strings.xml | 5 + app/src/main/res/values-ru/strings.xml | 5 + app/src/main/res/values-sv/strings.xml | 5 + app/src/main/res/values-th/strings.xml | 5 + app/src/main/res/values-tr/strings.xml | 5 + app/src/main/res/values-uk/strings.xml | 5 + app/src/main/res/values-vi/strings.xml | 5 + app/src/main/res/values-zh-rCN/strings.xml | 5 + app/src/main/res/values-zh-rHK/strings.xml | 5 + app/src/main/res/values-zh-rTW/strings.xml | 5 + app/src/main/res/values/strings.xml | 5 + tools/agent/AGENTS.md | 9 +- 38 files changed, 526 insertions(+), 61 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5db5b11509..4211f6bbc5 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -40,6 +40,8 @@ + + diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt index 96ddf0057a..9c9dd5c150 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentAttachments.kt @@ -22,6 +22,12 @@ object AgentAttachments { /** True while the file picker is open over a session: it answers the drawer's agent page, so the drawer must stay. */ @Volatile var picking = false + /** Launches a system screen that answers the agent page, keeping the drawer for it; the result callback clears [picking]. */ + fun pick(launch: () -> Unit) { + picking = true + if (runCatching(launch).isFailure) picking = false + } + private const val NEW = "new" private const val GUEST_DIR = "/root/.cache/droiddeck/attachments" private val IMAGE = setOf("png", "jpg", "jpeg", "webp", "gif", "bmp") @@ -38,14 +44,17 @@ object AgentAttachments { val folder = chat ?: NEW val dir = File(hostDir(app), folder).apply { mkdirs() } return uris.mapNotNull { uri -> + var target: File? = null runCatching { val name = displayName(app, uri).replace(Regex("[^A-Za-z0-9._-]"), "_").ifEmpty { "file" } - var target = File(dir, name) + var candidate = File(dir, name) var n = 1 - while (target.exists()) target = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}") - app.contentResolver.openInputStream(uri)!!.use { input -> target.outputStream().use { input.copyTo(it) } } - "$GUEST_DIR/$folder/${target.name}" - }.getOrNull() + // Created atomically, so copies running side by side never pick the same name. + while (!candidate.createNewFile()) candidate = File(dir, "${name.substringBeforeLast('.')}-${n++}${name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }}") + target = candidate + app.contentResolver.openInputStream(uri)!!.use { input -> candidate.outputStream().use { input.copyTo(it) } } + "$GUEST_DIR/$folder/${candidate.name}" + }.onFailure { target?.delete() }.getOrNull() } } 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 44f4d4bc90..b2793e5ba1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -5,7 +5,9 @@ import android.content.ContextWrapper import android.os.Build import android.view.KeyEvent import android.view.WindowManager +import androidx.activity.compose.BackHandler import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.expandVertically @@ -50,12 +52,12 @@ import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.Send import androidx.compose.material.icons.outlined.Extension -import androidx.compose.material.icons.outlined.PhotoCamera import androidx.compose.material.icons.outlined.MicOff import androidx.compose.material.icons.outlined.Mic import androidx.compose.material.icons.outlined.Add import androidx.compose.material.icons.outlined.ArrowDownward import androidx.compose.material.icons.outlined.AttachFile +import androidx.compose.material.icons.outlined.Keyboard import androidx.compose.material.icons.outlined.Terminal import androidx.compose.material.icons.outlined.Build import androidx.compose.material.icons.outlined.Close @@ -79,6 +81,7 @@ import androidx.compose.runtime.MutableState import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope @@ -108,6 +111,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalView import androidx.compose.ui.platform.testTag @@ -301,7 +305,7 @@ private fun AgentPageContent( readingBack = false scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) } } - val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() && + val hidden = !composer.focused && !composer.tray && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() && AgentHost.approvals.isEmpty() var listHeight by remember { mutableIntStateOf(0) } Box( @@ -319,6 +323,7 @@ private fun AgentPageContent( awaitEachGesture { awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE + composer.tray = false // Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving. if (composer.focused) focusManager.clearFocus(force = true) } @@ -344,6 +349,12 @@ private fun AgentPageContent( @Stable private class ComposerState { var focused by mutableStateOf(false) + /** The photo tray stands in for the keyboard, at the height the keyboard last had. */ + var tray by mutableStateOf(false) + var keyboardHeight by mutableStateOf(0.dp) + /** Tray photos copied, or being copied, for this conversation, so reopening the tray keeps their marks and copies nothing twice. */ + val photoCopies = mutableStateMapOf() + val photosCopying = mutableStateMapOf() var focusRequests by mutableIntStateOf(0) private set private var consumedFocusRequests by mutableIntStateOf(0) @@ -390,7 +401,7 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon .clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"), ) { val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) } - val parts = if (compact) listOfNotNull(mode ?: model) + val parts = if (compact) listOf(model) else listOfNotNull( AgentHost.harness.name, model, AgentHost.effort, mode, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }, @@ -748,6 +759,8 @@ private fun AgentComposer( if (text.isEmpty() && AgentAttachments.pending.isEmpty()) return@send AgentHost.send(context, text, AgentAttachments.pending.toList()) AgentAttachments.pending.clear() + composer.photosCopying.clear() + composer.tray = false onSent() } } @@ -813,7 +826,34 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState composer.keyboardHeight) composer.keyboardHeight = height + } + LaunchedEffect(hideAttach) { if (hideAttach) composer.tray = false } + LaunchedEffect(AgentHost.chat) { + composer.photoCopies.clear() + composer.photosCopying.clear() + } + // BackHandler throws where the host provides no back dispatcher: the front end and the floating pet. + if (LocalOnBackPressedDispatcherOwner.current != null) BackHandler(composer.tray) { composer.tray = false } + val focusManager = LocalFocusManager.current + val files = if (picks) rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { + AgentAttachments.picking = false + attachUris(context, it) + } else null + val toggleTray = { + if (composer.tray) { + composer.tray = false + composer.open() + } else { + focusManager.clearFocus(force = true) + composer.tray = true + } + } BoxWithConstraints( Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape16).background(colors.surface) .border(if (focused) 2.dp else 1.dp, if (focused) pal.primary else pal.line, Shape16).padding(6.dp), @@ -841,6 +881,7 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState 0.dp) composer.keyboardHeight else 280.dp).coerceAtLeast(160.dp).coerceAtMost(most) + AgentPhotoTray(height, composer.photoCopies, composer.photosCopying, files?.let { { AgentAttachments.pick { it.launch(arrayOf("*/*")) } } }) + } } /** @@ -974,53 +1018,15 @@ private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Un } } -/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */ +/** Opens the photo tray in place of the keyboard; while it is open, brings the keyboard back. */ @Composable -private fun GameFrameButton() { - val context = LocalContext.current +private fun AttachButton(trayOpen: Boolean, onClick: () -> Unit) { val pal = LocalPalette.current - RoundButton(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), pal.surfaceVariant, pal.onBackground, "agent-game-frame") { - val grab = AgentAttachments.gameFrame ?: return@RoundButton - val chat = AgentHost.chat - grab frame@{ frame -> - if (frame == null) { - android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show() - return@frame - } - Thread({ - val path = AgentAttachments.saveFrame(context, chat, frame) - frame.recycle() - android.os.Handler(android.os.Looper.getMainLooper()).post { - when { - path == null -> android.widget.Toast.makeText(context, R.string.agent_attach_game_failed, android.widget.Toast.LENGTH_SHORT).show() - AgentHost.chat == chat -> AgentAttachments.pending.add(path) - else -> AgentAttachments.discard(context, listOf(path)) - } - } - }, "agent-game-frame").start() - } - } -} - -@Composable -private fun AttachButton() { - val context = LocalContext.current - val pal = LocalPalette.current - val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> - AgentAttachments.picking = false - if (uris.isEmpty()) return@rememberLauncherForActivityResult - val chat = AgentHost.chat - Thread({ - val paths = AgentAttachments.copy(context, chat, uris) - android.os.Handler(android.os.Looper.getMainLooper()).post { - if (AgentHost.chat == chat) AgentAttachments.pending.addAll(paths) else AgentAttachments.discard(context, paths) - } - }, "agent-attach").start() - } - RoundButton(Icons.Outlined.AttachFile, stringResource(R.string.agent_attach), pal.surfaceVariant, pal.onBackground, "agent-attach") { - AgentAttachments.picking = true - if (runCatching { picker.launch(arrayOf("*/*")) }.isFailure) AgentAttachments.picking = false - } + RoundButton( + if (trayOpen) Icons.Outlined.Keyboard else Icons.Outlined.AttachFile, + stringResource(if (trayOpen) R.string.agent_keyboard else R.string.agent_attach), + if (trayOpen) pal.primary else pal.surfaceVariant, if (trayOpen) pal.onPrimary else pal.onBackground, "agent-attach", onClick = onClick, + ) } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt new file mode 100644 index 0000000000..d6c5dabe68 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPhotoTray.kt @@ -0,0 +1,280 @@ +package com.droiddeck.launcher.ui + +import android.Manifest +import android.content.ContentUris +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import android.provider.Settings +import android.widget.Toast +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Check +import androidx.compose.material.icons.outlined.FolderOpen +import androidx.compose.material.icons.outlined.PhotoCamera +import androidx.compose.material.icons.outlined.PhotoLibrary +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.SnapshotStateMap +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLifecycleOwner +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import coil.compose.AsyncImage +import coil.request.ImageRequest +import com.droiddeck.launcher.R +import com.droiddeck.launcher.agent.AgentAttachments +import com.droiddeck.launcher.agent.AgentHost +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** The device's photos, newest first, as MediaStore lets the app see them. */ +internal object AgentPhotos { + enum class Access { NONE, SELECTED, ALL } + + /** Android stops showing the request after repeated denials and answers it at once, so a denied request sends later ones to Settings. */ + var refused = false + + fun permissions(sdk: Int = Build.VERSION.SDK_INT): Array = when { + sdk >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) + sdk >= Build.VERSION_CODES.TIRAMISU -> arrayOf(Manifest.permission.READ_MEDIA_IMAGES) + else -> arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE) + } + + fun access(context: Context): Access { + fun granted(permission: String) = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED + val all = permissions().first() + return when { + Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && Environment.isExternalStorageManager() -> Access.ALL + granted(all) -> Access.ALL + Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && granted(Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) -> Access.SELECTED + else -> Access.NONE + } + } + + class Photo(val uri: Uri, val name: String) + + fun recent(context: Context, limit: Int = 300): List = runCatching { + val images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI + context.contentResolver.query( + images, arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME), null, null, "${MediaStore.Images.Media.DATE_ADDED} DESC", + )?.use { c -> + buildList { + while (size < limit && c.moveToNext()) add(Photo(ContentUris.withAppendedId(images, c.getLong(0)), c.getString(1).orEmpty())) + } + }.orEmpty() + }.getOrDefault(emptyList()) +} + +/** + * Copies [uris] into the conversation's attachments off the main thread, then hands [onCopied] what was attached: nothing if the + * conversation changed meanwhile or [current] says the copy was superseded. + */ +internal fun attachUris(context: Context, uris: List, current: () -> Boolean = { true }, onCopied: (List>) -> Unit = {}) { + if (uris.isEmpty()) return + val chat = AgentHost.chat + Thread({ + val copied = uris.mapNotNull { uri -> AgentAttachments.copy(context, chat, listOf(uri)).firstOrNull()?.let { uri to it } } + android.os.Handler(android.os.Looper.getMainLooper()).post { + val paths = copied.map { it.second } + if (AgentHost.chat == chat && current()) { + AgentAttachments.pending.addAll(paths) + onCopied(copied) + } else { + AgentAttachments.discard(context, paths) + onCopied(emptyList()) + } + } + }, "agent-attach").start() +} + +/** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */ +private fun attachGameFrame(context: Context) { + val grab = AgentAttachments.gameFrame ?: return + val chat = AgentHost.chat + grab frame@{ frame -> + if (frame == null) { + Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show() + return@frame + } + Thread({ + val path = AgentAttachments.saveFrame(context, chat, frame) + frame.recycle() + android.os.Handler(android.os.Looper.getMainLooper()).post { + when { + path == null -> Toast.makeText(context, R.string.agent_attach_game_failed, Toast.LENGTH_SHORT).show() + AgentHost.chat == chat -> AgentAttachments.pending.add(path) + else -> AgentAttachments.discard(context, listOf(path)) + } + } + }, "agent-game-frame").start() + } +} + +/** Shown in place of the keyboard: recent photos to tap onto the message, and the system picker for anything else. */ +@Composable +internal fun AgentPhotoTray(height: Dp, copies: SnapshotStateMap, copying: SnapshotStateMap, onFiles: (() -> Unit)?) { + val context = LocalContext.current + val pal = LocalPalette.current + var access by remember { mutableStateOf(AgentPhotos.access(context)) } + var photos by remember { mutableStateOf?>(null) } + var reloads by remember { mutableStateOf(0) } + // A window no activity owns (the floating pet's chat) cannot ask for a permission, so it sends the user to the app's settings. + val launcher = if (LocalActivityResultRegistryOwner.current != null) { + rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { + AgentAttachments.picking = false + access = AgentPhotos.access(context) + if (access == AgentPhotos.Access.NONE) AgentPhotos.refused = true + reloads++ + } + } else null + val request = { + if (launcher != null && !AgentPhotos.refused) { + AgentAttachments.pick { launcher.launch(AgentPhotos.permissions()) } + } else { + val details = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.packageName)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + runCatching { context.startActivity(details) } + } + Unit + } + // Access can change in Settings, and new pictures arrive, while the app is in the background. + val lifecycle = LocalLifecycleOwner.current.lifecycle + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + access = AgentPhotos.access(context) + reloads++ + } + } + lifecycle.addObserver(observer) + onDispose { lifecycle.removeObserver(observer) } + } + LaunchedEffect(access, reloads) { + photos = if (access == AgentPhotos.Access.NONE) emptyList() else withContext(Dispatchers.IO) { AgentPhotos.recent(context) } + } + LazyVerticalGrid( + GridCells.Adaptive(96.dp), + Modifier.fillMaxWidth().height(height).padding(top = 8.dp).testTag("agent-photo-tray"), + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + if (AgentAttachments.gameFrame != null) item { + TrayTile(Icons.Outlined.PhotoCamera, stringResource(R.string.agent_attach_game), "agent-game-frame") { attachGameFrame(context) } + } + if (onFiles != null) item { TrayTile(Icons.Outlined.FolderOpen, stringResource(R.string.agent_attach_files), "agent-attach-files", onFiles) } + if (access != AgentPhotos.Access.ALL) item { + TrayTile( + Icons.Outlined.PhotoLibrary, + stringResource(if (access == AgentPhotos.Access.NONE) R.string.agent_photos_allow else R.string.agent_photos_more), + "agent-photos-allow", + onClick = request, + ) + } + val list = photos + if (list != null && list.isEmpty() && access != AgentPhotos.Access.NONE) item(span = { GridItemSpan(maxLineSpan) }) { + Text( + stringResource(R.string.agent_photos_empty), fontSize = 13.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth().padding(16.dp), + ) + } + items(list.orEmpty(), key = { it.uri.toString() }) { photo -> + val uri = photo.uri + val path = copies[uri] + val selected = path != null && path in AgentAttachments.pending + Box( + Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant) + .then(if (selected) Modifier.border(3.dp, pal.primary, Shape12) else Modifier) + .clickable { + when { + selected -> AgentAttachments.pending.remove(path) + path != null && AgentAttachments.host(context, path).exists() -> AgentAttachments.pending.add(path) + uri in copying -> Unit + else -> { + // Leaving the conversation clears the markers, so a copy started before that is no longer current even back in it. + val copy = Any() + copying[uri] = copy + attachUris(context, listOf(uri), current = { copying[uri] === copy }) { copied -> + copied.forEach { (u, p) -> copies[u] = p } + if (copying[uri] === copy) copying.remove(uri) + } + } + } + }.semantics { + contentDescription = photo.name + this.selected = selected + }.testTag("agent-photo"), + ) { + AsyncImage( + model = ImageRequest.Builder(context).data(uri).size(320).build(), contentDescription = null, + contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(), + ) + if (selected) Box( + contentAlignment = Alignment.Center, + modifier = Modifier.align(Alignment.TopEnd).padding(6.dp).size(22.dp).clip(CircleShape).background(pal.primary), + ) { + Icon(Icons.Outlined.Check, null, tint = pal.onPrimary, modifier = Modifier.size(16.dp)) + } + } + } + } +} + +@Composable +private fun TrayTile(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) { + val pal = LocalPalette.current + Column( + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, + modifier = Modifier.aspectRatio(1f).clip(Shape12).background(pal.surfaceVariant).clickable(onClick = onClick).padding(8.dp).testTag(tag), + ) { + Icon(icon, null, tint = pal.onBackground, modifier = Modifier.size(26.dp)) + Text( + label, fontSize = 12.sp, color = pal.onBackground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 6.dp), + ) + } +} diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index ea85ca5c12..0329c403c1 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1180,6 +1180,11 @@ أدوات الوكيل غير مثبتة: %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 12254b5715..ff0f9b4685 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1198,6 +1198,11 @@ Herramientas del agente sin instalar: %1$s No enviar Adjuntar + Archivos + Permitir acceso a fotos + Elegir más fotos + Aún no hay fotos + Teclado Quitar Predeterminado Esfuerzo de razonamiento diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index bb4ff12581..70a66f3fe5 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1168,6 +1168,11 @@ Инструментите на агента не са инсталирани: %1$s Не изпращай Прикачи + Файлове + Разрешаване на достъп до снимки + Избор на още снимки + Все още няма снимки + Клавиатура Премахни По подразбиране Усилие за разсъждение diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 02d5c6d00d..d8b5e9960c 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1174,6 +1174,11 @@ Nástroje agenta nejsou nainstalované: %1$s Neposílat Přiložit + Soubory + Povolit přístup k fotkám + Vybrat další fotky + Zatím žádné fotky + Klávesnice Odebrat Výchozí Náročnost uvažování diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index f3383e6768..2dd816c23f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1168,6 +1168,11 @@ Agentens værktøjer er ikke installeret: %1$s Send ikke Vedhæft + Filer + Tillad adgang til billeder + Vælg flere billeder + Ingen billeder endnu + Tastatur Fjern Standard Ræsonneringsindsats diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index ce45ef01d4..ec19ca465a 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1160,6 +1160,11 @@ Agent-Werkzeuge nicht installiert: %1$s Nicht senden Anhängen + Dateien + Zugriff auf Fotos erlauben + Weitere Fotos auswählen + Noch keine Fotos + Tastatur Entfernen Standard Denkaufwand diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 7205dd9940..b4d1e7552d 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1168,6 +1168,11 @@ Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s Να μην σταλεί Επισύναψη + Αρχεία + Να επιτρέπεται η πρόσβαση στις φωτογραφίες + Επιλογή περισσότερων φωτογραφιών + Δεν υπάρχουν φωτογραφίες ακόμα + Πληκτρολόγιο Αφαίρεση Προεπιλογή Προσπάθεια συλλογισμού diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 71e10bdab3..c07d195c68 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1171,6 +1171,11 @@ Herramientas del agente sin instalar: %1$s No enviar Adjuntar + Archivos + Permitir acceso a las fotos + Elegir más fotos + Aún no hay fotos + Teclado Quitar Predeterminado Esfuerzo de razonamiento diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 464e2576be..2143c3416b 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1168,6 +1168,11 @@ Agentin työkaluja ei ole asennettu: %1$s Älä lähetä Liitä + Tiedostot + Salli kuvien käyttö + Valitse lisää kuvia + Ei vielä kuvia + Näppäimistö Poista Oletus Päättelyteho diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 7c1c1ef44d..a667d3b351 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1171,6 +1171,11 @@ Outils de l’agent non installés : %1$s Ne pas envoyer Joindre + Fichiers + Autoriser l\'accès aux photos + Choisir d\'autres photos + Aucune photo pour l\'instant + Clavier Supprimer Par défaut Effort de raisonnement diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 281c5914d5..fee8602fce 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1168,6 +1168,11 @@ एजेंट टूल इंस्टॉल नहीं हुए: %1$s न भेजें संलग्न करें + फ़ाइलें + फ़ोटो की अनुमति दें + और फ़ोटो चुनें + अभी कोई फ़ोटो नहीं + कीबोर्ड हटाएँ डिफ़ॉल्ट सोचने का स्तर diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index a74cef1df8..35f0ff99ef 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1168,6 +1168,11 @@ Az ügynök eszközei nincsenek telepítve: %1$s Ne küldd el Csatolás + Fájlok + Fotókhoz való hozzáférés engedélyezése + További fotók kiválasztása + Még nincsenek fotók + Billentyűzet Eltávolítás Alapértelmezett Gondolkodási erőfeszítés diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 8bd5840655..22bff7e5ec 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1165,6 +1165,11 @@ Alat agen tidak terpasang: %1$s Jangan kirim Lampirkan + File + Izinkan akses foto + Pilih foto lainnya + Belum ada foto + Keyboard Hapus Default Upaya penalaran diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 0d79a90921..a676758f72 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1163,6 +1163,11 @@ Strumenti dell’agente non installati: %1$s Non inviare Allega + File + Consenti accesso alle foto + Scegli altre foto + Ancora nessuna foto + Tastiera Rimuovi Predefinito Livello di ragionamento diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index f66a14fc6e..0c181e7ab3 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1165,6 +1165,11 @@ エージェントのツールが未インストール: %1$s 送信しない 添付 + ファイル + 写真へのアクセスを許可 + 写真をさらに選択 + まだ写真がありません + キーボード 削除 デフォルト 推論レベル diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index dbcf405e3f..5a6d979241 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1165,6 +1165,11 @@ 에이전트 도구가 설치되지 않음: %1$s 보내지 않기 첨부 + 파일 + 사진 접근 허용 + 사진 더 선택 + 아직 사진이 없습니다 + 키보드 제거 기본 추론 수준 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 2dc5bcea1b..188ed04d5e 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1165,6 +1165,11 @@ Alat ejen tidak dipasang: %1$s Jangan hantar Lampirkan + Fail + Benarkan akses foto + Pilih lebih banyak foto + Belum ada foto + Papan kekunci Alih keluar Lalai Usaha penaakulan diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 70da47fde8..75a3415f2e 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1168,6 +1168,11 @@ Agentverktøy er ikke installert: %1$s Ikke send Legg ved + Filer + Tillat tilgang til bilder + Velg flere bilder + Ingen bilder ennå + Tastatur Fjern Standard Resonneringsinnsats diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index aa95f349be..2df78a8419 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1168,6 +1168,11 @@ Agenttools niet geïnstalleerd: %1$s Niet verzenden Bijvoegen + Bestanden + Toegang tot foto\'s toestaan + Meer foto\'s kiezen + Nog geen foto\'s + Toetsenbord Verwijderen Standaard Redeneerinspanning diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 350871461b..f8218ebfef 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1174,6 +1174,11 @@ Narzędzia agenta nie są zainstalowane: %1$s Nie wysyłaj Załącz + Pliki + Zezwól na dostęp do zdjęć + Wybierz więcej zdjęć + Brak zdjęć + Klawiatura Usuń Domyślny Poziom rozumowania diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 58c25267da..4051e3fcb6 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1163,6 +1163,11 @@ Ferramentas do agente não instaladas: %1$s Não enviar Anexar + Ficheiros + Permitir acesso às fotos + Escolher mais fotos + Ainda não há fotos + Teclado Remover Predefinido Esforço de raciocínio diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 08eb2c38de..bf322e180b 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1170,6 +1170,11 @@ Ferramentas do agente não instaladas: %1$s Não enviar Anexar + Arquivos + Permitir acesso às fotos + Escolher mais fotos + Ainda não há fotos + Teclado Remover Padrão Esforço de raciocínio diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index bd89893d52..3325b9da12 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1171,6 +1171,11 @@ Instrumentele agentului nu sunt instalate: %1$s Nu trimite Atașează + Fișiere + Permite accesul la fotografii + Alege mai multe fotografii + Încă nu există fotografii + Tastatură Elimină Implicit Efort de raționament diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c75b0aa343..96694a0b2c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1174,6 +1174,11 @@ Инструменты агента не установлены: %1$s Не отправлять Прикрепить + Файлы + Разрешить доступ к фото + Выбрать ещё фото + Пока нет фото + Клавиатура Удалить По умолчанию Уровень рассуждений diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index f3819c7385..a0bbd67c37 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1168,6 +1168,11 @@ Agentens verktyg är inte installerade: %1$s Skicka inte Bifoga + Filer + Tillåt åtkomst till bilder + Välj fler bilder + Inga bilder än + Tangentbord Ta bort Standard Resonemangsnivå diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 21c96ecd2a..a4028f05ce 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1165,6 +1165,11 @@ ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s ไม่ต้องส่ง แนบ + ไฟล์ + อนุญาตให้เข้าถึงรูปภาพ + เลือกรูปภาพเพิ่ม + ยังไม่มีรูปภาพ + แป้นพิมพ์ นำออก ค่าเริ่มต้น ระดับการใช้เหตุผล diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index acc9089167..ef66a2f302 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1160,6 +1160,11 @@ Ajan araçları yüklenmedi: %1$s Gönderme Ekle + Dosyalar + Fotoğraflara erişime izin ver + Daha fazla fotoğraf seç + Henüz fotoğraf yok + Klavye Kaldır Varsayılan Akıl yürütme çabası diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 6ca06df91c..890e3ea863 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1174,6 +1174,11 @@ Інструменти агента не встановлено: %1$s Не надсилати Прикріпити + Файли + Дозволити доступ до фото + Вибрати ще фото + Поки немає фото + Клавіатура Видалити За замовчуванням Рівень міркувань diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 420c0c1bf5..ae806d0524 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1165,6 +1165,11 @@ Chưa cài công cụ của tác tử: %1$s Không gửi Đính kèm + Tệp + Cho phép truy cập ảnh + Chọn thêm ảnh + Chưa có ảnh + Bàn phím Xóa Mặc định Mức độ lập luận diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index eb5407a271..9bc2afeaee 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1248,6 +1248,11 @@ 智能体工具未安装:%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 7f4bbd0233..7a79238501 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1164,6 +1164,11 @@ 智能體工具未安裝:%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 e52193ca17..00e2bae533 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1164,6 +1164,11 @@ 智慧代理工具未安裝:%1$s 不要傳送 附加 + 檔案 + 允許存取相片 + 選擇更多相片 + 還沒有相片 + 鍵盤 移除 預設 推理強度 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ed8b435d3f..9ab2d5584d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1330,6 +1330,11 @@ Agent tools not installed: %1$s Don\'t send Attach + Files + Allow photo access + Choose more photos + No photos yet + Keyboard Remove Default Reasoning effort diff --git a/tools/agent/AGENTS.md b/tools/agent/AGENTS.md index 709dcbf181..3b2ccd2c84 100644 --- a/tools/agent/AGENTS.md +++ b/tools/agent/AGENTS.md @@ -44,8 +44,10 @@ from what tripped agents up on real devices. running makes Steam show "Game already running" and `launch` time out. - Session scripts are APK assets, copied into the rootfs at every session start over any local edit. A Lab build (`dd-lab-build`, see `docs/lab-builds.md`) carries app code and resources only: - session scripts, native code and assets need a new APK, such as the pull request's CI test build - (DroidDeck > Updates > Test builds). + session scripts, native code, assets and `AndroidManifest.xml` need a new APK, such as the pull + request's CI test build (DroidDeck > Updates > Test builds). `dd-lab-build` refuses changes to the + manifest, native code, Gradle files and a few startup classes, but builds session script and asset + changes without them. To try the rest of a branch, build a copy without those changes. ## Changing DroidDeck @@ -56,7 +58,8 @@ The source is checked out at `/root/DroidDeck` once the Agent tab's build tools - `dd-lab-build` builds the checkout as a Lab build and restarts DroidDeck on it. DroidDeck runs the build in a process of its own and shows its progress; `dd-lab-build` follows its log. Run it in the background and keep checking, so the user can talk to you meanwhile. The restart ends your - process, and the conversation continues on the new build. + process; DroidDeck starts you again on the new build, in the same conversation, so tell the user + what you will check then instead of asking them to message you. - To try a change, commit it and go straight to `dd-lab-build`: it compiles the app, so a Gradle compile first only adds time. It refuses changes since the installed build (`apkCommit` in `droiddeckctl state`) that need a new APK. For a branch from a newer `origin/main`, cherry-pick From b072cedd16f99a2240e6c6667dbd56f57f1947db Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 4 Dec 2026 14:01:37 -0500 Subject: [PATCH 57/80] Fix black bottom-screen Mirror with HDR enabled (#3710) * Keep Mirror frames readable with HDR enabled * Exercise mirror capture messages in the native host queue test * Preserve the HDR display fallback while Mirror is open --- app/src/main/cpp/waylandcomp/src/compositor.c | 24 ++++++++++-- .../main/cpp/waylandcomp/src/droiddeck_ext.c | 8 +++- .../main/cpp/waylandcomp/src/droiddeck_ext.h | 2 + .../cpp/waylandcomp/src/waylandcomp_jni.c | 5 +++ .../com/droiddeck/launcher/SessionActivity.kt | 5 +++ .../launcher/wayland/WaylandCompositor.java | 2 + tools/tests/test_bottom_mirror_composition.py | 38 +++++++++++++++++++ tools/tests/test_wayland_host_order.py | 8 ++++ 8 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 tools/tests/test_bottom_mirror_composition.py diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 112f731f5a..f17591cb16 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -343,6 +343,7 @@ volatile int g_hide_shell; volatile int g_zero_copy; static int g_zero_copy_paused; +static int g_mirror_capture; extern volatile int g_display_buffer_driver; extern void droiddeck_on_overlay_planes(int planes); static int g_overlay_planes_told = -1; @@ -2961,7 +2962,7 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) { static int said = -1, said_tm = -1; static const char *said_why; const int tm = route != 0 && !droiddeck_color_output(); - if (route == said && tm == said_tm && (route != 1 || hs->why == said_why)) return; + if (route == said && tm == said_tm && (route < 1 || route > 2 || hs->why == said_why)) return; int was = said; said = route; said_why = hs->why; said_tm = tm; char name[160] = "the HDR game"; @@ -2978,6 +2979,10 @@ static void hdr_note_route(int route, const struct hdr_scene *hs) { "BT2020_PQ", name, hs->why ? hs->why : "?", droiddeck_color_sdr_white()); break; case 2: + if (g_mirror_capture) { + droiddeck_log("color", "Mirror: %s is composed through the screen swapchain", name); + break; + } if (tm) droiddeck_log("color", "HDR with frame generation for %s, HDR output switched off: the scene is tone-mapped to " "SDR and presented through an SDR screen swapchain", name); @@ -3198,6 +3203,11 @@ static void render_scene(void) { const int cardboard = vkp_cardboard_active(); struct hdr_scene hs; int hdr_route = hdr_plan(&dl, w, h, fx_on, framegen, &hs); + /* Mirror's PixelCopy cannot see the separate game layer. Keep unimportable frames visible on top. */ + if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) { + hdr_route = 2; + hs.why = "Mirror needs the screen swapchain"; + } const char *hdr_copy = NULL; if (droiddeck_color_hdr_open()) { hdr_note_route(hdr_route, &hs); @@ -3263,16 +3273,16 @@ static void render_scene(void) { else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0); else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver"; } - if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on && + if (hdr_route == 0 && !g_mirror_capture && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on && !ahb_only) { settle_unwaited(); rendered = vkp_render(w, h, dl.d, dl.n) == 0; } else if (hdr_route == 0 || hdr_route == 3) { const int pass_on = fx_on || framegen; tell_overlay_planes(); - const int fg_layer = framegen && hdr_route == 0 && framegen_fits_layer(); + const int fg_layer = framegen && !g_mirror_capture && hdr_route == 0 && framegen_fits_layer(); g_framegen_layer = fg_layer; - int li = (g_zero_copy && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; + int li = (g_zero_copy && !g_mirror_capture && (!framegen || fg_layer) && !bfi && !cardboard && !cursor_on) ? layer_candidate(&dl, w, h) : -1; int over = li >= 0 ? dl.n - 1 - li : 0; const int fx_blocks = (li >= 0 && fx_on && over > 0); if (fx_blocks) { li = -1; over = 0; } @@ -5002,6 +5012,12 @@ const char *droiddeck_client_name(struct wl_client *client) { return client_name struct wl_display *droiddeck_get_display(void) { return g_display; } void droiddeck_request_redraw(void) { schedule_render(); } +void droiddeck_set_mirror_capture(int on) { + if (g_mirror_capture == on) return; + g_mirror_capture = on; + schedule_render(); +} + struct wl_resource *droiddeck_ime_target(void) { struct surface *s; if (g_ime_click && g_ime_click->mapped) return g_ime_click->resource; diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c index 041f9c6c2b..e4ce7e201d 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.c @@ -11,7 +11,7 @@ #include "ahb_swapchain.h" #include "droiddeck_color.h" -enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD }; +enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT, HOST_KEY, HOST_SELECT_GAME_FIELD, HOST_MIRROR_CAPTURE }; struct host_msg { enum host_kind kind; @@ -91,6 +91,9 @@ void droiddeck_host_text_delete(int before, int after) { void droiddeck_host_zero_copy(int on, int live) { host_post(HOST_ZERO_COPY, NULL, 0, on, live); } +void droiddeck_host_mirror_capture(int on) { + host_post(HOST_MIRROR_CAPTURE, NULL, 0, on, 0); +} void droiddeck_host_hdr_output(int on) { host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0); } @@ -271,6 +274,9 @@ static int on_wake(int fd, uint32_t mask, void *data) { case HOST_ZERO_COPY: ahb_swapchain_set_mode(m->a, m->b); break; + case HOST_MIRROR_CAPTURE: + droiddeck_set_mirror_capture(m->a); + break; case HOST_HDR_OUTPUT: droiddeck_color_set_output(m->a); break; diff --git a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h index d7813eb7eb..bc67469eff 100644 --- a/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h +++ b/app/src/main/cpp/waylandcomp/src/droiddeck_ext.h @@ -29,6 +29,8 @@ void droiddeck_host_text_commit_and_submit(const char *utf8, int len); void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end); void droiddeck_host_text_delete(int before, int after); void droiddeck_host_zero_copy(int on, int live); +void droiddeck_host_mirror_capture(int on); +void droiddeck_set_mirror_capture(int on); void droiddeck_host_hdr_output(int on); void droiddeck_host_key(int evdev, int state); void droiddeck_host_select_game_field(int copy); diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 6d8754e4e5..f22865c110 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -461,6 +461,11 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv * __android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : ""); } +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetMirrorCapture(JNIEnv *env, jclass clazz, jboolean on) { + droiddeck_host_mirror_capture(on ? 1 : 0); +} + JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetDisplayBufferDriver(JNIEnv *env, jclass clazz, jboolean on) { g_display_buffer_driver = on ? 1 : 0; diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index d371dd5491..b055097bb2 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -6348,7 +6348,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun holdComposedOutput(hold: Boolean) { + val wasHeld = composedHolds > 0 composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0) + val held = composedHolds > 0 + if (held == wasHeld) return + WaylandCompositor.nativeSetMirrorCapture(held) + // Importable HDR is redirected by the compositor hold. Keep its layer-only fallback available. if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree()) } 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 2cc0ecd638..a2676304d9 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -333,6 +333,8 @@ public final class WaylandCompositor { public static native void nativeSetZeroCopy(boolean on); + public static native void nativeSetMirrorCapture(boolean on); + public static native void nativeSetDisplayBufferDriver(boolean on); public static native int nativeZeroCopyFrames(); diff --git a/tools/tests/test_bottom_mirror_composition.py b/tools/tests/test_bottom_mirror_composition.py new file mode 100644 index 0000000000..6ddee5a720 --- /dev/null +++ b/tools/tests/test_bottom_mirror_composition.py @@ -0,0 +1,38 @@ +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parents[2] +NATIVE = ROOT / "app/src/main/cpp/waylandcomp/src" +APP = ROOT / "app/src/main/java/com/droiddeck/launcher" + + +class BottomMirrorCompositionTest(unittest.TestCase): + def test_mirror_requests_composition_until_its_last_consumer_leaves(self): + panel = (APP / "ui/BottomMirrorPage.kt").read_text() + self.assertIn("actions.holdComposed(true)", panel) + self.assertIn("onDispose { actions.holdComposed(false) }", panel) + activity = (APP / "SessionActivity.kt").read_text() + hold = activity.split("private fun holdComposedOutput(", 1)[1].split("private fun zeroCopyActive", 1)[0] + self.assertIn("if (held == wasHeld) return", hold) + self.assertIn("nativeSetMirrorCapture(held)", hold) + self.assertIn("if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy", hold) + self.assertIn("CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy", activity) + self.assertIn("nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())", activity) + self.assertIn("nativeSetZeroCopy(composedOutputFree())", hold) + self.assertNotIn("SessionPrefs.set", hold) + + def test_compositor_selects_readable_surface_without_dropping_unimportable_hdr(self): + jni = (NATIVE / "waylandcomp_jni.c").read_text() + self.assertIn("droiddeck_host_mirror_capture(on ? 1 : 0);", jni) + host = (NATIVE / "droiddeck_ext.c").read_text() + self.assertIn("case HOST_MIRROR_CAPTURE:\n droiddeck_set_mirror_capture(m->a);", host) + compositor = (NATIVE / "compositor.c").read_text() + self.assertIn("if (g_mirror_capture && hdr_route != 3 && hs.n_hdr > 0) {\n hdr_route = 2;", compositor) + self.assertIn("g_zero_copy && !g_mirror_capture && (!framegen || fg_layer)", compositor) + self.assertIn("if (un && g_zero_copy)", compositor) + self.assertIn("if (g_zero_copy && droiddeck_color_hdr_open()) note_hdr_unimported", compositor) + self.assertNotIn("if (g_mirror_capture) ls = NULL", compositor) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_wayland_host_order.py b/tools/tests/test_wayland_host_order.py index 44dc7f3088..0b42b8e3ef 100644 --- a/tools/tests/test_wayland_host_order.py +++ b/tools/tests/test_wayland_host_order.py @@ -78,6 +78,7 @@ static int g_loop_stub; static int g_fallback_accept; static int g_fallback_token; static int g_hdr_count; +static int g_mirror_count, g_mirror_capture; int text_input_host_commit(const char *u, size_t n) { @@ -143,6 +144,7 @@ void toplevel_icon_init(struct wl_display *d) { (void)d; } void single_pixel_init(struct wl_display *d) { (void)d; } void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; } void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; } +void droiddeck_set_mirror_capture(int on) { g_mirror_capture = on; g_mirror_count++; } struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; } void wl_display_flush_clients(struct wl_display *d) { (void)d; } @@ -216,7 +218,10 @@ int main(void) droiddeck_host_key(29, 0); droiddeck_host_text_commit("later", 5); droiddeck_host_hdr_output(1); + droiddeck_host_mirror_capture(1); + CHECK(g_mirror_count == 0); CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_mirror_count == 1 && g_mirror_capture == 1); CHECK(g_n == saved); CHECK(g_hdr_count == 1); CHECK(g_fallback_token > 0); @@ -259,7 +264,10 @@ int main(void) droiddeck_host_key(32, 1); droiddeck_host_key(32, 0); droiddeck_host_hdr_output(0); + droiddeck_host_mirror_capture(0); + CHECK(g_mirror_count == 1); CHECK(on_wake(g_wake[0], 0, NULL) == 0); + CHECK(g_mirror_count == 2 && g_mirror_capture == 0); CHECK(g_n == saved + 1); CHECK(g_hdr_count == 2); CHECK(g_fallback_token > 0); From f06c37e279489a0f1e8d3c76f885b16c83c8bd55 Mon Sep 17 00:00:00 2001 From: LunaDL <91587464+EnzoDLofi@users.noreply.github.com> Date: Sat, 5 Dec 2026 01:47:58 -0400 Subject: [PATCH 58/80] Feat: Add per-game scaling filter (#3726) --- .../com/droiddeck/launcher/SessionActivity.kt | 46 ++++++++-- .../launcher/session/SessionPrefs.kt | 89 ++++++++++++++++--- .../droiddeck/launcher/ui/FrontEndSetup.kt | 57 ++++++++++++ .../launcher/ui/ScalingFilterMenu.kt | 69 ++++++++++++++ app/src/main/res/values-ar/strings.xml | 2 + app/src/main/res/values-b+es+419/strings.xml | 2 + app/src/main/res/values-bg/strings.xml | 2 + app/src/main/res/values-cs/strings.xml | 2 + app/src/main/res/values-da/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-el/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fi/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-hi/strings.xml | 2 + app/src/main/res/values-hu/strings.xml | 2 + app/src/main/res/values-in/strings.xml | 2 + app/src/main/res/values-it/strings.xml | 2 + app/src/main/res/values-ja/strings.xml | 2 + app/src/main/res/values-ko/strings.xml | 2 + app/src/main/res/values-ms/strings.xml | 2 + app/src/main/res/values-nb/strings.xml | 2 + app/src/main/res/values-nl/strings.xml | 2 + app/src/main/res/values-pl/strings.xml | 2 + app/src/main/res/values-pt-rPT/strings.xml | 2 + app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ro/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 2 + app/src/main/res/values-sv/strings.xml | 2 + app/src/main/res/values-th/strings.xml | 2 + app/src/main/res/values-tr/strings.xml | 2 + app/src/main/res/values-uk/strings.xml | 2 + app/src/main/res/values-vi/strings.xml | 2 + app/src/main/res/values-zh-rCN/strings.xml | 2 + app/src/main/res/values-zh-rHK/strings.xml | 2 + app/src/main/res/values-zh-rTW/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../session/SessionPrefsUpscalerTest.kt | 79 ++++++++++++++++ 38 files changed, 388 insertions(+), 18 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index b055097bb2..2fc1b15edc 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -661,6 +661,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var effects by mutableStateOf(ScreenEffects.OFF) private var observedScreenEffectsProfileId by mutableStateOf(null) private var screenEffectsTarget by mutableStateOf(SCREEN_EFFECTS_TARGET_AUTO) + private var screenEffectsProfileRevision by mutableIntStateOf(0) private var cardboard by mutableStateOf(Cardboard.OFF) private var headTracker: HeadTracker? = null private var steamVrStatus by mutableStateOf(null) @@ -1641,8 +1642,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde effects = effects, screenEffectsTarget = screenEffectsTarget, screenEffectsTargets = screenEffectsTargetOptions(), - screenEffectsCanDelete = screenEffectsProfileIdForTarget(screenEffectsTarget)?.let { - SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) + screenEffectsCanDelete = screenEffectsProfileRevision.let { + screenEffectsProfileIdForTarget(screenEffectsTarget)?.let { + SessionPrefs.hasScreenEffectsOverride(this@SessionActivity, it) || + SessionPrefs.hasScreenEffectsUpscalerOverride(this@SessionActivity, it) + } } == true, cardboard = cardboard, cardboardSensor = hasRotationSensor, @@ -1748,6 +1752,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else { val profileId = screenEffectsProfileIdForTarget(target) SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m) + screenEffectsProfileRevision++ if (target == screenEffectsTarget) { upscaler = m @@ -1783,6 +1788,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } else { val profileId = screenEffectsProfileIdForTarget(target) SessionPrefs.setScreenEffectsUpscaler(this@SessionActivity, profileId, m) + screenEffectsProfileRevision++ if (target == screenEffectsTarget) { upscaler = m if (screenEffectsUpscalerTargetAppliesToLiveOutput(target)) { @@ -1829,7 +1835,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val profileId = screenEffectsProfileIdForTarget(editorTarget) SessionPrefs.setScreenEffects(this@SessionActivity, profileId, e) effects = e - if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) e.push(upscaler) + if (screenEffectsTargetAppliesToLiveOutput(editorTarget)) { + val upscalerAppliesToLiveOutput = + screenEffectsUpscalerTargetAppliesToLiveOutput(editorTarget) + val liveUpscaler = if (upscalerAppliesToLiveOutput) { + SessionPrefs.screenEffectsUpscaler( + this@SessionActivity, + screenEffectsProfileIdForTarget(editorTarget) + ) + } else { + SessionPrefs.screenEffectsUpscaler( + this@SessionActivity, + currentScreenEffectsProfileId() + ) + } + e.push(liveUpscaler) + } } } }, @@ -2648,10 +2669,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val targetUpscaler = SessionPrefs.screenEffectsUpscaler(this, profileId) effects = targetEffects upscaler = targetUpscaler + val upscalerAppliesToLiveOutput = screenEffectsUpscalerTargetAppliesToLiveOutput(target) + val liveUpscaler = if (upscalerAppliesToLiveOutput) { + targetUpscaler + } else { + SessionPrefs.screenEffectsUpscaler(this, currentScreenEffectsProfileId()) + } + if (upscalerAppliesToLiveOutput) { + WaylandCompositor.nativeSetUpscaler(liveUpscaler) + } if (screenEffectsTargetAppliesToLiveOutput(target)) { - WaylandCompositor.nativeSetUpscaler(targetUpscaler) - WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, targetUpscaler)?.name) - targetEffects.push(targetUpscaler) + WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(targetEffects, liveUpscaler)?.name) + targetEffects.push(liveUpscaler) + } else if (upscalerAppliesToLiveOutput) { + val liveEffects = SessionPrefs.screenEffects(this, currentScreenEffectsProfileId()) + WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(liveEffects, liveUpscaler)?.name) } } @@ -2664,6 +2696,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun resetScreenEffectsTarget(target: String) { if (target != screenEffectsTarget) return SessionPrefs.resetScreenEffectsProfile(this, screenEffectsProfileIdForTarget(target)) + screenEffectsProfileRevision++ syncScreenEffectsTarget(target) } @@ -2671,6 +2704,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (target != screenEffectsTarget) return val profileId = screenEffectsProfileIdForTarget(target) ?: return SessionPrefs.deleteScreenEffectsProfile(this, profileId) + screenEffectsProfileRevision++ syncScreenEffectsTarget(target) } 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 b2cc52bcee..3c8bafb78b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -2011,24 +2011,84 @@ object SessionPrefs { sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply() } + private const val GAME_UPSCALER_OVERRIDES_KEY = "upscaler.gameOverrides" + + private fun gameUpscalerOverrides(context: Context): JSONObject = runCatching { + JSONObject(prefs(context).getString(GAME_UPSCALER_OVERRIDES_KEY, null) ?: "{}") + }.getOrDefault(JSONObject()) + + private fun legacyScreenEffectsUpscaler(context: Context, profileId: String): Int? = + runCatching { + val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") + val profile = profiles.optJSONObject(profileId) + if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) { + profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1).takeIf { it >= 0 } + } else null + }.getOrNull()?.let(::canonicalUpscaler) + + private fun clearLegacyScreenEffectsUpscaler(context: Context, profileId: String) { + val sessionPrefs = prefs(context) + val profiles = runCatching { + JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") + }.getOrNull() ?: return + val profile = profiles.optJSONObject(profileId) ?: return + if (!profile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) return + profile.remove(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) + if (profile.length() == 0) profiles.remove(profileId) + sessionPrefs.edit().apply { + if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY) + else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()) + }.apply() + } + + fun hasGameUpscalerOverride(context: Context, gameId: String): Boolean { + if (gameId.isBlank()) return false + val stored = gameUpscalerOverrides(context) + return (stored.has(gameId) && stored.optInt(gameId, -1) >= 0) || + legacyScreenEffectsUpscaler(context, "game:$gameId") != null + } + + fun setGameUpscaler(context: Context, gameId: String, mode: Int) { + if (gameId.isBlank()) return + val overrides = gameUpscalerOverrides(context) + overrides.put(gameId, canonicalUpscaler(mode)) + prefs(context).edit().putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()).apply() + clearLegacyScreenEffectsUpscaler(context, "game:$gameId") + } + + fun clearGameUpscaler(context: Context, gameId: String) { + if (gameId.isBlank()) return + val sessionPrefs = prefs(context) + val overrides = gameUpscalerOverrides(context) + if (overrides.has(gameId)) { + overrides.remove(gameId) + sessionPrefs.edit().apply { + if (overrides.length() == 0) remove(GAME_UPSCALER_OVERRIDES_KEY) + else putString(GAME_UPSCALER_OVERRIDES_KEY, overrides.toString()) + }.apply() + } + clearLegacyScreenEffectsUpscaler(context, "game:$gameId") + } + fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean { if (profileId.isNullOrBlank()) return false - return runCatching { - val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") - profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true - }.getOrDefault(false) + if (profileId.startsWith("game:")) { + return hasGameUpscalerOverride(context, profileId.removePrefix("game:")) + } + return legacyScreenEffectsUpscaler(context, profileId) != null } fun screenEffectsUpscaler(context: Context, profileId: String?): Int { if (profileId.isNullOrBlank()) return upscaler(context) - val stored = runCatching { - val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") - val profile = profiles.optJSONObject(profileId) - if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) { - profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1) - } else -1 - }.getOrDefault(-1) - return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context) + if (profileId.startsWith("game:")) { + val gameId = profileId.removePrefix("game:") + val overrides = gameUpscalerOverrides(context) + if (overrides.has(gameId)) { + val stored = overrides.optInt(gameId, -1) + if (stored >= 0) return canonicalUpscaler(stored) + } + } + return legacyScreenEffectsUpscaler(context, profileId) ?: upscaler(context) } fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) { @@ -2036,6 +2096,10 @@ object SessionPrefs { setUpscaler(context, mode) return } + if (profileId.startsWith("game:")) { + setGameUpscaler(context, profileId.removePrefix("game:"), mode) + return + } val sessionPrefs = prefs(context) val profiles = runCatching { JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") @@ -2072,6 +2136,7 @@ object SessionPrefs { val profiles = runCatching { JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}") }.getOrElse { JSONObject() } + if (profileId.startsWith("game:")) clearGameUpscaler(context, profileId.removePrefix("game:")) if (!profiles.has(profileId)) return profiles.remove(profileId) sessionPrefs.edit().apply { 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 3bec0c50aa..4047781350 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -881,6 +881,28 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost com.droiddeck.launcher.gpu.FrameGen.hasGameOverride(context, it) } ?: false) } + val scalingFilterChoices = SessionPrefs.upscalerChoices(context) + var gameUpscaler by remember(frameGenProfileKey) { + mutableStateOf(frameGenProfileKey?.let { + SessionPrefs.screenEffectsUpscaler(context, "game:$it") + } ?: SessionPrefs.upscaler(context)) + } + var gameUpscalerOverride by remember(frameGenProfileKey) { + mutableStateOf(frameGenProfileKey?.let { SessionPrefs.hasGameUpscalerOverride(context, it) } ?: false) + } + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner, frameGenProfileKey) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + frameGenProfileKey?.let { key -> + gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key") + gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key) + } + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } var wincompOpen by remember(wincompKey) { mutableStateOf(null) } val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() } val steamScope = game?.let { com.droiddeck.launcher.session.NoSteamLaunch.scope(it) } @@ -914,6 +936,25 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost }, ) } + val scalingFilterMenuContent: @Composable () -> Unit = { + val key = frameGenProfileKey + if (key != null) ScalingFilterMenu( + mode = gameUpscaler, + options = scalingFilterChoices, + hasGameOverride = gameUpscalerOverride, + onPick = { mode -> + SessionPrefs.setGameUpscaler(context, key, mode) + gameUpscaler = SessionPrefs.screenEffectsUpscaler(context, "game:$key") + gameUpscalerOverride = SessionPrefs.hasGameUpscalerOverride(context, key) + }, + onResetGame = { + SessionPrefs.clearGameUpscaler(context, key) + gameUpscaler = SessionPrefs.upscaler(context) + gameUpscalerOverride = false + }, + gameName = game?.name, + ) + } val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> { add { m -> val back = stringResource(R.string.hop_from_games) @@ -938,6 +979,17 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost } } + if (frameGenProfileKey != null) add { m -> + Box(m) { + SettingCard( + stringResource(R.string.display_filter), + scalingFilterChoices.firstOrNull { it.first == gameUpscaler }?.second ?: scalingFilterChoices.first().second, + "card:scaling-filter", Modifier.fillMaxSize(), + ) { + host.open = if (host.open == "scaling-filter") null else "scaling-filter" + } + } + } if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) } if (steamCard != null) add(steamCard) val cardStore = com.droiddeck.launcher.stores.Store.byId(game?.source.orEmpty())?.takeIf { it == com.droiddeck.launcher.stores.Store.EPIC || it == com.droiddeck.launcher.stores.Store.GOG } @@ -972,6 +1024,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost frameGenMenuContent() } } + if (host.open == "scaling-filter") { + Box(Modifier.fillMaxWidth().padding(top = 4.dp)) { + scalingFilterMenuContent() + } + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt b/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt new file mode 100644 index 0000000000..b012bb1292 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/ScalingFilterMenu.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R + +@Composable +internal fun ScalingFilterMenu( + mode: Int, + options: List>, + hasGameOverride: Boolean, + onPick: (Int) -> Unit, + onResetGame: () -> Unit, + gameName: String? = null, +) { + val colors = MaterialTheme.colorScheme + Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) { + val selectedLabel = options.firstOrNull { it.first == mode }?.second ?: mode.toString() + Text( + stringResource( + if (hasGameOverride) R.string.display_filter_game_profile else R.string.display_filter_default_profile, + if (hasGameOverride) gameName.orEmpty() else selectedLabel, + selectedLabel, + ), + color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(bottom = 6.dp), + ) + options.forEachIndexed { index, (option, label) -> + val selected = mode == option + val pick = { onPick(option) } + OutlinedButton( + onClick = pick, + modifier = Modifier.fillMaxWidth() + .padding(top = if (index == 0) 0.dp else 6.dp) + .controllerConfirm(onClick = pick), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface, + contentColor = if (selected) colors.primary else colors.onSurface, + ), + ) { Text(label) } + } + Text( + stringResource(R.string.display_filter_note), + color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 6.dp), + ) + OutlinedButton( + onClick = onResetGame, + modifier = Modifier.fillMaxWidth().padding(top = 6.dp) + .controllerConfirm(onClick = onResetGame), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + ) { + Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓") + } + } +} diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 0329c403c1..f2af52c651 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -4330,4 +4330,6 @@ اختصار داخل اللعبة إظهار اختصار النظارات الذكية إظهار زر النظارات الذكية العائم فوق اللعبة. + استخدام ملف تعريف %1$s: %2$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 ff0f9b4685..109f454cba 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -4208,4 +4208,6 @@ Acceso directo en el juego Mostrar acceso directo de Smart Glasses Mostrar el botón flotante de Smart Glasses sobre el juego. + Usando el perfil %1$s: %2$s + Usando el perfil predeterminado: %1$s diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 70a66f3fe5..12846c1ab5 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -4170,4 +4170,6 @@ Пряк път в играта Показване на прекия път за Smart Glasses Показва плаващия бутон за Smart Glasses върху играта. + Използва се профил %1$s: %2$s + Използва се профилът по подразбиране: %1$s diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index d8b5e9960c..ba390d045d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -4250,4 +4250,6 @@ Zkratka ve hře Zobrazit zkratku Smart Glasses Zobrazit plovoucí tlačítko Smart Glasses nad hrou. + Používá se profil %1$s: %2$s + Používá se výchozí profil: %1$s diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 2dd816c23f..7dde6f63c7 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -4170,4 +4170,6 @@ Genvej i spillet Vis Smart Glasses-genvej Vis den flydende Smart Glasses-knap oven på spillet. + Bruger profilen %1$s: %2$s + Bruger standardprofilen: %1$s diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index ec19ca465a..992d29d406 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -4170,4 +4170,6 @@ Ingame-Verknüpfung Smart-Glasses-Verknüpfung anzeigen Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen. + Profil %1$s wird verwendet: %2$s + Standardprofil wird verwendet: %1$s diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index b4d1e7552d..a49dd4fbe4 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -4170,4 +4170,6 @@ Συντόμευση μέσα στο παιχνίδι Εμφάνιση συντόμευσης Smart Glasses Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι. + Χρήση προφίλ %1$s: %2$s + Χρήση προεπιλεγμένου προφίλ: %1$s diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c07d195c68..c24fabe18d 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -4210,4 +4210,6 @@ Acceso directo en el juego Mostrar acceso directo de Smart Glasses Mostrar el botón flotante de Smart Glasses sobre el juego. + Usando el perfil %1$s: %2$s + Usando el perfil predeterminado: %1$s diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 2143c3416b..16713dbcb4 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -4170,4 +4170,6 @@ Pelin aikainen pikakuvake Näytä Smart Glasses -pikakuvake Näytä pelin päällä kelluva Smart Glasses -painike. + Käytössä profiili %1$s: %2$s + Käytössä oletusprofiili: %1$s diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index a667d3b351..6238a0cc16 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -4209,4 +4209,6 @@ Raccourci en jeu Afficher le raccourci Smart Glasses Afficher le bouton flottant Smart Glasses par-dessus le jeu. + Profil %1$s utilisé : %2$s + Profil par défaut utilisé : %1$s diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index fee8602fce..e557f76d02 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -4170,4 +4170,6 @@ गेम में शॉर्टकट Smart Glasses शॉर्टकट दिखाएँ गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ। + %1$s प्रोफ़ाइल का उपयोग: %2$s + डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 35f0ff99ef..497d330460 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -4170,4 +4170,6 @@ Játékon belüli parancsikon Smart Glasses parancsikon megjelenítése A játék fölött lebegő Smart Glasses gomb megjelenítése. + Használt profil: %1$s – %2$s + Alapértelmezett profil használata: %1$s diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 22bff7e5ec..cdbb9de406 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -4140,4 +4140,6 @@ Pintasan dalam game Tampilkan pintasan Smart Glasses Tampilkan tombol Smart Glasses mengambang di atas game. + Menggunakan profil %1$s: %2$s + Menggunakan profil default: %1$s diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index a676758f72..d37563a4d5 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -4209,4 +4209,6 @@ Scorciatoia nel gioco Mostra scorciatoia Smart Glasses Mostra il pulsante mobile Smart Glasses sopra il gioco. + Profilo %1$s in uso: %2$s + Profilo predefinito in uso: %1$s diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 0c181e7ab3..be60a37db5 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -4140,4 +4140,6 @@ ゲーム内ショートカット Smart Glasses のショートカットを表示 ゲーム画面上に Smart Glasses のフローティングボタンを表示します。 + %1$s プロファイルを使用中: %2$s + デフォルトプロファイルを使用中: %1$s diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 5a6d979241..89c839ce22 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -4140,4 +4140,6 @@ 게임 내 바로가기 Smart Glasses 바로가기 표시 게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다. + %1$s 프로필 사용 중: %2$s + 기본 프로필 사용 중: %1$s diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 188ed04d5e..a13e0ba39f 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -4140,4 +4140,6 @@ Pintasan dalam permainan Tunjukkan pintasan Smart Glasses Tunjukkan butang Smart Glasses terapung di atas permainan. + Menggunakan profil %1$s: %2$s + Menggunakan profil lalai: %1$s diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 75a3415f2e..e2130d6988 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -4170,4 +4170,6 @@ Snarvei i spillet Vis Smart Glasses-snarvei Vis den flytende Smart Glasses-knappen over spillet. + Bruker profilen %1$s: %2$s + Bruker standardprofilen: %1$s diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 2df78a8419..7563fbaf45 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -4170,4 +4170,6 @@ Snelkoppeling in game Smart Glasses-snelkoppeling tonen Toon de zwevende Smart Glasses-knop boven het spel. + Profiel %1$s in gebruik: %2$s + Standaardprofiel in gebruik: %1$s diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index f8218ebfef..383bc3aed3 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -4250,4 +4250,6 @@ Skrót w grze Pokaż skrót Smart Glasses Pokaż pływający przycisk Smart Glasses nad grą. + Używany profil %1$s: %2$s + Używany profil domyślny: %1$s diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 4051e3fcb6..c18340904d 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -4209,4 +4209,6 @@ Atalho no jogo Mostrar atalho do Smart Glasses Mostrar o botão flutuante do Smart Glasses sobre o jogo. + Perfil %1$s em utilização: %2$s + Perfil predefinido em utilização: %1$s diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index bf322e180b..6fea986206 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -4217,4 +4217,6 @@ Atalho durante o jogo Mostrar atalho do Smart Glasses Mostrar o botão flutuante do Smart Glasses sobre o jogo. + Perfil %1$s em uso: %2$s + Perfil predefinido em uso: %1$s diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 3325b9da12..fc7da00b02 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -4210,4 +4210,6 @@ Comandă rapidă în joc Afișează comanda rapidă Smart Glasses Afișează butonul plutitor Smart Glasses peste joc. + Se folosește profilul %1$s: %2$s + Se folosește profilul implicit: %1$s diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 96694a0b2c..5117873485 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -4251,4 +4251,6 @@ Ярлык в игре Показывать ярлык Smart Glasses Показывать плавающую кнопку Smart Glasses поверх игры. + Используется профиль %1$s: %2$s + Используется профиль по умолчанию: %1$s diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index a0bbd67c37..455c4d6472 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -4170,4 +4170,6 @@ Genväg i spelet Visa Smart Glasses-genväg Visa den flytande Smart Glasses-knappen ovanpå spelet. + Använder profilen %1$s: %2$s + Använder standardprofilen: %1$s diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index a4028f05ce..104b5f6407 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -4140,4 +4140,6 @@ ทางลัดในเกม แสดงทางลัด Smart Glasses แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม + ใช้โปรไฟล์ %1$s: %2$s + ใช้โปรไฟล์เริ่มต้น: %1$s diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index ef66a2f302..bbe4bad308 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -4170,4 +4170,6 @@ Oyun içi kısayol Smart Glasses kısayolunu göster Oyun üzerinde yüzen Smart Glasses düğmesini göster. + %1$s profili kullanılıyor: %2$s + Varsayılan profil kullanılıyor: %1$s diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 890e3ea863..36ba31f001 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -4250,4 +4250,6 @@ Ярлик у грі Показувати ярлик Smart Glasses Показувати плаваючу кнопку Smart Glasses поверх гри. + Використовується профіль %1$s: %2$s + Використовується профіль за замовчуванням: %1$s diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index ae806d0524..9c9ec116bf 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -4140,4 +4140,6 @@ Lối tắt trong trò chơi Hiển thị lối tắt Smart Glasses Hiển thị nút Smart Glasses nổi phía trên trò chơi. + Đang dùng hồ sơ %1$s: %2$s + Đang dùng hồ sơ mặc định: %1$s diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 9bc2afeaee..d9a964ca6a 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -4138,4 +4138,6 @@ 游戏内快捷方式 显示 Smart Glasses 快捷方式 在游戏画面上显示悬浮的 Smart Glasses 按钮。 + 正在使用 %1$s 配置:%2$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 7a79238501..1e921fb63e 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -4138,4 +4138,6 @@ 遊戲內捷徑 顯示 Smart Glasses 捷徑 在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。 + 正在使用 %1$s 設定檔:%2$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 00e2bae533..7ea662de72 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -4138,4 +4138,6 @@ 遊戲內捷徑 顯示 Smart Glasses 捷徑 在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。 + 正在使用 %1$s 設定檔:%2$s + 正在使用預設設定檔:%1$s diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9ab2d5584d..213b72aa62 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2857,6 +2857,8 @@ Shared by Steam and Desktop. Applies live. Shared by Steam and Desktop. FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement. + Using %1$s profile: %2$s + Using Default profile: %1$s Filter sharpness %1$s Sets scaling to %2$s. Match screen (%1$d×%2$d) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt new file mode 100644 index 0000000000..36708bc145 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionPrefsUpscalerTest.kt @@ -0,0 +1,79 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class SessionPrefsUpscalerTest { + private lateinit var context: Context + + @Before fun setUp() { + context = RuntimeEnvironment.getApplication() + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun gameOverridesAreIsolatedAndFallBackToTheGlobalFilter() { + SessionPrefs.setUpscaler(context, 4) + SessionPrefs.setGameUpscaler(context, "12345", 7) + + assertEquals(4, SessionPrefs.upscaler(context)) + assertEquals(7, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + assertEquals(4, SessionPrefs.screenEffectsUpscaler(context, "game:54321")) + assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "54321")) + assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345")) + } + + @Test fun resettingGameOverrideRestoresTheGlobalFilter() { + SessionPrefs.setUpscaler(context, 3) + SessionPrefs.setGameUpscaler(context, "12345", 6) + + SessionPrefs.clearGameUpscaler(context, "12345") + + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(3, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + } + + @Test fun screenEffectsUpscalerApiKeepsGameFiltersSeparateFromScreenEffects() { + SessionPrefs.setUpscaler(context, 4) + SessionPrefs.setScreenEffectsUpscaler(context, "game:12345", 8) + + assertEquals(8, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345")) + } + + @Test fun legacyGameFilterOverridesRemainReadableAndCanBeReset() { + val profile = JSONObject().put("upscaler", 6) + val profiles = JSONObject().put("game:12345", profile) + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .putString("screenEffects.profiles", profiles.toString()).commit() + + assertTrue(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(6, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + + SessionPrefs.clearGameUpscaler(context, "12345") + + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(2, SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + assertFalse(SessionPrefs.hasScreenEffectsOverride(context, "game:12345")) + } + + @Test fun deletingGameScreenEffectsProfileClearsUpscalerOverrideEvenWithoutEffectsProfile() { + SessionPrefs.setGameUpscaler(context, "12345", 6) + + SessionPrefs.deleteScreenEffectsProfile(context, "game:12345") + + assertFalse(SessionPrefs.hasGameUpscalerOverride(context, "12345")) + assertEquals(SessionPrefs.upscaler(context), SessionPrefs.screenEffectsUpscaler(context, "game:12345")) + } +} From 9c6fafec4c3fcc2bbd6e08bc051ed189a5081ac3 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:52:52 -0500 Subject: [PATCH 59/80] fix(hook): end readlink answers so Steam's install scripts run without proot (#3386) Co-authored-by: maxjivi05 --- tools/nativeguest/hook/fileops.c | 1 + tools/nativeguest/hook/setup.c | 1 + tools/tests/test_native_hook_proc_exe.py | 16 ++++++++++++++++ 3 files changed, 18 insertions(+) diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index a515e6a248..8f6b936eda 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -422,6 +422,7 @@ static ssize_t copy_readlink_result(char *buf, size_t bufsiz, const char *out, s if (ret <= 0 || out == buf) return ret; size_t n = (size_t)ret < bufsiz ? (size_t)ret : bufsiz; memcpy(buf, out, n); + if (n < bufsiz) buf[n] = '\0'; return (ssize_t)n; } diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index 4b7d2bbb0f..d94956af5a 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -307,6 +307,7 @@ static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) { size_t len = strlen(out_path); size_t copy_len = (len < bufsiz) ? len : bufsiz; memcpy(buf, out_path, copy_len); + if (copy_len < bufsiz) buf[copy_len] = '\0'; return (ssize_t)copy_len; } diff --git a/tools/tests/test_native_hook_proc_exe.py b/tools/tests/test_native_hook_proc_exe.py index 479c78109d..3e1182c9bf 100644 --- a/tools/tests/test_native_hook_proc_exe.py +++ b/tools/tests/test_native_hook_proc_exe.py @@ -19,6 +19,13 @@ int main(int argc, char **argv) { for (int i = 1; i < argc; i++) { char buf[4096]; ssize_t n; + if (strncmp(argv[i], "fill:", 5) == 0 || strncmp(argv[i], "short:", 6) == 0) { + size_t size = argv[i][0] == 'f' ? sizeof(buf) : 256; + memset(buf, '/', sizeof(buf)); + n = readlink(strchr(argv[i], ':') + 1, buf, size); + printf("%s\t%s\n", argv[i], n > 0 && (size_t)n < size && buf[n] == 0 ? "ends" : "runs on"); + continue; + } if (strncmp(argv[i], "at:", 3) == 0) { int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY); n = dfd >= 0 ? readlinkat(dfd, "exe", buf, sizeof(buf) - 1) : -1; @@ -57,6 +64,7 @@ class NativeHookProcExeTest(unittest.TestCase): (cls.root / "usr/bin").mkdir(parents=True) cls.kwin = cls.root / "usr/bin/kwin_wayland" shutil.copy(tmp / "sleeper", cls.kwin) + (cls.root / "compositor").symlink_to("usr/bin/kwin_wayland") cls.runtime = tmp / "runtime" cls.runtime.mkdir() cls.bound = cls.runtime / "chrome" @@ -151,6 +159,14 @@ class NativeHookProcExeTest(unittest.TestCase): link = f"/proc/{pid}/exe" self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link]) + def test_the_own_program_answer_ends_where_the_name_ends(self): + key = "fill:/proc/self/exe" + self.assertEqual("ends", self.readlink(key)[key]) + + def test_a_link_read_into_a_short_buffer_ends_where_its_target_ends(self): + key = "short:/compositor" + self.assertEqual("ends", self.readlink(key)[key]) + def test_a_loader_without_a_known_program_keeps_the_kernel_link(self): pid = self.start(loader=True) link = f"/proc/{pid}/exe" From 56213d74b378c0a6138f028bb3b09d9237336f62 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 5 Dec 2026 01:59:21 -0500 Subject: [PATCH 60/80] fix(ubuntu): drop the Mesa patches Ubuntu's Mesa 26.2 now ships and rebase the rest (#3736) --- tools/ubuntu/README.md | 8 +- ...0002-turnip-kgsl-accept-ubwc-5-and-6.patch | 30 ----- ...p-kgsl-report-device-numbers-for-wsi.patch | 22 +-- ...ck-zs-aspect-before-creating-zs-view.patch | 41 ------ ...reed-memory-while-the-client-is-idle.patch | 125 +++++++++--------- 5 files changed, 83 insertions(+), 143 deletions(-) delete mode 100644 tools/ubuntu/patches/mesa/0002-turnip-kgsl-accept-ubwc-5-and-6.patch delete mode 100644 tools/ubuntu/patches/mesa/0005-zink-check-zs-aspect-before-creating-zs-view.patch diff --git a/tools/ubuntu/README.md b/tools/ubuntu/README.md index ba7256ccf7..751ce585c0 100644 --- a/tools/ubuntu/README.md +++ b/tools/ubuntu/README.md @@ -7,10 +7,10 @@ Steam on the desktop). The app installs it into `files/linuxfs` and runs it unde - `build-debs.sh` (run in an `ubuntu:26.04` container on an arm64 runner) rebuilds two Ubuntu source packages: Mesa with `-Dfreedreno-kmds=msm,kgsl`, so Turnip and freedreno reach Android's `/dev/kgsl-3d0`, and KWin with `patches/kwin` (nested desktop scale, an explicit render node, - scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds KGSL - UBWC 5/6 (backported from upstream Mesa) and the KGSL device numbers for WSI (from - [Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). It also carries Icenowy Zheng's upstream - Zink fix that keeps the Imagination depth/stencil swizzle off colour views (Mesa d55418dae7). + scroll source/discrete forwarding). Both get a `+droiddeck` version. `patches/mesa` adds the KGSL + device numbers for WSI (from [Droid-Deck/Drivers](https://github.com/Droid-Deck/Drivers)). + KGSL UBWC 5/6 and Icenowy Zheng's Zink fix that keeps the Imagination depth/stencil swizzle off + colour views (Mesa d55418dae7) are in Ubuntu's Mesa 26.2 and no longer patched. Zink also reclaims the memory a client freed once it has been idle for a second: otherwise only its next allocation does, and Steam's UI behind a game held 250 MiB more of unswappable GPU memory. - The runtime's built-in Vulkan driver is DroidDeck's DD-Turnip Linux build (`DD_TURNIP_URL` and diff --git a/tools/ubuntu/patches/mesa/0002-turnip-kgsl-accept-ubwc-5-and-6.patch b/tools/ubuntu/patches/mesa/0002-turnip-kgsl-accept-ubwc-5-and-6.patch deleted file mode 100644 index 1bdc8be424..0000000000 --- a/tools/ubuntu/patches/mesa/0002-turnip-kgsl-accept-ubwc-5-and-6.patch +++ /dev/null @@ -1,30 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: maxjivi05 -Date: Wed, 28 Oct 2026 13:30:00 -0400 -Subject: [PATCH] turnip/kgsl: accept UBWC 5 and 6 - -Backport of upstream Mesa's KGSL_UBWC_5_0/6_0 handling so Adreno 8xx -(UBWC 6) is found by the KGSL backend. ---- ---- a/src/freedreno/vulkan/msm_kgsl.h 2026-10-28 13:27:57.698671357 -0400 -+++ b/src/freedreno/vulkan/msm_kgsl.h 2026-10-28 13:27:57.700490261 -0400 -@@ -247,6 +247,8 @@ - #define KGSL_UBWC_2_0 2 - #define KGSL_UBWC_3_0 3 - #define KGSL_UBWC_4_0 4 -+#define KGSL_UBWC_5_0 5 -+#define KGSL_UBWC_6_0 6 - - /* - * Reset status values for context ---- a/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 13:27:57.697821704 -0400 -+++ b/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 13:27:57.710313562 -0400 -@@ -1884,6 +1884,8 @@ - device->ubwc_config.macrotile_mode = FDL_MACROTILE_4_CHANNEL; - break; - case KGSL_UBWC_4_0: -+ case KGSL_UBWC_5_0: -+ case KGSL_UBWC_6_0: - device->ubwc_config.bank_swizzle_levels = 0x6; - device->ubwc_config.macrotile_mode = FDL_MACROTILE_8_CHANNEL; - break; diff --git a/tools/ubuntu/patches/mesa/0003-turnip-kgsl-report-device-numbers-for-wsi.patch b/tools/ubuntu/patches/mesa/0003-turnip-kgsl-report-device-numbers-for-wsi.patch index 5d09c46d80..91a080d483 100644 --- a/tools/ubuntu/patches/mesa/0003-turnip-kgsl-report-device-numbers-for-wsi.patch +++ b/tools/ubuntu/patches/mesa/0003-turnip-kgsl-report-device-numbers-for-wsi.patch @@ -8,9 +8,11 @@ nested compositor such as gamescope can advertise dma-buf feedback and Vulkan swapchains work without the software WSI. Ported from Droid-Deck/Drivers (patches/scripts/linux_kgsl_wsi.py). --- ---- a/src/freedreno/vulkan/tu_device.cc 2026-10-28 14:41:54.161481991 -0400 -+++ b/src/freedreno/vulkan/tu_device.cc 2026-10-28 14:41:54.174757117 -0400 -@@ -312,7 +312,7 @@ +diff --git a/src/freedreno/vulkan/tu_device.cc b/src/freedreno/vulkan/tu_device.cc +index e8ef940..78ea4fc 100644 +--- a/src/freedreno/vulkan/tu_device.cc ++++ b/src/freedreno/vulkan/tu_device.cc +@@ -353,7 +353,7 @@ get_device_extensions(const struct tu_physical_device *device, .EXT_mutable_descriptor_type = true, .EXT_nested_command_buffer = true, .EXT_non_seamless_cube_map = true, @@ -18,19 +20,21 @@ Droid-Deck/Drivers (patches/scripts/linux_kgsl_wsi.py). + .EXT_physical_device_drm = !is_kgsl(device->instance) || device->has_local, .EXT_pipeline_creation_cache_control = true, .EXT_pipeline_creation_feedback = true, - .EXT_primitive_topology_list_restart = true, ---- a/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 14:41:54.159481934 -0400 -+++ b/src/freedreno/vulkan/tu_knl_kgsl.cc 2026-10-28 14:41:54.174233883 -0400 -@@ -11,6 +11,8 @@ + #ifdef TU_USE_WSI_PLATFORM +diff --git a/src/freedreno/vulkan/tu_knl_kgsl.cc b/src/freedreno/vulkan/tu_knl_kgsl.cc +index 9cb95ec..a7a2ee0 100644 +--- a/src/freedreno/vulkan/tu_knl_kgsl.cc ++++ b/src/freedreno/vulkan/tu_knl_kgsl.cc +@@ -10,6 +10,8 @@ #include #include #include +#include +#include - #include #define __user -@@ -1907,6 +1909,13 @@ + #include "ion/ion.h" +@@ -1943,6 +1945,13 @@ tu_knl_kgsl_load(struct tu_instance *instance, int fd) instance->knl = &kgsl_knl_funcs; diff --git a/tools/ubuntu/patches/mesa/0005-zink-check-zs-aspect-before-creating-zs-view.patch b/tools/ubuntu/patches/mesa/0005-zink-check-zs-aspect-before-creating-zs-view.patch deleted file mode 100644 index 3a2aa0bd96..0000000000 --- a/tools/ubuntu/patches/mesa/0005-zink-check-zs-aspect-before-creating-zs-view.patch +++ /dev/null @@ -1,41 +0,0 @@ -From d55418dae753c8daacf66ab81a7481094808576a Mon Sep 17 00:00:00 2001 -From: Icenowy Zheng -Date: Sun, 31 May 2026 21:56:32 +0800 -Subject: [PATCH] zink: check Z/S aspect before creating Z/S image view - -When moving the code of creating image views to the init_sampler_view() -function, the check for Z/S aspect bits was forgotten to be added -(because it was a big if gating a lot of code originally). - -When the driver doesn't have needs_zs_shader_swizzle set, this is not -problematic, because the condition for creating Z/S view is to have only -Z aspect; however the needs_zs_shader_swizzle case now fails because Z/S -views are now created for color images. - -Fix the issue by re-adding the Z/S aspect check before checking -needs_zs_shader_swizzle flag. - -Fixes: cafa22142bf1 ("zink: create views for samplers lazily") -Signed-off-by: Icenowy Zheng -Part-of: ---- - src/gallium/drivers/zink/zink_context.c | 3 ++- - 1 file changed, 2 insertions(+), 1 deletion(-) - -diff --git a/src/gallium/drivers/zink/zink_context.c b/src/gallium/drivers/zink/zink_context.c -index e264e57b2703..41bc1b6932a7 100644 ---- a/src/gallium/drivers/zink/zink_context.c -+++ b/src/gallium/drivers/zink/zink_context.c -@@ -1173,7 +1173,8 @@ init_sampler_view(struct zink_context *ctx, struct zink_sampler_view *sv) - - bool red_depth_sampler_view = false; - if (sv->ivci.subresourceRange.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT || -- screen->driver_compiler_workarounds.needs_zs_shader_swizzle) { -+ ((sv->ivci.subresourceRange.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) && -+ screen->driver_compiler_workarounds.needs_zs_shader_swizzle)) { - VkComponentSwizzle *swizzle = (VkComponentSwizzle*)&sv->ivci.components; - for (unsigned i = 0; i < 4; i++) { - if (swizzle[i] == VK_COMPONENT_SWIZZLE_ONE || --- -GitLab - diff --git a/tools/ubuntu/patches/mesa/0006-zink-reclaim-freed-memory-while-the-client-is-idle.patch b/tools/ubuntu/patches/mesa/0006-zink-reclaim-freed-memory-while-the-client-is-idle.patch index a2081913f2..34b23bd68d 100644 --- a/tools/ubuntu/patches/mesa/0006-zink-reclaim-freed-memory-while-the-client-is-idle.patch +++ b/tools/ubuntu/patches/mesa/0006-zink-reclaim-freed-memory-while-the-client-is-idle.patch @@ -7,55 +7,8 @@ fullscreen game after scrolling its library, and released it the moment the overlay drew a frame. A thread now reclaims once a second after a second without allocations. ---- a/src/util/pb_slab.h -+++ b/src/util/pb_slab.h -@@ -145,6 +145,9 @@ - unsigned - pb_slabs_reclaim(struct pb_slabs *slabs); - -+unsigned -+pb_slabs_reclaim_all(struct pb_slabs *slabs); -+ - bool - pb_slabs_init(struct pb_slabs *slabs, - unsigned min_order, unsigned max_order, ---- a/src/util/pb_slab.c -+++ b/src/util/pb_slab.c -@@ -231,6 +231,19 @@ - return num_reclaims; - } - -+/* Like pb_slabs_reclaim, but skips entries that are still in use instead of -+ * stopping at the first ones, so entries freed behind them are reclaimed too. -+ */ -+unsigned -+pb_slabs_reclaim_all(struct pb_slabs *slabs) -+{ -+ unsigned num_reclaims; -+ simple_mtx_lock(&slabs->mutex); -+ num_reclaims = pb_slabs_reclaim_all_locked(slabs); -+ simple_mtx_unlock(&slabs->mutex); -+ return num_reclaims; -+} -+ - /* Initialize the slabs manager. - * - * The minimum and maximum size of slab entries are 2^min_order and ---- a/src/gallium/drivers/zink/zink_types.h -+++ b/src/gallium/drivers/zink/zink_types.h -@@ -1427,6 +1427,12 @@ - struct pb_slabs bo_slabs[NUM_SLAB_ALLOCATORS]; - unsigned min_alloc_size; - uint32_t next_bo_unique_id; -+ uint32_t alloc_serial; -+ thrd_t reclaim_thread; -+ mtx_t reclaim_lock; -+ cnd_t reclaim_cond; -+ bool reclaim_stop; -+ bool reclaim_running; - } pb; - uint8_t heap_map[ZINK_HEAP_MAX][VK_MAX_MEMORY_TYPES]; // mapping from zink heaps to memory type indices - uint8_t heap_count[ZINK_HEAP_MAX]; // number of memory types per zink heap +diff --git a/src/gallium/drivers/zink/zink_bo.c b/src/gallium/drivers/zink/zink_bo.c +index 0e98a20..a0d0ceb 100644 --- a/src/gallium/drivers/zink/zink_bo.c +++ b/src/gallium/drivers/zink/zink_bo.c @@ -34,6 +34,7 @@ @@ -66,7 +19,7 @@ without allocations. #ifdef HAVE_LIBDRM #define ZINK_USE_DMABUF -@@ -577,6 +578,7 @@ +@@ -537,6 +538,7 @@ struct pb_buffer_lean * zink_bo_create(struct zink_screen *screen, uint64_t size, unsigned alignment, enum zink_heap heap, enum zink_alloc_flag flags, unsigned mem_type_idx, const void *pNext) { struct zink_bo *bo; @@ -74,7 +27,7 @@ without allocations. /* pull in sparse flag */ flags |= zink_alloc_flags_from_heap(heap); -@@ -1390,6 +1392,40 @@ +@@ -1350,6 +1352,39 @@ bo_slab_alloc_normal(void *priv, unsigned mem_type_idx, unsigned entry_size, uns return bo_slab_alloc(priv, mem_type_idx, entry_size, group_index, false); } @@ -100,8 +53,7 @@ without allocations. + + uint32_t serial = p_atomic_read(&screen->pb.alloc_serial); + if (serial == seen) { -+ for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) -+ pb_slabs_reclaim_all(&screen->pb.bo_slabs[i]); ++ pb_slabs_reclaim_all(&screen->pb.bo_slabs); + pb_cache_release_all_buffers(&screen->pb.bo_cache); + } + seen = serial; @@ -115,10 +67,10 @@ without allocations. bool zink_bo_init(struct zink_screen *screen) { -@@ -1425,12 +1461,25 @@ - min_slab_order = max_order + 1; +@@ -1371,12 +1406,25 @@ zink_bo_init(struct zink_screen *screen) + (void*)bo_slab_free)) { + return false; } - screen->pb.min_alloc_size = 1 << screen->pb.bo_slabs[0].min_order; + + mtx_init(&screen->pb.reclaim_lock, mtx_plain); + cnd_init(&screen->pb.reclaim_cond); @@ -138,6 +90,61 @@ without allocations. + thrd_join(screen->pb.reclaim_thread, NULL); + screen->pb.reclaim_running = false; + } - for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) { - if (screen->pb.bo_slabs[i].groups) - pb_slabs_deinit(&screen->pb.bo_slabs[i]); + if (screen->pb.bo_slabs.groups) + pb_slabs_deinit(&screen->pb.bo_slabs); + pb_cache_deinit(&screen->pb.bo_cache); +diff --git a/src/gallium/drivers/zink/zink_types.h b/src/gallium/drivers/zink/zink_types.h +index 9c461cf..f31cc42 100644 +--- a/src/gallium/drivers/zink/zink_types.h ++++ b/src/gallium/drivers/zink/zink_types.h +@@ -1443,6 +1443,12 @@ struct zink_screen { + struct pb_cache bo_cache; + struct pb_slabs bo_slabs; + uint32_t next_bo_unique_id; ++ uint32_t alloc_serial; ++ thrd_t reclaim_thread; ++ mtx_t reclaim_lock; ++ cnd_t reclaim_cond; ++ bool reclaim_stop; ++ bool reclaim_running; + } pb; + uint8_t heap_map[ZINK_HEAP_MAX][VK_MAX_MEMORY_TYPES]; // mapping from zink heaps to memory type indices + uint8_t heap_count[ZINK_HEAP_MAX]; // number of memory types per zink heap +diff --git a/src/util/pb_slab.c b/src/util/pb_slab.c +index 24f4d34..bf27e88 100644 +--- a/src/util/pb_slab.c ++++ b/src/util/pb_slab.c +@@ -231,6 +231,19 @@ pb_slabs_reclaim(struct pb_slabs *slabs) + return num_reclaims; + } + ++/* Like pb_slabs_reclaim, but skips entries that are still in use instead of ++ * stopping at the first ones, so entries freed behind them are reclaimed too. ++ */ ++unsigned ++pb_slabs_reclaim_all(struct pb_slabs *slabs) ++{ ++ unsigned num_reclaims; ++ simple_mtx_lock(&slabs->mutex); ++ num_reclaims = pb_slabs_reclaim_all_locked(slabs); ++ simple_mtx_unlock(&slabs->mutex); ++ return num_reclaims; ++} ++ + /* Initialize the slabs manager. + * + * The minimum and maximum size of slab entries are 2^min_order and +diff --git a/src/util/pb_slab.h b/src/util/pb_slab.h +index 7ef7c5d..663dcc7 100644 +--- a/src/util/pb_slab.h ++++ b/src/util/pb_slab.h +@@ -145,6 +145,9 @@ pb_slab_free(struct pb_slabs* slabs, struct pb_slab_entry *entry); + unsigned + pb_slabs_reclaim(struct pb_slabs *slabs); + ++unsigned ++pb_slabs_reclaim_all(struct pb_slabs *slabs); ++ + bool + pb_slabs_init(struct pb_slabs *slabs, + unsigned min_order, unsigned max_order, From 2d25fb91c524e6717e5103e7d944b0493c7f3f45 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sat, 5 Dec 2026 02:26:42 -0500 Subject: [PATCH 61/80] Run Easy Anti-Cheat and BattlEye games on x86-64 DroidDeck-Proton under FEX (#3641) * FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers * Guest hook: route raw execve/execveat through the exec wrapper and pass self-sent SIGSYS to the program A program that execs with syscall(SYS_execveat, ...) bypassed the environment the guest needs, so re-executing /proc/self/exe died in the loader. /proc/self/exe now maps to the real program on exec as it already does on open. A SIGSYS the program queues itself, or one from a filter for another architecture, went to the Android-filter emulation instead of the program's handler. * FEX: list only guest mappings in /proc//maps on hosts below 47 address bits Credit the anti-cheat emulation source in the patch header. * Preloads: leave poll, ppoll and select buffers untouched when no emulated device is open A bad user pointer now reaches the kernel and returns EFAULT instead of crashing the caller inside the wrapper. * Emulate only host-architecture seccomp traps in the guest hook; report the calling thread's seccomp mode in FEX's /proc/self/status A SIGSYS carrying another architecture's seccomp siginfo now takes its default action when the program has no handler, so a process whose emulated filter traps a syscall while SIGSYS is blocked or ignored dies as on Linux. * FEX: read the host status file through the raw openat syscall * README: credit StonkGuy's FEX anti-cheat emulation * FEX: open the host status file with a direct system call so preloads cannot rewrite it * FEX: hand a traced program's ptrace state across exec * Credit StonkGuy in the FEX anti-cheat patches and README Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com> * FEX: open guest paths with the raw openat system call so host preloads cannot replace the file * FEX: serve emulated proc files by the requested path when the host returns a memfd * FEX: map fixed guest memory above a small host address space Co-authored-by: StonkGuy * FEX: serve decoder reads from fixed guest memory above the host limit * Run games with anti-cheat files on an x86-64 DroidDeck-Proton under FEX The Proton launchers look for Easy Anti-Cheat or BattlEye bridge files in the game folder and, when an x86-64 DroidDeck-Proton and the matching Proton runtime are installed, hand the launch to that Proton under FEX with the game's own prefix. Picking the x86-64 tool directly also runs it under FEX. DROIDDECK_ANTICHEAT=off keeps a game on ARM64. * Keep x86-64 DroidDeck-Proton builds out of the ARM64 tool list * droiddeck-fex: take the runtime from an adopted tool's original manifest * FEX: show the guest command line when the argument area cannot be remapped * FEX: describe the container's procfs in emulated mount tables * FEX: order the anti-cheat series after the guest stack patch from main * Test the container procfs view of FEX's emulated mount tables * Docs: describe the anti-cheat signal mask fix and the container procfs view * README: match the StonkGuy credit to the renumbered FEX patches * Keep anti-cheat games on a tool the user chose instead of moving them to x86-64 * test(game-env): build the adopted-tool wrapper through extra_wrapper_sh * Check anti-cheat runtime bridges, apply component choices under FEX and honour MAP_FIXED_NOREPLACE above the host limit * Check the driver query is answered before each wrapper's call sites * Keep x86-64 Proton builds out of the automatic default tool * Keep high guest mappings intact when a fixed map or unmap fails Check room in the region table, splits included, before a fixed map or unmap removes anything, return the host munmap error without touching the table entry, and keep write-protecting low shared aliases of executable ranges that sit above the host address limit. * Keep a requested x86-64 default and accept linked anti-cheat runtimes A request for the current automatic x86-64 default now marks it as the app's choice, so the next settle no longer moves it back to ARM64. Anti-cheat runtime discovery follows a symlinked runtime directory. * Route anti-cheat games to x86-64 Proton only on a capable FEX The FEX build now lists its patches in share/fex-emu/.droiddeck-patches. Anti-cheat routing needs the fixed guest memory patch in that list and otherwise keeps the launch on ARM64, as an older FEX cannot map the anti-cheat helper buffer above the host address limit. Installing a FEX build without the list removes a list left by an earlier build. * Update FEX before deciding anti-cheat routing A device on an older FEX build never went through droiddeck-fex on the ARM64 path, so the catalog FEX was never installed and the gate kept anti-cheat games on ARM64 forever. dd_anticheat now runs the new droiddeck-fex update action first, which installs the catalog build under the same lock and retry window as other FEX launches. * Leave MAP_FIXED_NOREPLACE above the host limit to the host Wine finds the top of the address space with MAP_FIXED_NOREPLACE probes. Claiming those probes above a 39-bit host limit made Wine place its stacks in relocated memory, and every wineserver request then failed with EFAULT because the iovec buffers it passes to writev are nested pointers that are not translated. Only MAP_FIXED requests are relocated again, so the probes see the real host limit while fixed mappings above it keep working. * Translate only pointer syscall arguments into high guest memory Pointer arguments are now picked from a per-syscall layout table, so scalar values such as a truncate length are never rewritten. Sized buffers must map to one contiguous host range or the call fails with EFAULT, and new host backings are placed next to their guest neighbours so adjacent mappings stay contiguous. readv, writev and the preadv/pwritev family, sendmsg and recvmsg get a host-side copy of their iovec and msghdr with translated bases, leaving the guest copies untouched. Code invalidation for kernel writes maps the host buffer back to its guest address, and an unmap checks the table before it changes any host mapping. * Claim high guest memory only with LSE atomics and invalidate every code alias High guest mappings are claimed only when the JIT emits LSE atomics, and exclusive load/store instructions are never single-stepped, so an atomic on high memory cannot spin. A store into high code invalidates every mirror of the written page through the tracked mapping. madvise and mprotect on high memory apply to each region at its own host address. * Reject wrapping lengths and drop stale code on discarded high memory A nonzero length that wraps when page-aligned now fails madvise with EINVAL and mprotect with ENOMEM, as on Linux. Discarding advice on high memory invalidates translated code for the range whenever advice reached any region. * Add an end-to-end probe for guest memory above the host address limit * Emulate exclusive pairs on high guest memory and release failed host unmaps later * Size counted guest buffers by element and keep exclusive access within guest protection poll, ppoll, epoll waits, mmsg calls and select bitmaps now translate the whole array their count describes, so a buffer that crosses into an unrelated host range fails with EFAULT and oversized counts cannot wrap. High regions remember their protection through mprotect, splitting at the range edges, and exclusive stores to read-only pages or loads from inaccessible pages reach the guest as a fault instead of being emulated. * Refuse a high unmap when failed host unmaps could not all be retained UnmapLocked counts the overlapping regions before it changes anything and returns ENOMEM when the retired list could not hold all of them, so a host range is never dropped from tracking while still mapped. * Serve memory trim requests while syscall user dispatch blocks A thread that runs with syscall user dispatch on and its selector set to block (as x86-64 Wine does while in Windows code) took the trim signal with the selector still blocking. Every raw syscall the handler made was then dispatched to the program's SIGSYS handler, which either deadlocked the thread or killed the process when SIGSYS was blocked, so the session saw it as a deaf process and the game stalled during loading. Track the selector each thread registers through prctl, allow syscalls for the length of the handler and restore the selector before returning. * Allow syscalls for a forwarded prctl while dispatch blocks The prctl wrapper issues its syscall from the preload's own text, so a thread whose selector blocks got SIGSYS where the plain libc call would have been dispatched the same way by the caller's own rules. Allow syscalls for the forwarded call and restore the selector afterwards. The dispatch test now waits until the selector blocks before it sends the trim request, and checks a prctl call made while it blocks. * Merge high regions after protection changes and translate message batches Protect now merges neighbouring high regions whose guest and host ranges touch and whose protection and code state match, so toggling page protections no longer fills the region table. Exclusive loads on high memory accept write-only pages and exclusive stores need only PROT_WRITE, matching x86-64 where writable pages are readable. sendmmsg and recvmmsg translate the name, control and io vectors of every message in the batch, return msg_len for each processed message and the received header fields for recvmmsg. Counted arrays passed to getgroups, setgroups, semop, semtimedop, io_submit, io_getevents, io_pgetevents, move_pages, futex_waitv and listmount are now checked to stay within one host range. The unused ToHost helper is removed. * Translate fixed-size, string and in-array guest pointers in high memory Give every syscall pointer without a length a fixed x86-64 size, a length read through another argument, or a terminator scan for strings, so spans crossing separately backed regions are refused before the kernel sees them. Size message queue buffers as the type word plus msgsz. Translate io_submit control blocks and their buffers, including vectored reads and writes, through bounded host copies, restore the guest words afterwards, and report guest iocb addresses back from io_getevents. Translate move_pages page lists for the calling process and futex_waitv addresses. Merge new mappings with matching neighbours. * Size high-memory syscall spans by kernel widths and embedded sizes Read counts with the width the kernel uses for each argument, so int and unsigned int counts ignore the upper register bits and negative counts reach the handler. Size capability data by its header version, perf and scheduler attributes, file handles and mount requests by their own size fields, and landlock rules by rule type. Keep the translated prefix of a message batch, read headers that span separate backings one by one, write results back through the current guest mapping, and stop counting messages whose length cannot be stored. Revisit an entry moved into an earlier slot while merging regions. Give newer syscalls fallback numbers in the test harness. * Send translated message batches one message at a time Submit sendmmsg batches that need scratch headers one message per call, storing each length before the next message goes out, so a length that cannot be stored stops the batch where Linux would. Skip the name length when no name was given and store flags before the control length. Check the whole fixed file-handle header even when its size is invalid. Hand capget and capset a private header so the checked data size matches the version the kernel reads, and return a rewritten version to the guest. Patch and restore AIO control blocks under the mapping lock and restore only the block that was patched. * Harden high-memory aio, capability and message batch write-backs Restore patched aio buffers through /proc/self/mem when the control block became read-only and keep the scratch vectors alive if that fails too, fault capability calls whose header write-back fails, stop send batches after a short message, and pin the batch socket with a private dup. * Pin batch sockets, fall back to whole batches and reconcile pending aio restores Follow-up message sends and the first dispatch share one duplicated socket. When it cannot be duplicated, the whole translated batch goes to the kernel in one call and lengths are written back up to the first one that cannot be stored. Short sends compare against the iovec lengths given to the kernel. Unrestorable aio_buf edits, including unreadable control blocks, keep their storage in a bounded list that later submissions reconcile. * Stop message batches at unreadable vectors, send singly without a spare descriptor and reserve aio restore slots A message whose iovec snapshot cannot be taken ends the prepared batch instead of being sent with an unknown length; when it is the first message the kernel handles the original array natively. When the batch socket cannot be duplicated, messages still go one at a time on the original descriptor with each length written before the next send. Pending aio restore slots are reserved under the pending mutex before the first guest edit and released or handed to the pending record, so concurrent submissions cannot exceed the bound. Tests use a real socket pair, injected descriptor exhaustion and concurrent reservations. * Send only the first message of a batch when the socket cannot be pinned * Replay high-memory faults over the whole access and reconcile aio restores on unmap * Keep high-memory traps ordered, fault-exact and locked against unmap Protect, Map and low mmap/munmap/mremap/mprotect reconcile pending aio restores at once, and io_submit reconciles them even when no high region is mapped. Ordered loads and stores split across backings are emulated between full fences instead of being byte-copied through the trampoline; atomics and exclusives are still refused. Gather and scatter use fault-safe copies, and a failing piece is re-faulted at the guest instruction through a probe load, with SIGBUS redelivered the same way. The VMA lock is held from planning until the scatter finishes, so unmap and protect cannot race a resumed access. Sign-extending loads are no longer classified as writes. * Defer user signals while guest high memory mappings are held Only the trampoline breakpoint completes a replay, user-sent SIGSEGV, SIGBUS and SIGTRAP raised while the mapping lock is held are requeued after it is released, and stranded control block words are restored when their page turns readable again. The harness now runs under a timeout. * Rebase the FEX patch series onto FEX-2612 * FEX: restore stranded aio words before readable protection, report failures Restore every pending aio word in the range before a readable guest protection is applied, on both the high and low paths, and fail the guest mprotect with the old protection kept when a word cannot be restored or its window cannot be closed. Ignore user-sent SIGSEGV/SIGBUS after deferral, read the cleared syscall info when resuming with guest GPRs and on restore, and check exclusive acquisition from a separate thread in the harness. * FEX: submit aio control blocks through private host copies Stop editing guest IOCBs in place when aio_buf needs translation. io_submit now hands the kernel a host copy of each such control block, maps io_event.obj back to the guest pointer when the completion is reaped, redirects io_cancel by guest pointer and context to the copy, and frees copies on reap, on io_destroy, or when the kernel did not accept them. The guest control block is never patched and its protection is never touched, so the pending restore records, the protection windows and the restore hooks in mmap, munmap, mremap and mprotect are removed with their tests. * fex: keep aio keys, cancels and reaped events native for copied control blocks Guest aio_key is no longer cleared before dispatch: the slot is probed with a same-value write and only the first n accepted copies get key 0 after the host io_submit returns n. io_cancel redirects to a copy only when the guest block is readable and its key is 0, so unreadable blocks fault in the kernel as before. io_getevents and io_pgetevents reap into emulator storage, translate and release copies there, then copy the events out, returning -EFAULT if that fails. A successful io_setup clears the ring header magic so userspace ring reapers fall back to io_getevents, where copies are translated and released. * fex: leave aio rejections, keys and unwritable event buffers to the kernel A copied control block whose key slot is read-only is now passed to the kernel as the guest's own block at the end of the list, so the kernel reports its native fd, eventfd or key error. After io_submit, guest keys follow the private copies through the first rejected position, and they are stored through a fresh translation of the guest address, skipped when it no longer maps. io_getevents and io_pgetevents probe the guest event buffer and reap at most its writable prefix, handing an unwritable buffer to the kernel so completions are not consumed. * Kept AIO completions and key stores stable against sibling remaps Wrapped event buffers go to the kernel unchanged. Direct reaps report guest control blocks and release copies only after the store lands. Guest stores and reads hold the mapping lock across translation and copy. Completions whose copy-out fails are stashed per context and delivered first on the next reap, and dropped on io_destroy. * fex: stage every AIO reap and keep stashed completions recoverable Hold the guest mapping for every high address, restore the caller's signal mask after thread-context holds, replace the fixed event stash with a per-context table that reserves space before dispatch, stage all reaps so control block identities are translated before copy-out, keep collecting ready completions once the stash meets min_nr, and restash events on every error except an interrupted delivery or a destroyed context. * fex: own AIO recovery storage before dispatch and bind it to the context lifetime Allocate the recovery node with the event buffer before the kernel consumes completions and hand the buffer itself to the stash when copy-out fails, so settling never allocates. Track each context by a generation that io_setup advances, so a destroy that finishes after a replacement context reuses the ring address only releases the old context's copies and stash. Drop the reservation cap so blocking reaps keep their min_nr. * fex: publish AIO contexts from private storage, keep their generation, wake blocked reapers for stashed completions * fex: wait for AIO events in bounded slices instead of wake markers, roll back setup by its own generation, fault unreadable io_setup output Blocked reapers wait in the kernel for at most 20 ms at a time and take stashed completions between waits until the guest minimum or timeout is met, so no eventfd or io_submit notification is needed. Deferred signals end the wait like EINTR. io_setup rollback uses the generation BeginContext installed, and an unreadable context output returns -EFAULT before dispatch. --------- Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com> Co-authored-by: StonkGuy --- README.md | 1 + app/src/main/cpp/fakeinput_steam.cpp | 34 +- .../launcher/session/ProtonExtras.kt | 5 +- .../launcher/session/ProtonExtrasTest.kt | 11 + docs/development/anti-cheat.md | 54 + docs/development/x86-64-steam-client.md | 7 +- tools/fex/build-in-arch.sh | 5 + ...7-cmake-install-code-without-depends.patch | 1 + ...signal-return-restores-syscall-state.patch | 4 +- ...gnal-handler-escape-frees-host-stack.patch | 20 +- .../0011-thunk-calls-mark-spilled-state.patch | 22 +- ...ignal-return-applies-guest-registers.patch | 12 +- .../0017-fd-exec-keeps-argv0-and-path.patch | 6 +- ...at-ptrace-seccomp-and-proc-emulation.patch | 5015 +++++++++++++++++ ...st-only-on-small-address-space-hosts.patch | 132 + ...roc-status-seccomp-of-calling-thread.patch | 53 + .../0024-read-host-status-directly.patch | 105 + .../0025-ptrace-state-across-exec.patch | 104 + ...mulated-proc-files-behind-host-memfd.patch | 78 + ...uest-memory-above-host-address-limit.patch | 3258 +++++++++++ ...t-cmdline-without-checkpoint-restore.patch | 58 + ...tables-describe-the-container-procfs.patch | 310 + tools/fex/probes/guest-high-memory.c | 92 + .../overlay/usr/local/bin/droiddeck-fex | 27 +- .../usr/local/bin/droiddeck-fex-update | 12 +- .../overlay/usr/local/bin/steam-compatibility | 95 +- tools/linuxfs/preload/vdec.c | 3 +- tools/linuxfs/preload/zram.c | 31 + tools/nativeguest/hook/exec.c | 1 + tools/nativeguest/hook/privileged.c | 13 + tools/nativeguest/hook/signals.c | 19 +- tools/tests/test_anticheat_routing.py | 223 + tools/tests/test_droiddeck_fex.py | 23 + tools/tests/test_droiddeck_proton_default.py | 46 + tools/tests/test_fex_guest_high_memory.py | 3392 +++++++++++ tools/tests/test_fex_install.py | 22 + tools/tests/test_fex_proc_mount_tables.py | 157 + .../tests/test_fex_signal_register_update.py | 51 +- tools/tests/test_game_environment.py | 12 +- tools/tests/test_zram_preload.py | 83 + 40 files changed, 13520 insertions(+), 77 deletions(-) create mode 100644 docs/development/anti-cheat.md create mode 100644 tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch create mode 100644 tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch create mode 100644 tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch create mode 100644 tools/fex/patches/0024-read-host-status-directly.patch create mode 100644 tools/fex/patches/0025-ptrace-state-across-exec.patch create mode 100644 tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch create mode 100644 tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch create mode 100644 tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch create mode 100644 tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch create mode 100644 tools/fex/probes/guest-high-memory.c create mode 100644 tools/tests/test_anticheat_routing.py create mode 100644 tools/tests/test_fex_guest_high_memory.py create mode 100644 tools/tests/test_fex_proc_mount_tables.py diff --git a/README.md b/README.md index 4a15571419..021fed17b3 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). - [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). +- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0021 with his authorship, patches 0022 to 0029 build on it, and his `eac-tests` regression suite verifies them. - x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence. diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index 856501cb3c..4c592ded09 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -329,16 +329,28 @@ static constexpr int kWatchedFds = 1 << 16; static constexpr int kWatchedBits = sizeof(unsigned long) * 8; static std::atomic watched_fds[kWatchedFds / kWatchedBits]; static std::atomic watched_beyond{false}; +static std::atomic watched_count{0}; static void watch_fd(int fd) { if (fd < 0) return; - if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release); - else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release); + if (fd >= kWatchedFds) { + watched_beyond.store(true, std::memory_order_release); + return; + } + const unsigned long bit = 1UL << (fd % kWatchedBits); + if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit)) + watched_count.fetch_add(1, std::memory_order_acq_rel); } static void unwatch_fd(int fd) { - if (fd >= 0 && fd < kWatchedFds) - watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release); + if (fd < 0 || fd >= kWatchedFds) return; + const unsigned long bit = 1UL << (fd % kWatchedBits); + if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit) + watched_count.fetch_sub(1, std::memory_order_acq_rel); +} + +static bool any_watched() { + return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire); } static bool watched(int fd) { @@ -4269,7 +4281,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout, const auto my_poll = next_symbol(Next::poll); const auto my_ppoll = next_symbol(Next::ppoll); - nfds_t first = 0; + nfds_t first = any_watched() ? 0 : nfds; while (first < nfds && !watched(fds[first].fd)) first++; bool has_fake_fds = false; std::vector real_fds; @@ -4372,12 +4384,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) { EXPORT int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout, const sigset_t *sigmask) { const auto my_ppoll = next_symbol(Next::ppoll); - if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) { - errno = EINVAL; - return -1; - } - for (nfds_t i = 0; i < nfds; ++i) { + for (nfds_t i = 0; any_watched() && i < nfds; ++i) { if (!is_fake_input_fd(fds[i].fd)) continue; + if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) { + errno = EINVAL; + return -1; + } if (!sigmask) return poll_fake(fds, nfds, static_cast(timespec_to_ms(timeout)), nullptr); sigset_t all_signals, original_mask; @@ -4410,6 +4422,8 @@ EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *t EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { const auto my_select = next_symbol(Next::select); + if (!any_watched()) + return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1; fd_set original_readfds; fd_set original_writefds; diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index 412fc79627..fa66513e3a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -66,11 +66,14 @@ object ProtonExtras { internal fun installedIn(dir: File, tool: Tool): List = dir.listFiles() - ?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) } + ?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && !x86_64Build(it) && usable(it) } ?.map { it.name } ?.sortedWith { a, b -> compareVersions(a, b) } ?: emptyList() + internal fun x86_64Build(dir: File): Boolean = + File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory + private fun usable(dir: File): Boolean { val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false diff --git a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt index d975b6b756..2f9f3ad5e5 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/ProtonExtrasTest.kt @@ -181,6 +181,17 @@ class ProtonExtrasTest { assertEquals(emptyList(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge"))) } + @Test + fun x86_64BuildsAreNotTakenForTheArm64Tool() { + val tools = temp.newFolder("compatibilitytools.d") + for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-14.2-x86_64")) installTool(tools, name) + File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs() + File(tools, "DroidDeck-Proton 11-7.5/files/lib/wine/x86_64-unix").mkdirs() + File(tools, "DroidDeck-Proton 11-7.5/files/bin-arm64").mkdirs() + assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedIn(tools, tool("droiddeck"))) + assertTrue(ProtonExtras.x86_64Build(File(tools, "DroidDeck-Proton-11-14.2-x86_64"))) + } + @Test fun interruptedBuildsAreNotReportedAsInstalled() { val tools = temp.newFolder("compatibilitytools.d") diff --git a/docs/development/anti-cheat.md b/docs/development/anti-cheat.md new file mode 100644 index 0000000000..d287aea85e --- /dev/null +++ b/docs/development/anti-cheat.md @@ -0,0 +1,54 @@ +# Easy Anti-Cheat and BattlEye + +On a Steam Deck, Proton loads Valve's anti-cheat runtimes (Proton EasyAntiCheat Runtime, app 1826330, and +Proton BattlEye Runtime, app 1161040). Their bridge libraries are x86 only, so the ARM64 DroidDeck-Proton +cannot load them. Games that need them run an x86-64 DroidDeck-Proton under FEX instead. + +## Routing + +The Proton launchers (`steam-compatibility`: the built-in DroidDeck-Proton launcher and the wrapper put around +every tool in `compatibilitytools.d`) check each `run` and `waitforexitandrun` before any ARM64 setup: + +- **Condition.** The game folder (`STEAM_COMPAT_INSTALL_PATH`, three levels deep) holds one of + `EasyAntiCheat/Settings.json`, `easyanticheat_x64.so`, `BEClient_x64.so` or `BEService_x64.exe`. No + title, app ID or device list is involved. +- **Chosen tool.** Only launches through DroidDeck's own Proton (the built-in launcher or a `DroidDeck-Proton*` + folder) are moved. A game set to any other tool, such as GE-Proton, Bionic or Valve's Proton, in DroidDeck or + in Steam's Properties, runs on that tool and the launcher logs that it was chosen. +- **Tool.** The newest `compatibilitytools.d/DroidDeck-Proton*` whose layout is x86-64 + (`files/lib/wine/x86_64-unix`, no `files/bin-arm64`). +- **Runtime.** `PROTON_EAC_RUNTIME` or `PROTON_BATTLEYE_RUNTIME` when it already points at a folder with the + bridge libraries, otherwise the runtime's folder in any Steam library. +- **Launch.** `droiddeck-fex proton /proton `: FEX with the Steam Linux Runtime rootfs, + keeping the game's own `STEAM_COMPAT_DATA_PATH` prefix. + +Without the x86-64 tool or the runtime files the launch stays on ARM64 and the launcher logs why. +`DROIDDECK_ANTICHEAT=off` in the game's launch options keeps it on ARM64. Picking the x86-64 tool for a +game in Steam always runs it under FEX. + +## Why the x86-64 build needs its own Wine patches + +Android kernels use 39-bit user address spaces. Easy Anti-Cheat's launcher maps fixed memory at +`0x7001_0000_0000`, which FEX serves from emulated guest pages (`tools/fex/patches/0027`). Exclusive load and store pairs on that +memory are emulated as a compare-and-swap, so hosts without LSE atomics work too. `tools/fex/probes/guest-high-memory.c` +checks loads, stores, atomics, iovec system calls, `madvise` and code written through a high alias. The x86-64 Wine +in DroidDeck-Proton carries `ntdll-fixed-allocations-above-host-address-limit.patch` (fixed mappings above +the host limit go to the emulator) and `ntdll-keep-libc-in-native-syscall-dispatch-range.patch` (the +re-armed syscall user dispatch range keeps libc native). Stock x86-64 Proton stops after "Hack native +syscalls" on the same game. + +Easy Anti-Cheat's launcher attaches to the game with ptrace, stops it on a `rt_sigprocmask` call, runs its +own loader and restores the registers it saved at the stop. The call then returns `ENOSYS` without writing +the old mask, as it does on a desktop kernel. `ntdll-retry-blocking-signals-dropped-by-a-tracer.patch` +retries the block once when it fails, so Wine never restores an uninitialised mask that blocks `SIGSYS`. + +## The container's procfs + +Android mounts `/proc` with `hidepid=invisible,gid=3009`, and Easy Anti-Cheat refuses that mount with +launch error 261. Without root, user namespaces or PID namespaces, no procfs instance without those options +can be mounted. Every program in the container runs as the app's user and already sees all of the +container's processes, as it would in a PID-namespaced sandbox on a desktop, so FEX's emulated +`/proc//mounts` and `/proc//mountinfo` show the proc mount without `hidepid=`, `gid=` and +`subset=` (`tools/fex/patches/0029`). Only x86 programs under FEX see this view; every other line of the +table is the host's. Processes of other Android users stay hidden, as host processes do from a desktop +sandbox. diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index ced25e4c70..d4d67c7687 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -216,9 +216,10 @@ alone would then read as an installed client. NullReferenceException, internal CLR errors). A writable mapping or mprotect now write-protects the overlapping part of any alias that is already executable, so the first write faults and invalidates. `FEX_SMCCHECKS=full` was the only workaround; no setting is needed with the patch. - - `0007-cmake-install-code-without-depends`: CMake 4.5 rejects the `DEPENDS` argument FEX passes to - `install(CODE ...)` for the guest thunk libraries, so builds with host thunks stopped at configure. - The guest libraries are external projects in the default build, which `install` already follows. + - `0007-cmake-install-code-without-depends` (`Fixed-upstream: FEX-2612`): CMake 4.5 rejects the + `DEPENDS` argument FEX passes to `install(CODE ...)` for the guest thunk libraries, so builds with + host thunks stopped at configure. The guest libraries are external projects in the default build, + which `install` already follows. - `0008-signal-return-restores-syscall-state`: a guest `rt_sigreturn` is a system call, so FEX's syscall stub marks every static register as spilled (`InSyscallInfo = 0xFFFF`). When the handler left RIP alone, the return resumed the interrupted JIT code without passing the stub's reset, and diff --git a/tools/fex/build-in-arch.sh b/tools/fex/build-in-arch.sh index dccb24f882..9adc7e93e5 100755 --- a/tools/fex/build-in-arch.sh +++ b/tools/fex/build-in-arch.sh @@ -63,6 +63,11 @@ cmake -S fex-src -B fex-build -G Ninja \ ${FEX_EXTRA_CXXFLAGS:+-DCMAKE_CXX_FLAGS="$FEX_EXTRA_CXXFLAGS"} ninja -C fex-build DESTDIR="$WORK/out" ninja -C fex-build install +mkdir -p out/usr/local/share/fex-emu +for p in tools/fex/patches/*.patch; do + p=$(basename "$p" .patch) + echo "${p#*-}" +done > out/usr/local/share/fex-emu/.droiddeck-patches install -Dm755 /usr/bin/unsquashfs out/usr/local/bin/unsquashfs install -Dm644 "$(readlink -f /usr/lib/libxxhash.so.0)" out/usr/local/lib/libxxhash.so.0 bundled=$(cd out/usr/local/lib && ls -- *.so* | sort -u) diff --git a/tools/fex/patches/0007-cmake-install-code-without-depends.patch b/tools/fex/patches/0007-cmake-install-code-without-depends.patch index 6752b40280..83c0e1fb82 100644 --- a/tools/fex/patches/0007-cmake-install-code-without-depends.patch +++ b/tools/fex/patches/0007-cmake-install-code-without-depends.patch @@ -1,3 +1,4 @@ +Fixed-upstream: FEX-2612 diff --git a/CMakeLists.txt b/CMakeLists.txt index 8976588..3ae54f4 100644 --- a/CMakeLists.txt diff --git a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch index 6592a94550..327fe76a85 100644 --- a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -1,8 +1,8 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index b4c7b24..643185d 100644 +index 345f4d834..085ff00a2 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr +@@ -283,12 +283,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr auto Frame = Thread->CurrentFrame; if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { diff --git a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch index fbeec5ec96..6af2b7eb33 100644 --- a/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch +++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch @@ -1,5 +1,5 @@ diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h -index 02bb6bf..2e72492 100644 +index 02bb6bfef..2e724929f 100644 --- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h @@ -49,6 +49,11 @@ struct X86ContextBackup { @@ -27,10 +27,10 @@ index 02bb6bf..2e72492 100644 // Arm64 doesn't have a red zone diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index 643185d..53179c4 100644 +index 085ff00a2..5c79d1092 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -136,6 +136,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* +@@ -155,6 +155,31 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* #endif } @@ -62,7 +62,7 @@ index 643185d..53179c4 100644 ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore::Core::InternalThreadState* Thread, int Signal, void* ucontext) { // We can end up getting a signal at any point in our host state // Jump to a handler that saves all state so we can safely return -@@ -249,6 +274,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr +@@ -268,6 +293,19 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr } OldSP = *reinterpret_cast(GuestSP); @@ -82,7 +82,7 @@ index 643185d..53179c4 100644 } uintptr_t NewSP = OldSP; -@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -306,6 +344,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); auto Frame = Thread->CurrentFrame; @@ -90,7 +90,7 @@ index 643185d..53179c4 100644 // Ref count our faults // We use this to track if it is safe to clear cache -@@ -336,6 +375,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -355,6 +394,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP]; uint64_t NewGuestSP = OldGuestSP; @@ -99,7 +99,7 @@ index 643185d..53179c4 100644 // altstack is only used if the signal handler was setup with SA_ONSTACK if (GuestAction->sa_flags & SA_ONSTACK) { -@@ -345,6 +386,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -364,6 +405,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS // Then that means we are hitting recursive signals and we need to walk back the stack correctly uint64_t AltStackBase = reinterpret_cast(GuestStack->ss_sp); uint64_t AltStackEnd = AltStackBase + GuestStack->ss_size; @@ -108,7 +108,7 @@ index 643185d..53179c4 100644 if (OldGuestSP >= AltStackBase && OldGuestSP <= AltStackEnd) { // We are already in the alt stack, the rest of the code will handle adjusting this } else { -@@ -353,6 +396,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS +@@ -372,6 +415,40 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS } } @@ -149,7 +149,7 @@ index 643185d..53179c4 100644 // siginfo_t siginfo_t* HostSigInfo = reinterpret_cast(info); -@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre +@@ -510,6 +587,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre // Our ref counting doesn't matter anymore Thread->CurrentFrame->SignalHandlerRefCounter = 0; @@ -159,7 +159,7 @@ index 643185d..53179c4 100644 // Set the new PC if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext))) { diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h -index dfcd4b0..e4a86a9 100644 +index 0f45cf68d..408cddf71 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h @@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch index 626c726b59..cebe184aa2 100644 --- a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch +++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch @@ -1,7 +1,8 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +index 1946dc946..9f04358c5 100644 --- a/FEXCore/Source/Interface/Core/Core.cpp +++ b/FEXCore/Source/Interface/Core/Core.cpp -@@ -383,7 +383,11 @@ +@@ -383,7 +383,11 @@ bool ContextImpl::InitCore() { } void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) { @@ -15,9 +16,10 @@ diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/C void ContextImpl::ExecuteThread(FEXCore::Core::InternalThreadState* Thread) { diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index ae3ed51e4..c5e656d2c 100644 --- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp -@@ -305,6 +305,9 @@ +@@ -306,6 +306,9 @@ DEF_OP(Thunk) { PushDynamicRegs(TMP1); @@ -27,7 +29,7 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr)); InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash); -@@ -320,6 +323,8 @@ +@@ -321,6 +324,8 @@ DEF_OP(Thunk) { FillStaticRegs({ .NZCV = false, }); @@ -37,9 +39,10 @@ diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/In DEF_OP(ValidateCode) { diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 5c79d1092..e8e04b056 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -107,6 +107,10 @@ +@@ -126,6 +126,10 @@ void SignalDelegator::SpillSRA(FEXCore::Core::InternalThreadState* Thread, void* #ifdef ARCHITECTURE_arm64 Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext)); @@ -50,7 +53,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou for (size_t i = 0; i < Config.SRAGPRCount; i++) { const uint8_t SRAIdxMap = Config.SRAGPRMapping[i]; if (IgnoreMask & (1U << SRAIdxMap)) { -@@ -301,12 +305,10 @@ +@@ -320,12 +324,10 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr if (Context->UContextLocation) { auto Frame = Thread->CurrentFrame; @@ -67,7 +70,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou if (Is64BitMode) { RestoreFrame_x64(Thread, Context, Frame, ucontext); -@@ -361,6 +363,9 @@ +@@ -380,6 +382,9 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; Thread->CurrentFrame->InSyscallInfo = 0; } else { @@ -78,9 +81,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Sou // This is likely to cause issues but in some cases it isn't fatal // This can also happen if we have put a signal on hold, then we just reenabled the signal diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index fa6260954..e5d92e7c5 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp -@@ -131,7 +131,7 @@ +@@ -131,7 +131,7 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { // Restore previous `InSyscallInfo` structure. @@ -89,7 +93,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram // Hack! Go back to the top of the dispatcher top // This is only safe inside the JIT rather than anything outside of it -@@ -211,7 +211,7 @@ +@@ -211,7 +211,7 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre // If the guest modified the RIP then we need to take special precautions here if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { // Restore previous `InSyscallInfo` structure. @@ -98,7 +102,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram // Hack! Go back to the top of the dispatcher top // This is only safe inside the JIT rather than anything outside of it -@@ -290,7 +290,7 @@ +@@ -290,7 +290,7 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { // Restore previous `InSyscallInfo` structure. diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch index d97a75bee3..09c8398310 100644 --- a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch +++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch @@ -1,7 +1,8 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +index 9e6820bf6..43898e700 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h -@@ -263,6 +263,8 @@ +@@ -266,6 +266,8 @@ private: FEXCore::Core::CpuStateFrame* Frame, void* ucontext); void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext); @@ -11,9 +12,10 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Sourc ///< Setup the signal frame for x64. uint64_t SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index e5d92e7c5..38dc524f1 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp -@@ -122,6 +122,32 @@ +@@ -122,6 +122,32 @@ static void SetXStateInfo(T* xstate, bool is_avx_enabled) { } } @@ -46,7 +48,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { auto* guest_uctx = reinterpret_cast(Context->UContextLocation); -@@ -202,6 +228,27 @@ +@@ -202,6 +228,27 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa const auto modulo_i = (i + CurrentOffset) % 8; memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0])); } @@ -74,7 +76,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram } } -@@ -280,6 +327,17 @@ +@@ -280,6 +327,17 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre const auto modulo_i = (i + CurrentOffset) % 8; memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); } @@ -92,7 +94,7 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFram } } -@@ -359,6 +417,17 @@ +@@ -359,6 +417,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th const auto modulo_i = (i + CurrentOffset) % 8; memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); } diff --git a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch index 2192b9b0af..9bdad1cebd 100644 --- a/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch +++ b/tools/fex/patches/0017-fd-exec-keeps-argv0-and-path.patch @@ -1,8 +1,8 @@ diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp -index 2881ad9..abc84f3 100644 +index dd2c18303..e7e88f8f2 100644 --- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp -@@ -518,7 +518,7 @@ int main(int argc, char** argv, char** const envp) { +@@ -524,7 +524,7 @@ int main(int argc, char** argv, char** const envp) { FEXCore::Config::Set(FEXCore::Config::CONFIG_APP_CONFIG_NAME, Program.ProgramName); } else { // Anonymous program. @@ -12,7 +12,7 @@ index 2881ad9..abc84f3 100644 } } else { diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp -index a7a432b..4a77d87 100644 +index a7a432bbd..4a77d8716 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp @@ -441,7 +441,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname diff --git a/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch b/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch new file mode 100644 index 0000000000..b070802512 --- /dev/null +++ b/tools/fex/patches/0021-anticheat-ptrace-seccomp-and-proc-emulation.patch @@ -0,0 +1,5015 @@ +From: StonkGuy <68372320+StonkGuy@users.noreply.github.com> +Subject: [PATCH] x86-64 ptrace, seccomp and /proc emulation for anti-cheat launchers + +Author: StonkGuy (https://github.com/StonkGuy/FEX) +Source: https://github.com/StonkGuy/FEX branch eac-2611 (tag eac-2611.1) +Copyright (c) StonkGuy and FEX contributors, MIT licence + +diff --git a/FEXCore/Source/CMakeLists.txt b/FEXCore/Source/CMakeLists.txt +index 61385d2c3..b515a4a02 100644 +--- a/FEXCore/Source/CMakeLists.txt ++++ b/FEXCore/Source/CMakeLists.txt +@@ -4,6 +4,7 @@ set(FEXCORE_BASE_SRCS + Interface/Config/Config.cpp + Utils/Allocator.cpp + Utils/FileLoading.cpp ++ Utils/FaultSafeRead.cpp + Utils/FileUtils.cpp + Utils/ForcedAssert.cpp + Utils/LogManager.cpp +diff --git a/FEXCore/Source/Interface/Config/Config.json.in b/FEXCore/Source/Interface/Config/Config.json.in +index 6bd89a1e5..860bd4429 100644 +--- a/FEXCore/Source/Interface/Config/Config.json.in ++++ b/FEXCore/Source/Interface/Config/Config.json.in +@@ -604,6 +604,62 @@ + "\tfull: Validate code before every run (slow)" + ] + }, ++ "ProfileSampleHz": { ++ "Type": "uint32", ++ "Default": "0", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Samples the host PC of the main guest thread this many times per second into /dev/shm/fex--samples (in-process; no ptrace).", ++ "Use with LibraryJITNaming to attribute samples to guest libraries. 0 disables." ++ ] ++ }, ++ "ProfileSampleMinThreads": { ++ "Type": "uint32", ++ "Default": "100", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "ProfileSampleHz starts the sampler in the process that reaches this many guest threads (default 100: the application,", ++ "not the hundreds of helper processes of a Steam/Wine session). 1 samples every process from its first thread.", ++ "0: no sampler thread; each SIGPROF sent from outside stores a snapshot record of the receiving thread (ring in fex--snap)." ++ ] ++ }, ++ "ProfileSampleAllThreads": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "ProfileSampleHz samples every guest thread instead of only the main one." ++ ] ++ }, ++ "SignalTrace": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Records guest signal handling events (host signal arrival, masking decisions, delivery, rt_sigreturn, sigprocmask, kill/tgkill)", ++ "into a ring buffer in /dev/shm/fex--sigtrace. For diagnosing lost signals; decode with tools/harness/sigtrace.py." ++ ] ++ }, ++ "SignalMaskFix": { ++ "Type": "bool", ++ "Default": "true", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Run guest signal handlers with the signal mask Linux gives them (the interrupted mask plus sa_mask and the signal)", ++ "and restore the interrupted mask at rt_sigreturn. With false FEX blocks only sa_mask and the signal during the handler and keeps", ++ "a stale view of the mask afterwards, so a signal handler that restores its saved mask can unblock the signal it is running for." ++ ] ++ }, ++ "SMCHotPageFaults": { ++ "Type": "uint32", ++ "Default": "32", ++ "AffectsCodeGen": "true", ++ "Desc": [ ++ "Number of self-modifying-code write faults a guest page may take before FEX stops write-protecting it.", ++ "Instead the JIT verifies the code of every instruction it translates from such a page (like SMCChecks=full, but only for that page).", ++ "Only used with SMCChecks=mtrack. 0 disables the demotion (pages stay write-protected and keep faulting)." ++ ] ++ }, + "TSOEnabled": { + "Type": "bool", + "Default": "true", +@@ -691,6 +747,16 @@ + "Should only be used for applications that have issues with this set." + ] + }, ++ "EnableCPUIDFaulting": { ++ "Type": "bool", ++ "Default": "false", ++ "AffectsCodeGen": "false", ++ "Desc": [ ++ "Honour ARCH_SET_CPUID. When a guest thread calls arch_prctl(ARCH_SET_CPUID, 0), CPUID from that", ++ "thread raises a #GP (SIGSEGV, si_code SI_KERNEL) like Linux with a CPUID-faulting CPU, instead of", ++ "executing transparently. Off by default, so a guest that never asks for it is unaffected." ++ ] ++ }, + "StartupSleep": { + "Type": "uint32", + "Default": "0", +diff --git a/FEXCore/Source/Interface/Context/Context.h b/FEXCore/Source/Interface/Context/Context.h +index cce4d5113..24118405d 100644 +--- a/FEXCore/Source/Interface/Context/Context.h ++++ b/FEXCore/Source/Interface/Context/Context.h +@@ -224,8 +224,12 @@ public: + + void OnCodeBufferAllocated(const std::shared_ptr&) override; + void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) override; +- void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override; +- void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; ++ void InvalidateExecutableRangeCaches() override { ++ ExecutableRangeEpoch.fetch_add(1, std::memory_order_acq_rel); ++ } ++ bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) override; ++ std::atomic ExecutableRangeEpoch {}; ++ void InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) override; + FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() override { + return CodeInvalidationMutex; + } +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +index 9f04358c5..02d9a280a 100644 +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -31,6 +31,7 @@ $end_info$ + #include "Utils/Allocator.h" + #include "Utils/Allocator/HostAllocator.h" + #include "Utils/crc32.h" ++#include + #include + #include "Utils/variable_length_integer.h" + +@@ -201,8 +202,11 @@ uint32_t ContextImpl::ReconstructCompactedEFLAGS(FEXCore::Core::InternalThreadSt + case X86State::RFLAG_SF_RAW_LOC: + case X86State::RFLAG_OF_RAW_LOC: + case X86State::RFLAG_DF_RAW_LOC: ++ case X86State::RFLAG_NZCV_LOC: ++ case X86State::RFLAG_NZCV_1_LOC: ++ case X86State::RFLAG_NZCV_2_LOC: ++ case X86State::RFLAG_NZCV_3_LOC: + // Intentionally do nothing. +- // These contain multiple bits which can corrupt other members when compacted. + break; + default: EFLAGS |= uint32_t {Frame->State.flags[i]} << i; break; + } +@@ -645,11 +649,13 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue + Thread->OpDispatcher->_GuestOpcode(InstAddress - GuestRIP); + } + +- if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection) { ++ if (Config.SMCChecks == FEXCore::Config::CONFIG_SMC_FULL || Block.ForceFullSMCDetection || SyscallHandler->IsSMCHotPage(InstAddress)) { + auto ExistingCodePtr = reinterpret_cast(Block.Entry + BlockInstructionsLength); + auto InstAddressReg = Thread->OpDispatcher->_EntrypointOffset(GPRSize, InstAddress - GuestRIP); + +- auto Value = FEXCore::Utils::crc32(ExistingCodePtr, DecodedInfo->InstSize); ++ uint8_t InstBytes[16]; ++ const bool Readable = FEXCore::Utils::FaultSafeRead::Copy(InstBytes, ExistingCodePtr, DecodedInfo->InstSize); ++ auto Value = Readable ? FEXCore::Utils::crc32(InstBytes, DecodedInfo->InstSize) : ~0U; + auto CRC = WantsDiskCachePatching ? + Thread->OpDispatcher->_PatchableGuestCRC(IR::OpSize::i64Bit, Value, (int64_t)ExistingCodePtr, DecodedInfo->InstSize) : + Thread->OpDispatcher->Constant(Value); +@@ -730,6 +736,8 @@ ContextImpl::GenerateIR(FEXCore::Core::InternalThreadState* Thread, uint64_t Gue + Thread->OpDispatcher->InvalidOp(DecodedInfo); + } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::UNIMPLEMENTED_INST) { + Thread->OpDispatcher->UnimplementedOp(DecodedInfo); ++ } else if (Block.BlockStatus == Frontend::Decoder::DecodedBlockStatus::TOO_LONG_INST) { ++ Thread->OpDispatcher->PermissionRestrictedOp(DecodedInfo); + } else { + Thread->OpDispatcher->NoExecOrPartialOp(DecodedInfo); + } +@@ -897,9 +905,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + auto LoadedCode = Thread->CPUBackend->LoadCachedCode(Hit->HostCode); + if (LoadedCode.BlockBegin) { + for (auto& CodePage : Hit->GuestPages) { +- if (Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) { + SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } ++ Thread->LookupCache->AddBlockExecutableRange(Thread, Hit->EntryPointRIPs, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } + + LOGMAN_THROW_A_FMT(Hit->EntryPointRIPs.size() == Hit->EntryPointHostOffsets.size(), "Mismatched Disk Cache entrypoint pairs!"); +@@ -993,9 +1002,10 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + CodePages.reserve(BlockInfo->CodePages.size()); + CodePages.insert(CodePages.end(), BlockInfo->CodePages.begin(), BlockInfo->CodePages.end()); + for (auto CodePage : BlockInfo->CodePages) { +- if (Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ if (!Thread->LookupCache->HasBlockExecutableRange(CodePage)) { + SyscallHandler->MarkGuestExecutableRange(Thread, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } ++ Thread->LookupCache->AddBlockExecutableRange(Thread, BlockInfo->EntryPoints, CodePage, FEXCore::Utils::FEX_PAGE_SIZE); + } + } + +@@ -1006,10 +1016,13 @@ uintptr_t ContextImpl::CompileBlock(FEXCore::Core::CpuStateFrame* Frame, uint64_ + if (DebugData && DebugData->Relocations) { + Relocations = *DebugData->Relocations; + } +- std::span GuestCode = {reinterpret_cast(StartAddr), Length}; +- const Frontend::Decoder::DecodedBlockInformation* BlockInfo = +- NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr; +- DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo); ++ fextl::vector GuestCodeCopy(Length); ++ if (FEXCore::Utils::FaultSafeRead::Copy(GuestCodeCopy.data(), reinterpret_cast(StartAddr), Length)) { ++ std::span GuestCode = GuestCodeCopy; ++ const Frontend::Decoder::DecodedBlockInformation* BlockInfo = ++ NeedsAddGuestCodeRanges ? Thread->FrontendDecoder->GetDecodedBlockInfo() : nullptr; ++ DiskCache.Store(Thread, Region, GuestRIP, *DiskCacheGuestCodeKey, GuestCode, CompiledCode, Relocations, BlockInfo); ++ } + } + + if (CodeMapWriter && Region && Region->FileStartVA != 0) { +@@ -1055,31 +1068,38 @@ uintptr_t ContextImpl::CompileSingleStep(FEXCore::Core::CpuStateFrame* Frame, ui + return (uintptr_t)CodePtr; + } + +-void ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) { ++bool ContextImpl::InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) { + FEXCORE_PROFILE_SCOPED("InvalidateCodeBuffersCodeRange"); + + LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here"); + std::scoped_lock lk {CodeBufferListLock}; ++ bool Found = false; + auto it = CodeBufferList.begin(); + while (it != CodeBufferList.end()) { + if (auto Strong = it->lock()) { +- Strong->LookupCache->InvalidateRange(Start, Length); ++ Found |= Strong->LookupCache->InvalidateRange(Start, Length); + it++; + } else { + it = CodeBufferList.erase(it); + } + } ++ return Found; + } + +-void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { ++void ContextImpl::InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached) { + LOGMAN_THROW_A_FMT(CodeInvalidationMutex.try_lock() == false, "CodeInvalidationMutex needs to be unique_locked here"); + + // Ensures now-modified mappings aren't cached as being in their previous non-executable state. + // Accessing FrontendDecoder is safe as the thread's code invalidation mutex must be locked here. + Thread->FrontendDecoder->ResetExecutableRangeCache(); + ++ if (!CodeMayBeCached) { ++ return; ++ } ++ + if (Thread->LookupCache->InvalidateCacheRange(Start, Length)) { + FEXCORE_PROFILE_SCOPED("InvalidateCallRet"); ++ FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedCallRetFlushCount, 1); + + // This may cause access violations in the thread on Windows as zeroing is not atomic, this is handled by the frontend + Allocator::VirtualDontNeed(Thread->CallRetStackBase, FEXCore::Core::InternalThreadState::CALLRET_STACK_SIZE); +diff --git a/FEXCore/Source/Interface/Core/DiskCache.cpp b/FEXCore/Source/Interface/Core/DiskCache.cpp +index 3c78b22da..d903216c1 100644 +--- a/FEXCore/Source/Interface/Core/DiskCache.cpp ++++ b/FEXCore/Source/Interface/Core/DiskCache.cpp +@@ -11,6 +11,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -22,6 +23,23 @@ + #include + #include + ++namespace { ++template ++bool HashGuestMemory(UpdateFn&& Update, uint64_t Address, uint64_t Size) { ++ uint8_t Buffer[256]; ++ while (Size) { ++ const uint64_t Chunk = std::min(Size, sizeof(Buffer)); ++ if (!FEXCore::Utils::FaultSafeRead::Copy(Buffer, reinterpret_cast(Address), Chunk)) { ++ return false; ++ } ++ Update(Buffer, Chunk); ++ Address += Chunk; ++ Size -= Chunk; ++ } ++ return true; ++} ++} ++ + namespace FEXCore { + + namespace DiskCache { +@@ -576,12 +594,18 @@ namespace DiskCache { + } + uint64_t HashStart = SubBlock.Entry; + // skip over masked in-block data and data/etc gaps between blocks ++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) { ++ XXH3_64bits_update(&HashState, Bytes, Size); ++ }; + for (auto& DataMask : SubBlock.DataMasks) { +- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), DataMask.FieldAddress - HashStart); ++ if (!HashGuestMemory(Update, HashStart, DataMask.FieldAddress - HashStart)) { ++ return std::nullopt; ++ } + HashStart = DataMask.FieldAddress + DataMask.ValueSize; + } +- if (HashStart != SubBlock.Entry + SubBlock.Size) { +- XXH3_64bits_update(&HashState, reinterpret_cast(HashStart), SubBlock.Size - (HashStart - SubBlock.Entry)); ++ if (HashStart != SubBlock.Entry + SubBlock.Size && ++ !HashGuestMemory(Update, HashStart, SubBlock.Size - (HashStart - SubBlock.Entry))) { ++ return std::nullopt; + } + } + GuestCodeKey = XXH3_64bits_digest(&HashState); +@@ -704,8 +728,13 @@ namespace DiskCache { + if (FirstHash || LastFootprintHashed != CurrentFootprint) { + XXH3_state_t HashState; + XXH3_128bits_reset(&HashState); ++ auto Update = [&](const uint8_t* Bytes, uint64_t Size) { ++ XXH3_128bits_update(&HashState, Bytes, Size); ++ }; + for (uint32_t i = 0; i < Entry.GuestExtents.size(); i += 2) { +- XXH3_128bits_update(&HashState, reinterpret_cast(GuestRIP) + Entry.GuestExtents[i], Entry.GuestExtents[i + 1]); ++ if (!HashGuestMemory(Update, GuestRIP + Entry.GuestExtents[i], Entry.GuestExtents[i + 1])) { ++ return std::nullopt; ++ } + } + LiveGuestHash = XXH3_128bits_digest(&HashState); + LastFootprintHashed = CurrentFootprint; +diff --git a/FEXCore/Source/Interface/Core/DiskCache.h b/FEXCore/Source/Interface/Core/DiskCache.h +index 0bd3c21e4..0f1490cba 100644 +--- a/FEXCore/Source/Interface/Core/DiskCache.h ++++ b/FEXCore/Source/Interface/Core/DiskCache.h +@@ -249,7 +249,7 @@ namespace DiskCache { + // The current version of the diskcache. + // This must be changed any time codegen changes occur! + // Be aware of the impact of changing this frequently! +- static constexpr uint16_t FormatVersion = 52; ++ static constexpr uint16_t FormatVersion = 0x8000 | (1 << 8) | 52; + + static constexpr uint32_t LOOKUP_KEY_MAX_BUCKET_DEPTH = 500; + +diff --git a/FEXCore/Source/Interface/Core/Frontend.cpp b/FEXCore/Source/Interface/Core/Frontend.cpp +index 94e4ac522..18cda8889 100644 +--- a/FEXCore/Source/Interface/Core/Frontend.cpp ++++ b/FEXCore/Source/Interface/Core/Frontend.cpp +@@ -19,6 +19,7 @@ $end_info$ + #include + #include + #include ++#include + #include + #include + #include +@@ -108,6 +109,11 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) { + } + } + ++ if (const auto Epoch = CTX->ExecutableRangeEpoch.load(std::memory_order_acquire); Epoch != ExecutableRangeEpochSeen) { ++ ExecutableRangeEpochSeen = Epoch; ++ ResetExecutableRangeCache(); ++ } ++ + uint64_t RemainingSize = Size; + while (Address < ExecutableRangeBase || Address + RemainingSize > ExecutableRangeEnd) { + auto RangeInfo = CTX->SyscallHandler->QueryGuestExecutableRange(Thread, Address); +@@ -132,8 +138,13 @@ int32_t Decoder::CheckRangeExecutable(uint64_t Address, uint64_t Size) { + } + + uint8_t Decoder::ReadByte() { ++ if (InstructionSize >= MAX_INST_SIZE) { ++ HitInstructionLengthLimit = true; ++ return 0; ++ } ++ + std::optional Byte = PeekByte(0); +- if (!Byte || InstructionSize == MAX_INST_SIZE) { ++ if (!Byte) { + HitNonExecutableRange = true; + // Pretend we read 0, the main decode loop will see HitNonExecutableRange and rollback the instruction. + return 0; +@@ -146,8 +157,10 @@ uint8_t Decoder::ReadByte() { + + std::optional Decoder::PeekByte(uint8_t Offset) { + uint64_t ByteAddress = reinterpret_cast(InstStream.InstStream + InstructionSize + Offset); +- if (CheckRangeExecutable(ByteAddress, 1) == 1) { +- return InstStream.AdjustedInstStream[InstructionSize + Offset]; ++ uint8_t Byte; ++ if (CheckRangeExecutable(ByteAddress, 1) == 1 && ++ FEXCore::Utils::FaultSafeRead::Copy(&Byte, &InstStream.AdjustedInstStream[InstructionSize + Offset], 1)) { ++ return Byte; + } else { + return std::nullopt; + } +@@ -160,13 +173,24 @@ std::pair Decoder::ReadData(uint8_t Size) { + uint64_t Address = reinterpret_cast(InstStream.InstStream + InstructionSize); + LastFieldReadOffset = (uint8_t)InstructionSize; + LastFieldReadSize = Size; +- auto ReadableSize = CheckRangeExecutable(Address, Size); +- if (ReadableSize == Size) { +- std::memcpy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size); +- } else { +- HitNonExecutableRange = true; +- // See PeekByte, this specific case may cause some executable memory to read as 0 but it doesn't matter as the entire instruction will be rolled back anyway. ++ int32_t ReadableSize {}; ++ if (InstructionSize + Size > MAX_INST_SIZE) [[unlikely]] { ++ const int32_t FetchableSize = InstructionSize < MAX_INST_SIZE ? MAX_INST_SIZE - InstructionSize : 0; ++ ReadableSize = FetchableSize ? CheckRangeExecutable(Address, FetchableSize) : 0; ++ if (ReadableSize != FetchableSize) { ++ HitNonExecutableRange = true; ++ } ++ HitInstructionLengthLimit = true; + Res = 0; ++ } else { ++ ReadableSize = CheckRangeExecutable(Address, Size); ++ if (ReadableSize == Size && !FEXCore::Utils::FaultSafeRead::Copy(&Res, &InstStream.AdjustedInstStream[InstructionSize], Size)) { ++ ReadableSize = 0; ++ } ++ if (ReadableSize != Size) { ++ HitNonExecutableRange = true; ++ Res = 0; ++ } + } + + // Skip the number of decoded bytes regardless to get instruction size. +@@ -881,7 +905,7 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstructionImpl(uint64_t PC) { + + for (;;) { + if (InstructionSize >= MAX_INST_SIZE) { +- return DecodedBlockStatus::INVALID_INST; ++ return DecodedBlockStatus::TOO_LONG_INST; + } + uint8_t Op = ReadByte(); + switch (Op) { +@@ -1108,11 +1132,12 @@ void Decoder::DecodeREXIfValid(int8_t ExpectedOffset) { + Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) { + // Will be set if DecodeInstructionImpl tries to read non-executable memory + HitNonExecutableRange = false; ++ HitInstructionLengthLimit = false; + HitBadRelocation = false; + HitBreakpoint = ~0U; + auto ErrorDuringDecoding = DecodeInstructionImpl(PC); + +- if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitBadRelocation) [[unlikely]] { ++ if (ErrorDuringDecoding != DecodedBlockStatus::SUCCESS || HitNonExecutableRange || HitInstructionLengthLimit || HitBadRelocation) [[unlikely]] { + // Put an invalid instruction in the stream so the core can raise SIGILL if hit + // Error while decoding instruction. We don't know the table or instruction size + DecodeInst->TableInfo = nullptr; +@@ -1134,6 +1159,10 @@ Decoder::DecodedBlockStatus Decoder::DecodeInstruction(uint64_t PC) { + return DecodedBlockStatus::BAD_RELOCATION; + } + ++ if (HitInstructionLengthLimit) { ++ return DecodedBlockStatus::TOO_LONG_INST; ++ } ++ + return ErrorDuringDecoding; + } else if (!DecodeInst->TableInfo || (DecodeInst->TableInfo->Type == TYPE_INST && !DecodeInst->TableInfo->OpcodeDispatcher.OpDispatch)) { + // If there wasn't an error during decoding but we have no dispatcher for the instruction then claim invalid instruction. +@@ -1693,6 +1722,7 @@ void Decoder::DecodeLoop(const uint8_t* _InstStream, uint64_t GuestSizePause) { + BlockIt->BlockStatus == DecodedBlockStatus::BREAKPOINT_3 ? "Breakpoint" : + BlockIt->BlockStatus == DecodedBlockStatus::INVALID_INST ? "Invalid" : + BlockIt->BlockStatus == DecodedBlockStatus::NOEXEC_INST ? "NoExec" : ++ BlockIt->BlockStatus == DecodedBlockStatus::TOO_LONG_INST ? "TooLong" : + BlockIt->BlockStatus == DecodedBlockStatus::BAD_RELOCATION ? "BadRelocation" : + BlockIt->BlockStatus == DecodedBlockStatus::UNIMPLEMENTED_INST ? "Unimplemented" : + "PartialDecode", +diff --git a/FEXCore/Source/Interface/Core/Frontend.h b/FEXCore/Source/Interface/Core/Frontend.h +index ade14bc44..6d279b22c 100644 +--- a/FEXCore/Source/Interface/Core/Frontend.h ++++ b/FEXCore/Source/Interface/Core/Frontend.h +@@ -28,6 +28,7 @@ public: + INVALID_INST, + NOEXEC_INST, + PARTIAL_DECODE_INST, ++ TOO_LONG_INST, + BAD_RELOCATION, + UNIMPLEMENTED_INST, + BREAKPOINT_0, +@@ -93,6 +94,8 @@ public: + ExecutableRangeBase = ExecutableRangeEnd = 0; + } + ++ uint64_t ExecutableRangeEpochSeen {}; ++ + private: + // To pass any information from instruction prefixes + // down into the actual instruction handling machinery. +@@ -159,6 +162,7 @@ private: + uint64_t ExecutableRangeEnd {}; + bool ExecutableRangeWritable {}; + bool HitNonExecutableRange {}; ++ bool HitInstructionLengthLimit {}; + bool HitBadRelocation {}; + uint32_t HitBreakpoint {~0U}; + +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index c5e656d2c..7b9c15b61 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -195,6 +195,21 @@ DEF_OP(ExitFunction) { + ARMEmitter::ForwardLabel SkipFullLookup; + auto RipReg = GetReg(Op->NewRIP); + ++ if (Op->Hint == IR::BranchHint::CheckTF || CompilingWithTF) { ++ ARMEmitter::ForwardLabel TFUnset; ++ ldrb(TMP1, STATE_PTR(CpuStateFrame, State.flags[X86State::RFLAG_TF_RAW_LOC])); ++ (void)cbz(ARMEmitter::Size::i32Bit, TMP1, &TFUnset); ++ if (Op->Hint == IR::BranchHint::Return) { ++ add(ARMEmitter::Size::i64Bit, REG_CALLRET_SP, REG_CALLRET_SP, 0x10); ++ } else if (Op->Hint == IR::BranchHint::Call) { ++ stp(ARMEmitter::XReg::zr, ARMEmitter::XReg::zr, REG_CALLRET_SP, -0x10); ++ } ++ str(RipReg.X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); ++ ldr(TMP2, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.DispatcherLoopTop)); ++ br(TMP2); ++ (void)Bind(&TFUnset); ++ } ++ + if (Op->Hint == IR::BranchHint::Return) { + // First try to pop from the call-ret stack, otherwise follow the normal path (but ending in a ret) + ldp(TMP1, TMP2, REG_CALLRET_SP, 0x10); +diff --git a/FEXCore/Source/Interface/Core/JIT/JIT.cpp b/FEXCore/Source/Interface/Core/JIT/JIT.cpp +index fa9c8c880..777b4b51d 100644 +--- a/FEXCore/Source/Interface/Core/JIT/JIT.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/JIT.cpp +@@ -862,6 +862,7 @@ CPUBackend::CompiledCode Arm64JITCore::EmitJITCode(uint64_t Entry, uint64_t Size + this->DebugData = DebugData; + this->IR = IR; + RequiresFarARM64Jumps = false; ++ CompilingWithTF = CheckTF; + SSANodeMultiplier = 24; + + // Prepare restart via long jump in case branch encoding fails. +diff --git a/FEXCore/Source/Interface/Core/JIT/JITClass.h b/FEXCore/Source/Interface/Core/JIT/JITClass.h +index 55286855f..684ac9d9d 100644 +--- a/FEXCore/Source/Interface/Core/JIT/JITClass.h ++++ b/FEXCore/Source/Interface/Core/JIT/JITClass.h +@@ -86,6 +86,7 @@ private: + // In the rare case when those assumptions are broken, FEX needs to safely restart the JIT. + RestartOptions RestartControl {}; + bool RequiresFarARM64Jumps {}; ++ bool CompilingWithTF {}; + // Default to 6 instructions per SSA node. + uint32_t SSANodeMultiplier {24}; + +diff --git a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp +index d15ef9aee..bc1fb9c19 100644 +--- a/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/MiscOps.cpp +@@ -86,6 +86,34 @@ DEF_OP(Break) { + br(TMP1); + } + ++DEF_OP(BreakErrorCode) { ++ auto Op = IROp->C(); ++ ++ uxth(ARMEmitter::Size::i64Bit, TMP2, GetReg(Op->ErrorCode)); ++ ResetStack(); ++ ++ Core::CpuStateFrame::SynchronousFaultDataStruct State = { ++ .FaultToTopAndGeneratedException = 1, ++ .Signal = Op->Reason.Signal, ++ .TrapNo = Op->Reason.TrapNumber, ++ .si_code = Op->Reason.si_code, ++ .err_code = 0, ++ .FaultAddress = 0, ++ }; ++ static_assert(offsetof(Core::CpuStateFrame::SynchronousFaultDataStruct, err_code) == 4, "err_code is bits 32-47"); ++ ++ uint64_t Constant {}; ++ memcpy(&Constant, &State, sizeof(uint64_t)); ++ ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, static_cast(Constant)); ++ bfi(ARMEmitter::Size::i64Bit, TMP1, TMP2, 32, 16); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData)); ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, SynchronousFaultData) + 8); ++ ++ ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.GuestSignal_SynchronousFault)); ++ br(TMP1); ++} ++ + DEF_OP(GetRoundingMode) { + auto Dst = GetReg(Node); + mrs(Dst, ARMEmitter::SystemRegister::FPCR); +diff --git a/FEXCore/Source/Interface/Core/LookupCache.h b/FEXCore/Source/Interface/Core/LookupCache.h +index 391d48560..228d03969 100644 +--- a/FEXCore/Source/Interface/Core/LookupCache.h ++++ b/FEXCore/Source/Interface/Core/LookupCache.h +@@ -125,7 +125,7 @@ struct GuestToHostMap { + return BlockList.erase(Address) != 0; + } + +- void InvalidateRange(uint64_t Start, uint64_t Length) { ++ bool InvalidateRange(uint64_t Start, uint64_t Length) { + auto lk = AcquireWriteLock(); + + auto lower = CodePages.lower_bound(Start >> 12); +@@ -136,7 +136,9 @@ struct GuestToHostMap { + Erase(Entry, lk); + } + } ++ const bool Found = lower != upper; + CodePages.erase(lower, upper); ++ return Found; + } + + void AddBlockLink(uint64_t GuestDestination, FEXCore::Context::ExitFunctionLinkData* HostLink, +@@ -144,6 +146,11 @@ struct GuestToHostMap { + BlockLinks->insert({{GuestDestination, HostLink}, delinker}); + } + ++ bool HasBlockExecutableRange(uint64_t Page, const LookupCacheReadLockToken&) const { ++ auto it = CodePages.find(Page >> 12); ++ return it != CodePages.end() && !it->second.empty(); ++ } ++ + bool AddBlockExecutableRange(const std::ranges::input_range auto& Addresses, uint64_t Start, uint64_t Length, const LookupCacheWriteLockToken&) { + bool rv = false; + +@@ -282,6 +289,11 @@ public: + + GuestToHostMap* Shared = nullptr; + ++ bool HasBlockExecutableRange(uint64_t Page) { ++ auto lk = Shared->AcquireReadLock(); ++ return Shared->HasBlockExecutableRange(Page, lk); ++ } ++ + // Appends a list of Block {Address} to CodePages [Start, Start + Length) + // Returns true if new pages are marked as containing code + bool AddBlockExecutableRange(FEXCore::Core::InternalThreadState* Thread, auto& Addresses, uint64_t Start, uint64_t Length) { +diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +index 356fc3bb1..27491cea4 100644 +--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp ++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp +@@ -138,6 +138,31 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) { + + const auto GPRSize = GetGPROpSize(); + ++ { ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ ++ auto CondJump_ = CondJump(GetRFLAG(FEXCore::X86State::RFLAG_NT_LOC), CondClass::EQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ ++ _StoreContextGPR(GPRSize, GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip)); ++ ++ IR::BreakDefinition Reason {}; ++ Reason.ErrorRegister = 0; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ Break(Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ } ++ + Ref SP = _RMWHandle(LoadGPRRegister(X86State::REG_RSP)); + + // RIP (64/32/16 bits) +@@ -164,7 +189,7 @@ void OpDispatchBuilder::IRETOp(OpcodeArgs) { + StoreGPRRegister(X86State::REG_RSP, SP); + } + +- ExitFunction(NewRIP); ++ ExitFunction(NewRIP, BranchHint::CheckTF); + BlockSetRIP = true; + } + +@@ -1230,6 +1255,36 @@ void OpDispatchBuilder::FLAGControlOp(OpcodeArgs) { + } + + ++void OpDispatchBuilder::MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset) { ++ Ref Index = _Bfe(OpSize::i32Bit, 13, 3, Selector); ++ Ref TI = _Bfe(OpSize::i32Bit, 1, 2, Selector); ++ Ref Allowed = _And(OpSize::i32Bit, _Lshr(OpSize::i32Bit, Constant(0x8071), Index), Constant(1)); ++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::ULT, Index, Constant(16), Allowed, Constant(0)); ++ Allowed = _Select(OpSize::i32Bit, OpSize::i32Bit, CondClass::EQ, TI, Constant(0), Allowed, Constant(0)); ++ ++ auto FaultBlock = CreateNewCodeBlockAfter(GetCurrentBlock()); ++ auto ContinueBlock = CreateNewCodeBlockAfter(FaultBlock); ++ auto CondJump_ = CondJump(Allowed, CondClass::NEQ); ++ SetTrueJumpTarget(CondJump_, ContinueBlock); ++ SetFalseJumpTarget(CondJump_, FaultBlock); ++ ++ SetCurrentCodeBlock(FaultBlock); ++ StartNewBlock(); ++ Ref FaultSelector = LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags); ++ _StoreContextGPR(GetGPROpSize(), GetRelocatedPC(Op, -Op->InstSize), offsetof(FEXCore::Core::CPUState, rip)); ++ IR::BreakDefinition Reason {}; ++ Reason.Signal = Core::FAULT_SIGSEGV; ++ Reason.TrapNumber = X86State::X86_TRAPNO_GP; ++ Reason.si_code = 0x80; ++ BlockSetRIP = true; ++ BreakErrorCode(_And(OpSize::i32Bit, FaultSelector, Constant(0xfffc)), Reason); ++ ++ SetCurrentCodeBlock(ContinueBlock); ++ StartNewBlock(); ++ _StoreContextGPR(OpSize::i16Bit, LoadSourceGPR_WithOpSize(Op, Op->Src[0], OpSize::i16Bit, Op->Flags), IndexOffset); ++ _StoreContextGPR(OpSize::i64Bit, Constant(0), BaseOffset); ++} ++ + void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + // In x86-64 mode the accesses to the segment registers end up being constant zero moves + // Aside from FS/GS +@@ -1243,7 +1298,6 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + // selected for the registers + // This statement is actually untrue, the instructions will /actually/ load 16bits in to the selector portion of the register! + // Tested on a Zen+ CPU, the selector is the portion that is modified! +- // We don't currently support FS/GS selector modifying, so this needs to be asserted out + // The loads here also load the selector, NOT the base + + if (ToSeg) { +@@ -1283,8 +1337,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, gs_idx)); + UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX); + } else { +- LogMan::Msg::EFmt("We don't support modifying GS selector in 64bit mode!"); +- DecodeFailure = true; ++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, gs_idx), offsetof(FEXCore::Core::CPUState, gs_cached)); + } + break; + case FEXCore::X86State::REG_RSP: // FS +@@ -1293,8 +1346,7 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + _StoreContextGPR(OpSize::i16Bit, Src, offsetof(FEXCore::Core::CPUState, fs_idx)); + UpdatePrefixFromSegment(Src, FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX); + } else { +- LogMan::Msg::EFmt("We don't support modifying FS selector in 64bit mode!"); +- DecodeFailure = true; ++ MOVSegFSGS64(Op, Src, offsetof(FEXCore::Core::CPUState, fs_idx), offsetof(FEXCore::Core::CPUState, fs_cached)); + } + break; + default: UnimplementedOp(Op); return; +@@ -1321,19 +1373,11 @@ void OpDispatchBuilder::MOVSegOp(OpcodeArgs, bool ToSeg) { + break; + case FEXCore::X86State::REG_RBP: // GS + case FEXCore::X86State::REG_R13: // GS +- if (Is64BitMode) { +- Segment = Constant(0); +- } else { +- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx)); +- } ++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, gs_idx)); + break; + case FEXCore::X86State::REG_RSP: // FS + case FEXCore::X86State::REG_R12: // FS +- if (Is64BitMode) { +- Segment = Constant(0); +- } else { +- Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx)); +- } ++ Segment = _LoadContextGPR(OpSize::i16Bit, offsetof(FEXCore::Core::CPUState, fs_idx)); + break; + default: UnimplementedOp(Op); return; + } +diff --git a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +index d3e523d9b..601db6009 100644 +--- a/FEXCore/Source/Interface/Core/OpcodeDispatcher.h ++++ b/FEXCore/Source/Interface/Core/OpcodeDispatcher.h +@@ -216,6 +216,10 @@ public: + } + return _Break(Reason, RelocatedPC); + } ++ IRPair BreakErrorCode(Ref ErrorCode, BreakDefinition Reason) { ++ FlushRegisterCache(); ++ return _BreakErrorCode(ErrorCode, Reason); ++ } + IRPair Thunk(Ref ArgPtr, SHA256Sum ThunkNameHash) { + FlushRegisterCache(); + return _Thunk(ArgPtr, ThunkNameHash); +@@ -417,6 +421,7 @@ public: + void XCHGRAXOp(OpcodeArgs); + void SAHFOp(OpcodeArgs); + void LAHFOp(OpcodeArgs); ++ void MOVSegFSGS64(OpcodeArgs, Ref Selector, uint32_t IndexOffset, uint32_t BaseOffset); + void MOVSegOp(OpcodeArgs, bool ToSeg); + void FLAGControlOp(OpcodeArgs); + void MOVOffsetOp(OpcodeArgs); +@@ -1974,8 +1979,8 @@ private: + // An exception should still be raised after an instruction that unsets TF, leave the unblocked bit set but unset + // the TF bit to cause such behaviour. The handling code at the start of the next block will then unset the + // unblocked bit before raising the exception. +- auto NewPackedTF = +- _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), Constant(1)); ++ auto NewPackedTF = _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, Value, Constant(0), _And(OpSize::i32Bit, PackedTF, Constant(~1)), ++ _Select(OpSize::i64Bit, OpSize::i64Bit, CondClass::EQ, PackedTF, Constant(3), Constant(3), Constant(1))); + _StoreContextGPR(OpSize::i8Bit, NewPackedTF, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset)); + } else { + _StoreContextGPR(OpSize::i8Bit, Value, ARRAY_OFFSETOF(FEXCore::Core::CPUState, flags, BitOffset)); +diff --git a/FEXCore/Source/Interface/IR/IR.json b/FEXCore/Source/Interface/IR/IR.json +index 4b79cf35c..0c01f580d 100644 +--- a/FEXCore/Source/Interface/IR/IR.json ++++ b/FEXCore/Source/Interface/IR/IR.json +@@ -324,6 +324,12 @@ + "Break BreakDefinition:$Reason, GPR:$FaultAddress": { + "HasSideEffects": true + }, ++ "BreakErrorCode GPR:$ErrorCode, BreakDefinition:$Reason": { ++ "HasSideEffects": true, ++ "Desc": ["Break whose fault error code is the low 16 bits of $ErrorCode, known only at run time", ++ "(a #GP with a selector as its error code); Reason.ErrorRegister is not used" ++ ] ++ }, + "CallbackReturn": { + "HasSideEffects": true + }, +diff --git a/FEXCore/Source/Interface/IR/IREmitter.cpp b/FEXCore/Source/Interface/IR/IREmitter.cpp +index 6c8ed5d11..d8fd1431e 100644 +--- a/FEXCore/Source/Interface/IR/IREmitter.cpp ++++ b/FEXCore/Source/Interface/IR/IREmitter.cpp +@@ -23,7 +23,8 @@ static bool IsFragmentExit(FEXCore::IR::IROps Op) { + case OP_SYSCALL: + case OP_CPUID: + case OP_EXITFUNCTION: +- case OP_BREAK: return true; ++ case OP_BREAK: ++ case OP_BREAKERRORCODE: return true; + default: return false; + } + } +diff --git a/FEXCore/Source/Utils/FaultSafeRead.cpp b/FEXCore/Source/Utils/FaultSafeRead.cpp +new file mode 100644 +index 000000000..aaa7a80cf +--- /dev/null ++++ b/FEXCore/Source/Utils/FaultSafeRead.cpp +@@ -0,0 +1,46 @@ ++// SPDX-License-Identifier: MIT ++#include ++ ++#include ++ ++namespace FEXCore::Utils::FaultSafeRead { ++#if defined(ARCHITECTURE_arm64) && !defined(_WIN32) ++__attribute__((naked)) static size_t CopyImpl(void* Dest, const void* Src, size_t Size) { ++ __asm volatile(R"( ++ // Early exit if a copy of size zero. ++ cbz x2, 2f; ++ ++ 1: ++ .globl FEXCore_FaultSafeRead_FaultInst ++ FEXCore_FaultSafeRead_FaultInst: ++ ldrb w3, [x1], 1; // <- This line can fault. ++ strb w3, [x0], 1; ++ sub x2, x2, 1; ++ cbnz x2, 1b; ++2: ++ mov x0, 0; ++ ret; ++ )" :: ++ : "memory"); ++} ++ ++extern "C" uint64_t FEXCore_FaultSafeRead_FaultInst; ++ ++bool Copy(void* Dest, const void* Src, size_t Size) { ++ return CopyImpl(Dest, Src, Size) == 0; ++} ++ ++bool IsFaultLocation(uint64_t PC) { ++ return reinterpret_cast(PC) == &FEXCore_FaultSafeRead_FaultInst; ++} ++#else ++bool Copy(void* Dest, const void* Src, size_t Size) { ++ memcpy(Dest, Src, Size); ++ return true; ++} ++ ++bool IsFaultLocation(uint64_t PC) { ++ return false; ++} ++#endif ++} +diff --git a/FEXCore/include/FEXCore/Core/Context.h b/FEXCore/include/FEXCore/Core/Context.h +index 7e1d30770..854c5ce1c 100644 +--- a/FEXCore/include/FEXCore/Core/Context.h ++++ b/FEXCore/include/FEXCore/Core/Context.h +@@ -141,9 +141,11 @@ public: + virtual void FlushAndCloseCodeMap() = 0; + + FEX_DEFAULT_VISIBILITY virtual void ClearCodeCache(FEXCore::Core::InternalThreadState* Thread, bool NewCodeBuffer = true) = 0; +- FEX_DEFAULT_VISIBILITY virtual void InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0; ++ FEX_DEFAULT_VISIBILITY virtual void InvalidateExecutableRangeCaches() = 0; ++ ++ FEX_DEFAULT_VISIBILITY virtual bool InvalidateCodeBuffersCodeRange(uint64_t Start, uint64_t Length) = 0; + FEX_DEFAULT_VISIBILITY virtual void +- InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) = 0; ++ InvalidateThreadCachedCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length, bool CodeMayBeCached = true) = 0; + FEX_DEFAULT_VISIBILITY virtual FEXCore::Utils::WritePriorityMutex::Mutex& GetCodeInvalidationMutex() = 0; + + FEX_DEFAULT_VISIBILITY virtual void +diff --git a/FEXCore/include/FEXCore/Core/CoreState.h b/FEXCore/include/FEXCore/Core/CoreState.h +index 7c02605f5..98ba8e150 100644 +--- a/FEXCore/include/FEXCore/Core/CoreState.h ++++ b/FEXCore/include/FEXCore/Core/CoreState.h +@@ -282,6 +282,11 @@ struct alignas(64) CPUState { + + // TODO: This should be moved to the frontend. + constexpr static uint32_t DEFAULT_USER_CS = 6; ++ constexpr static uint32_t DEFAULT_USER_DS = 5; ++ ++ constexpr static uint32_t DEFAULT_USER_CS_SEL = (DEFAULT_USER_CS << 3) | 3; ++ constexpr static uint32_t DEFAULT_USER_DS_SEL = (DEFAULT_USER_DS << 3) | 3; ++ constexpr static uint32_t DEFAULT_USER32_CS_SEL = 0x23; + + // Follows encoding of the TI bit in segment selector encoding. + constexpr static uint32_t SEGMENT_ARRAY_INDEX_GDT = 0; +diff --git a/FEXCore/include/FEXCore/HLE/SyscallHandler.h b/FEXCore/include/FEXCore/HLE/SyscallHandler.h +index 0ba0218e3..89e36d52e 100644 +--- a/FEXCore/include/FEXCore/HLE/SyscallHandler.h ++++ b/FEXCore/include/FEXCore/HLE/SyscallHandler.h +@@ -33,6 +33,10 @@ public: + virtual void HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) = 0; + + virtual void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {} ++ ++ virtual bool IsSMCHotPage(uint64_t Address) { ++ return false; ++ } + virtual void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) {} + virtual void MarkOvercommitRange(uint64_t Start, uint64_t Length) {} + virtual void UnmarkOvercommitRange(uint64_t Start, uint64_t Length) {} +diff --git a/FEXCore/include/FEXCore/Utils/FaultSafeRead.h b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h +new file mode 100644 +index 000000000..1fc7213b5 +--- /dev/null ++++ b/FEXCore/include/FEXCore/Utils/FaultSafeRead.h +@@ -0,0 +1,12 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++#include ++ ++#include ++#include ++ ++namespace FEXCore::Utils::FaultSafeRead { ++FEX_DEFAULT_VISIBILITY bool Copy(void* Dest, const void* Src, size_t Size); ++ ++FEX_DEFAULT_VISIBILITY bool IsFaultLocation(uint64_t PC); ++} +diff --git a/FEXCore/include/FEXCore/Utils/SHMStats.h b/FEXCore/include/FEXCore/Utils/SHMStats.h +index c5844fe10..d646c6a2f 100644 +--- a/FEXCore/include/FEXCore/Utils/SHMStats.h ++++ b/FEXCore/include/FEXCore/Utils/SHMStats.h +@@ -74,7 +74,10 @@ struct ThreadStats { + uint64_t AccumulatedDiskCacheHitCount; + uint64_t AccumulatedDiskCacheMissCount; + uint64_t AccumulatedDiskCacheLookupTime; +- uint64_t Padding; ++ ++ uint64_t AccumulatedInvalidationCount; ++ uint64_t AccumulatedInvalidationTime; ++ uint64_t AccumulatedCallRetFlushCount; + }; + + // Ensure 16-byte alignment to take advantage of ARM single-copy atomicity. +diff --git a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +index e7e88f8f2..26b8186c8 100644 +--- a/Source/Tools/FEXInterpreter/FEXInterpreter.cpp ++++ b/Source/Tools/FEXInterpreter/FEXInterpreter.cpp +@@ -602,8 +602,7 @@ int main(int argc, char** argv, char** const envp) { + // Create a thread without a RIP or stack pointer setup initially. + auto ParentThread = SyscallHandler->TM.CreateThread(); + SyscallHandler->TM.TrackThread(ParentThread); +- SignalDelegation->RegisterTLSState(ParentThread); +- ThunkHandler->RegisterTLSState(ParentThread); ++ SyscallHandler->RegisterTLSState(ParentThread); + + SyscallHandler->DeserializeSeccompFD(ParentThread, FEXSeccompFD); + +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 2e724929f..62135b824 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -20,6 +20,7 @@ namespace FEX::ArchHelpers::Context { + + enum ContextFlags : uint32_t { + CONTEXT_FLAG_INJIT = (1U << 0), ++ CONTEXT_FLAG_SYSCALLINFO_CLEARED = (1U << 1), + }; + + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED +@@ -40,7 +41,11 @@ struct X86ContextBackup { + FEXCore::x86_64::_libc_fpstate FPRState; + uint64_t sa_mask; + uint16_t InSyscallInfo; ++ uint16_t ClearedSyscallInfo; + bool FaultToTopAndGeneratedException; ++ uint64_t GuestSignalMask; ++ uint64_t SeccompTrapRIP; ++ uint64_t SavedJITStackSP; + + // Guest state + int Signal; +@@ -72,7 +77,11 @@ struct ArmContextBackup { + __uint128_t FPRs[32]; + uint64_t sa_mask; + uint16_t InSyscallInfo; ++ uint16_t ClearedSyscallInfo; + bool FaultToTopAndGeneratedException; ++ uint64_t GuestSignalMask; ++ uint64_t SeccompTrapRIP; ++ uint64_t SavedJITStackSP; + + // Guest state + int Signal; +@@ -92,6 +101,11 @@ struct ArmContextBackup { + static constexpr int RedZoneSize = 0; + }; + ++template ++static inline uint16_t SavedSyscallInfo(const Backup* Context) { ++ return (Context->Flags & CONTEXT_FLAG_SYSCALLINFO_CLEARED) ? Context->ClearedSyscallInfo : Context->InSyscallInfo; ++} ++ + static inline ucontext_t* GetUContext(void* ucontext) { + ucontext_t* _context = (ucontext_t*)ucontext; + return _context; +diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt +index 715a8f132..3f02104ea 100644 +--- a/Source/Tools/LinuxEmulation/CMakeLists.txt ++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt +@@ -10,6 +10,9 @@ add_library(LinuxEmulation STATIC + LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp + LinuxSyscalls/FaultSafeUserMemAccess.cpp + LinuxSyscalls/FileManagement.cpp ++ LinuxSyscalls/PtraceEmu.cpp ++ LinuxSyscalls/SamplingProfiler.cpp ++ LinuxSyscalls/SignalTrace.cpp + LinuxSyscalls/LinuxAllocator.cpp + LinuxSyscalls/Seccomp/SeccompEmulator.cpp + LinuxSyscalls/Seccomp/BPFEmitter.cpp +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 2095d4dc5..eb12945e4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -10,6 +10,7 @@ $end_info$ + + #include "Common/CPUInfo.h" + #include "Common/FDUtils.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" + +@@ -24,6 +25,8 @@ $end_info$ + + #include + ++#include ++#include + #include + #include + #include +@@ -593,6 +596,10 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + FDReadCreators[procAuxv] = &EmulatedFDManager::ProcAuxv; + FDReadCreators["/proc/self/auxv"] = &EmulatedFDManager::ProcAuxv; + ++ fextl::string procStatus = fextl::fmt::format("/proc/{}/status", getpid()); ++ FDReadCreators[procStatus] = &EmulatedFDManager::ProcStatus; ++ FDReadCreators["/proc/self/status"] = &EmulatedFDManager::ProcStatus; ++ + if (ThreadsConfig > 1) { + cpus_online = fextl::fmt::format("0-{}", ThreadsConfig - 1); + } else { +@@ -602,6 +609,20 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + + EmulatedFDManager::~EmulatedFDManager() {} + ++static bool IsProcMapsPath(const char* Path) { ++ if (strncmp(Path, "/proc/", 6) != 0) { ++ return false; ++ } ++ const char* P = Path + 6; ++ if (!isdigit(*P)) { ++ return strcmp(P, "self/maps") == 0; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ return strcmp(P, "/maps") == 0; ++} ++ + int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) { + auto Creator = FDReadCreators.end(); + if (pathname) { +@@ -609,12 +630,148 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + } + + if (Creator == FDReadCreators.end()) { ++ if (pathname && IsProcMapsPath(pathname)) { ++ return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode); ++ } + return -1; + } + + return Creator->second(CTX, AT_FDCWD, pathname, flags, mode); + } + ++int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC); ++ if (HostFD < 0) { ++ return -1; ++ } ++ fextl::string In; ++ char Buf[65536]; ++ for (;;) { ++ const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf)); ++ if (Len > 0) { ++ In.append(Buf, Len); ++ } else if (Len == 0) { ++ break; ++ } else if (errno != EINTR) { ++ LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno); ++ ::close(HostFD); ++ return -1; ++ } ++ } ++ ::close(HostFD); ++ ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; ++ fextl::string Out; ++ Out.reserve(In.size()); ++ size_t Pos = 0; ++ while (Pos < In.size()) { ++ size_t Eol = In.find('\n', Pos); ++ const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1; ++ const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16); ++ if (Start < X86_64TaskSizeMax) { ++ Out.append(In, Pos, End - Pos); ++ } ++ Pos = End; ++ } ++ ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Out.size();) { ++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ ++int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ char Buf[8192]; ++ ssize_t Len = 0; ++ { ++ int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ if (HostFD >= 0) { ++ Len = ::read(HostFD, Buf, sizeof(Buf) - 1); ++ ::close(HostFD); ++ } ++ } ++ if (Len < 0) { ++ Len = 0; ++ } ++ Buf[Len] = '\0'; ++ ++ uint32_t SeccompMode = SECCOMP_MODE_DISABLED; ++ if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) { ++ SeccompMode = Thread->SeccompMode; ++ } ++ ++ fextl::string Out; ++ Out.reserve(Len + 64); ++ const char* Cursor = Buf; ++ while (*Cursor) { ++ const char* Eol = strchr(Cursor, '\n'); ++ const size_t LineLen = Eol ? static_cast(Eol - Cursor) + 1 : strlen(Cursor); ++ if (strncmp(Cursor, "Seccomp:", 8) == 0) { ++ Out += fextl::fmt::format("Seccomp:\t{}\n", SeccompMode); ++ } else if (strncmp(Cursor, "TracerPid:", 10) == 0) { ++ if (FEX::HLE::PtraceEmu::IsAttached()) { ++ Out.append(Cursor, LineLen); ++ } else { ++ Out += "TracerPid:\t0\n"; ++ } ++ } else { ++ Out.append(Cursor, LineLen); ++ if (!Eol) { ++ break; ++ } ++ } ++ if (!Eol) { ++ break; ++ } ++ Cursor = Eol + 1; ++ } ++ ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Out.size();) { ++ const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ + int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { + const auto [auxvBase, auxvSize] = FEX::HLE::_SyscallHandler->GetCodeLoader()->GetAuxv(); + if (auxvBase == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +index 854232341..b98ef4bda 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +@@ -34,6 +34,8 @@ private: + fextl::unordered_map FDReadCreators; + + static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + const uint32_t ThreadsConfig; + }; + } // namespace FEX::EmulatedFile +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp +index 6471e6483..7a7e068e2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FaultSafeUserMemAccess.cpp +@@ -1,6 +1,8 @@ + // SPDX-License-Identifier: MIT + #include "LinuxSyscalls/Syscalls.h" + ++#include ++ + namespace FEX::HLE::FaultSafeUserMemAccess { + #ifdef ARCHITECTURE_arm64 + __attribute__((naked)) size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { +@@ -41,6 +43,26 @@ __attribute__((naked)) size_t CopyToUser(void* Dest, const void* Src, size_t Siz + : "memory"); + } + ++__attribute__((naked)) static size_t StringReadableImpl(const char* Src) { ++ __asm volatile(R"( ++ 1: ++ .globl StringReadable_FaultInst ++ StringReadable_FaultInst: ++ ldrb w1, [x0], 1; // <- This line can fault. ++ cbnz w1, 1b; ++ mov x0, 0; ++ ret; ++ )" :: ++ : "memory"); ++} ++ ++bool IsStringReadable(const char* Src) { ++ return Src == nullptr || StringReadableImpl(Src) == 0; ++} ++ ++extern "C" uint64_t StringReadable_FaultInst; ++void* const StringReadable_FaultLocation = &StringReadable_FaultInst; ++ + extern "C" uint64_t CopyFromUser_FaultInst; + void* const CopyFromUser_FaultLocation = &CopyFromUser_FaultInst; + +@@ -157,6 +179,8 @@ bool IsFaultLocation(uint64_t PC) { + bool IsMemcpyFault = false; + IsMemcpyFault |= reinterpret_cast(PC) == CopyToUser_FaultLocation; + IsMemcpyFault |= reinterpret_cast(PC) == CopyFromUser_FaultLocation; ++ IsMemcpyFault |= reinterpret_cast(PC) == StringReadable_FaultLocation; ++ IsMemcpyFault |= FEXCore::Utils::FaultSafeRead::IsFaultLocation(PC); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + IsMemcpyFault |= reinterpret_cast(PC) == UserReadable_FaultLocation; + IsMemcpyFault |= reinterpret_cast(PC) == UserWritable_FaultLocation; +@@ -176,6 +200,10 @@ size_t CopyToUser(void* Dest, const void* Src, size_t Size) { + return Size; + } + ++bool IsStringReadable(const char* Src) { ++ return true; ++} ++ + bool IsFaultLocation(uint64_t PC) { + return false; + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +index 2210e4508..62b6a2d27 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +@@ -13,6 +13,7 @@ $end_info$ + #include "FEXCore/Config/Config.h" + #include "LinuxSyscalls/FileManagement.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + +@@ -954,6 +955,27 @@ uint64_t FileManager::FAccessat2(int dirfd, const char* pathname, int mode, int + return ::syscall(SYSCALL_DEF(faccessat2), dirfd, SelfPath, mode, flags); + } + ++static std::optional ReadlinkTraceeExe(const char* Path, char* Buf, size_t BufSize) { ++ if (!Path || strncmp(Path, "/proc/", 6) != 0) { ++ return std::nullopt; ++ } ++ char* End = nullptr; ++ const long Pid = strtol(Path + 6, &End, 10); ++ if (End == Path + 6 || strcmp(End, "/exe") != 0) { ++ return std::nullopt; ++ } ++ const auto Exe = PtraceEmu::TraceeExePath(static_cast(Pid)); ++ if (!Exe) { ++ return std::nullopt; ++ } ++ const size_t Len = std::min(BufSize, Exe->size()); ++ if (FaultSafeUserMemAccess::CopyToUser(Buf, Exe->data(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++} ++ + uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) { + // calculate the non-self link to exe + // Some executables do getpid, stat("/proc/$pid/exe") +@@ -962,8 +984,16 @@ uint64_t FileManager::Readlink(const char* pathname, char* buf, size_t bufsiz) { + + if (strcmp(pathname, "/proc/self/exe") == 0 || strcmp(pathname, "/proc/thread-self/exe") == 0 || strcmp(pathname, PidSelfPath) == 0) { + const auto& App = Filename(); +- strncpy(buf, App.c_str(), bufsiz); +- return std::min(bufsiz, App.size()); ++ const size_t Len = std::min(bufsiz, App.size()); ++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++ } ++ ++ if (auto Traced = ReadlinkTraceeExe(pathname, buf, bufsiz)) { ++ return *Traced; + } + + FDPathTmpData TmpFilename; +@@ -1039,8 +1069,18 @@ uint64_t FileManager::Readlinkat(int dirfd, const char* pathname, char* buf, siz + + if (Path == "/proc/self/exe" || Path == "/proc/thread-self/exe" || Path == PidSelfPath) { + const auto& App = Filename(); +- strncpy(buf, App.c_str(), bufsiz); +- return std::min(bufsiz, App.size()); ++ const size_t Len = std::min(bufsiz, App.size()); ++ if (FaultSafeUserMemAccess::CopyToUser(buf, App.c_str(), Len)) { ++ errno = EFAULT; ++ return -1; ++ } ++ return Len; ++ } ++ ++ if (!Path.empty() && Path[0] == '/') { ++ if (auto Traced = ReadlinkTraceeExe(Path.c_str(), buf, bufsiz)) { ++ return *Traced; ++ } + } + + FDPathTmpData TmpFilename; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp +index 7ae8236b3..3be10d097 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.cpp +@@ -50,6 +50,7 @@ public: + + void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) override; + int Munmap(void* addr, size_t length) override; ++ void TrackUnmapped(void* addr, size_t length) override; + void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) override; + uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) override; + uint64_t Shmdt(const void* shmaddr) override; +@@ -333,6 +334,17 @@ int MemAllocator32Bit::Munmap(void* addr, size_t length) { + return 0; + } + ++void MemAllocator32Bit::TrackUnmapped(void* addr, size_t length) { ++ std::scoped_lock lk {AllocMutex}; ++ ++ const uint64_t Addr = reinterpret_cast(addr); ++ const uint64_t PageAddr = std::max(Addr >> FEXCore::Utils::FEX_PAGE_SHIFT, BASE_KEY); ++ const uint64_t PageEnd = std::min(FEXCore::AlignUp(Addr + length, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT, TOP_KEY); ++ if (PageAddr < PageEnd) { ++ SetFreePages(PageAddr, PageEnd - PageAddr); ++ } ++} ++ + void* MemAllocator32Bit::Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) { + size_t OldPagesLength = FEXCore::AlignUp(old_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT; + size_t NewPagesLength = FEXCore::AlignUp(new_size, FEXCore::Utils::FEX_PAGE_SIZE) >> FEXCore::Utils::FEX_PAGE_SHIFT; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h +index dd6ae074f..c84f85b4a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/LinuxAllocator.h +@@ -14,6 +14,7 @@ public: + virtual ~MemAllocator() = default; + virtual void* Mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset) = 0; + virtual int Munmap(void* addr, size_t length) = 0; ++ virtual void TrackUnmapped(void* addr, size_t length) {} + virtual void* Mremap(void* old_address, size_t old_size, size_t new_size, int flags, void* new_address) = 0; + virtual uint64_t Shmat(int shmid, const void* shmaddr, int shmflg, uint32_t* ResultAddress) = 0; + virtual uint64_t Shmdt(const void* shmaddr) = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +new file mode 100644 +index 000000000..ca4c86063 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -0,0 +1,838 @@ ++// SPDX-License-Identifier: MIT ++ ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/Syscalls.h" ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::PtraceEmu { ++namespace { ++#ifndef NT_X86_XSTATE ++ constexpr uintptr_t NT_X86_XSTATE = 0x202; ++#endif ++ ++ enum UserReg : unsigned { ++ R15, R14, R13, R12, Rbp, Rbx, R11, R10, R9, R8, Rax, Rcx, Rdx, Rsi, Rdi, OrigRax, Rip, Cs, Eflags, Rsp, Ss, FsBase, GsBase, Ds, Es, Fs, Gs, ++ }; ++ static_assert(Gs + 1 == NumUserRegs); ++ ++ constexpr uintptr_t UserDebugRegByteOffset = 848; ++ constexpr uintptr_t UserDebugRegByteEnd = UserDebugRegByteOffset + 8 * sizeof(uint64_t); ++ constexpr uintptr_t UserStructSize = 928; ++ ++ constexpr uint64_t UserTaskSizeMax = 0x00007ffffffff000ULL; ++ ++ bool DrFieldValid(uint64_t Field, uint64_t* AlignMask) { ++ const uint64_t Len = Field & 0xC; ++ switch (Field & 0x3) { ++ case 0x0: ++ if (Len != 0x0) { ++ return false; ++ } ++ *AlignMask = 0; ++ return true; ++ case 0x1: ++ case 0x3: ++ switch (Len) { ++ case 0x0: *AlignMask = 0; return true; ++ case 0x4: *AlignMask = 1; return true; ++ case 0xC: *AlignMask = 3; return true; ++ case 0x8: *AlignMask = 7; return true; ++ default: return false; ++ } ++ default: ++ return false; ++ } ++ } ++ ++ constexpr unsigned DrEnableShift(unsigned N) { return N * 2; } ++ constexpr unsigned DrFieldShift(unsigned N) { return 16 + N * 4; } ++ ++ bool DrAddressValid(uint64_t Addr, uint64_t AlignMask) { ++ return Addr < UserTaskSizeMax && (Addr & AlignMask) == 0; ++ } ++ ++ bool Dr7Valid(const uint64_t Dr[8], uint64_t NewDr7) { ++ for (unsigned N = 0; N < 4; ++N) { ++ const bool Enabled = (NewDr7 >> DrEnableShift(N)) & 0x3; ++ const bool Registered = Dr[N] != 0; ++ if (!Enabled && !Registered) { ++ continue; ++ } ++ const uint64_t Field = (NewDr7 >> DrFieldShift(N)) & 0xF; ++ uint64_t AlignMask = 0; ++ if (!DrFieldValid(Field, &AlignMask) || !DrAddressValid(Dr[N], AlignMask)) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ constexpr uint16_t UserCodeSegment = 0x33; ++ constexpr uint16_t UserStackSegment = 0x2b; ++ constexpr uint64_t UserFlags = 0x246; ++ constexpr uint64_t NoOverride = ~0ULL; ++ ++ constexpr int X86_PTRACE_GETREGS = 12; ++ constexpr int X86_PTRACE_SETREGS = 13; ++ constexpr int X86_PTRACE_EVENT_EXEC = 4; ++ ++ SharedState StaticState {SharedState::MagicValue}; ++ SharedState* Current = &StaticState; ++ thread_local uint64_t PendingRip = 0; ++ ++ struct OpenSyscall { ++ bool Open = false; ++ uint64_t Nr {}; ++ uint64_t Args[6] {}; ++ } Previous; ++ ++ constexpr const char* SidecarDirs[] = {"/dev/shm", "/tmp"}; ++ ++ std::string SidecarPath(const char* Dir, const char* Kind, pid_t Pid) { ++ return std::string(Dir) + "/fex-ptrace-" + Kind + "-" + std::to_string(Pid); ++ } ++ ++ int OpenSidecar(const char* Kind, pid_t Pid, int Flags) { ++ for (const char* Dir : SidecarDirs) { ++ const int fd = ::open(SidecarPath(Dir, Kind, Pid).c_str(), Flags | O_CLOEXEC, 0600); ++ if (fd >= 0) { ++ return fd; ++ } ++ } ++ return -1; ++ } ++ ++ void RemoveSidecar(const char* Kind, pid_t Pid) { ++ for (const char* Dir : SidecarDirs) { ++ ::unlink(SidecarPath(Dir, Kind, Pid).c_str()); ++ } ++ } ++ ++ bool IsMainThread() { ++ return ::syscall(SYS_gettid) == ::getpid(); ++ } ++ ++ bool HasHostTracer() { ++ const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ if (fd < 0) { ++ return true; ++ } ++ char Buf[2048]; ++ const ssize_t n = ::read(fd, Buf, sizeof(Buf) - 1); ++ ::close(fd); ++ if (n <= 0) { ++ return true; ++ } ++ Buf[n] = 0; ++ const char* Tag = strstr(Buf, "TracerPid:"); ++ return !Tag || atoi(Tag + sizeof("TracerPid:") - 1) != 0; ++ } ++ ++ ++ void BuildRegs(const FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, bool Entry, uint64_t Ret, uint64_t* X) { ++ using namespace FEXCore::X86State; ++ const auto& S = Frame->State; ++ X[R15] = S.gregs[REG_R15]; ++ X[R14] = S.gregs[REG_R14]; ++ X[R13] = S.gregs[REG_R13]; ++ X[R12] = S.gregs[REG_R12]; ++ X[Rbp] = S.gregs[REG_RBP]; ++ X[Rbx] = S.gregs[REG_RBX]; ++ X[R11] = UserFlags; ++ X[R10] = S.gregs[REG_R10]; ++ X[R9] = S.gregs[REG_R9]; ++ X[R8] = S.gregs[REG_R8]; ++ X[Rax] = Entry ? static_cast(-ENOSYS) : Ret; ++ X[Rcx] = S.gregs[REG_RCX]; ++ X[Rdx] = S.gregs[REG_RDX]; ++ X[Rsi] = S.gregs[REG_RSI]; ++ X[Rdi] = S.gregs[REG_RDI]; ++ X[OrigRax] = Nr; ++ X[Rip] = S.gregs[REG_RCX] ? S.gregs[REG_RCX] : S.rip; ++ X[Cs] = UserCodeSegment; ++ X[Eflags] = UserFlags; ++ X[Rsp] = S.gregs[REG_RSP]; ++ X[Ss] = UserStackSegment; ++ X[FsBase] = S.fs_cached; ++ X[GsBase] = S.gs_cached; ++ X[Ds] = X[Es] = X[Fs] = X[Gs] = 0; ++ } ++ ++ void Stop(uint64_t Nr, const uint64_t Args[6], bool Entry, uint64_t Ret, const uint64_t* Regs) { ++ SharedState& S = *Current; ++ if (!HasHostTracer()) { ++ S.SyscallStops = 0; ++ S.Attached = 0; ++ return; ++ } ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ S.Regs[i] = Regs[i]; ++ } ++ S.PendingNr = Nr; ++ for (unsigned i = 0; i < 6; ++i) { ++ S.PendingArgs[i] = Args[i]; ++ } ++ S.PendingRet = Ret; ++ S.PendingIsEntry = Entry ? 1 : 0; ++ S.Pending = 1; ++ ::syscall(SYS_tgkill, ::getpid(), ::syscall(SYS_gettid), SIGSTOP); ++ S.Pending = 0; ++ } ++ ++ uint64_t ApplyTracerWrites(FEXCore::Core::CpuStateFrame* Frame, bool Entry) { ++ using namespace FEXCore::X86State; ++ SharedState& S = *Current; ++ ++ if (S.FlushLen) { ++ const uint64_t Addr = S.FlushAddr; ++ const uint64_t Len = S.FlushLen; ++ S.FlushLen = 0; ++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len); ++ } ++ ++ const uint64_t Dirty = S.DirtyMask; ++ if (!Dirty) { ++ return NoOverride; ++ } ++ ++ static constexpr int Map[15] = {REG_R15, REG_R14, REG_R13, REG_R12, REG_RBP, REG_RBX, -1, REG_R10, REG_R9, REG_R8, -1, REG_RCX, REG_RDX, REG_RSI, REG_RDI}; ++ auto& State = Frame->State; ++ uint64_t Override = NoOverride; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!(Dirty & (1ULL << i))) { ++ continue; ++ } ++ const uint64_t V = S.Regs[i]; ++ if (i < 15) { ++ if (Map[i] >= 0) { ++ State.gregs[Map[i]] = V; ++ } ++ } else if (i == Rip) { ++ PendingRip = V; ++ } else if (i == Rsp) { ++ State.gregs[REG_RSP] = V; ++ } else if (i == FsBase) { ++ State.fs_cached = V; ++ } else if (i == GsBase) { ++ State.gs_cached = V; ++ } ++ if (i == Rax && !Entry) { ++ Override = V; ++ } ++ } ++ if (Entry && (Dirty & (1ULL << OrigRax))) { ++ State.gregs[REG_RAX] = S.Regs[OrigRax]; ++ } ++ S.DirtyMask = 0; ++ return Override; ++ } ++ ++ void PublishSharedPage() { ++ if (Current != &StaticState) { ++ return; ++ } ++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR | O_CREAT | O_TRUNC); ++ if (fd < 0) { ++ return; ++ } ++ if (::ftruncate(fd, 4096) == 0) { ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ if (Page != MAP_FAILED) { ++ std::memcpy(Page, &StaticState, sizeof(SharedState)); ++ Current = static_cast(Page); ++ } ++ } ++ ::close(fd); ++ } ++ ++ struct Remote { ++ uint8_t* Mapped = nullptr; ++ uintptr_t StaticAddr = 0; ++ std::array FpRegs {}; ++ bool FpValid = false; ++ std::array XState {}; ++ bool XStateValid = false; ++ }; ++ std::mutex RemotesLock; ++ std::unordered_map Remotes; ++ std::unordered_map ExePaths; ++ ++ uintptr_t FindFexImageBase(pid_t Pid) { ++ static const std::string SelfExe = []() { ++ char Buf[512]; ++ const ssize_t n = ::readlink("/proc/self/exe", Buf, sizeof(Buf) - 1); ++ return n > 0 ? std::string(Buf, n) : std::string(); ++ }(); ++ if (SelfExe.empty()) { ++ return 0; ++ } ++ const std::string Maps = Pid ? "/proc/" + std::to_string(Pid) + "/maps" : "/proc/self/maps"; ++ FILE* F = fopen(Maps.c_str(), "r"); ++ if (!F) { ++ return 0; ++ } ++ char Line[1024]; ++ uintptr_t Lowest = 0; ++ while (fgets(Line, sizeof(Line), F)) { ++ if (!strstr(Line, SelfExe.c_str())) { ++ continue; ++ } ++ unsigned long long Start = 0, End = 0, Offset = 0; ++ if (sscanf(Line, "%llx-%llx %*s %llx", &Start, &End, &Offset) == 3 && Offset == 0 && (!Lowest || Start < Lowest)) { ++ Lowest = Start; ++ } ++ } ++ fclose(F); ++ return Lowest; ++ } ++ ++ Remote* Lookup(pid_t Pid) { ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ return &It->second; ++ } ++ Remote R; ++ const int fd = OpenSidecar("state", Pid, O_RDWR); ++ if (fd >= 0) { ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ ::close(fd); ++ if (Page != MAP_FAILED) { ++ R.Mapped = static_cast(Page); ++ } ++ } ++ if (!R.Mapped) { ++ static const uintptr_t SelfBase = FindFexImageBase(0); ++ const uintptr_t TraceeBase = FindFexImageBase(Pid); ++ if (!SelfBase || !TraceeBase) { ++ return nullptr; ++ } ++ R.StaticAddr = TraceeBase + (reinterpret_cast(&StaticState) - SelfBase); ++ } ++ return &Remotes.emplace(Pid, std::move(R)).first->second; ++ } ++ ++ void Forget(pid_t Pid, bool Exited) { ++ std::lock_guard lk(RemotesLock); ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ if (It->second.Mapped) { ++ ::munmap(It->second.Mapped, 4096); ++ } ++ Remotes.erase(It); ++ } ++ RemoveSidecar("state", Pid); ++ if (Exited) { ++ ExePaths.erase(Pid); ++ } ++ } ++ ++ void CaptureExecPath(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && R->Mapped) { ++ auto* S = reinterpret_cast(R->Mapped); ++ if (S->Magic == SharedState::MagicValue && S->ExePath[0]) { ++ ExePaths[Pid] = std::string(S->ExePath, strnlen(S->ExePath, sizeof(S->ExePath))); ++ } ++ } ++ } ++ ++ uint64_t HostPtrace(int Request, pid_t Pid, void* Addr, void* Data) { ++ const long R = ::syscall(SYS_ptrace, Request, Pid, Addr, Data); ++ return R == -1 ? static_cast(-errno) : static_cast(R); ++ } ++ ++ bool ReadWord(pid_t Pid, size_t Offset, uint64_t* Out) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (!R) { ++ return false; ++ } ++ if (R->Mapped) { ++ *Out = *reinterpret_cast(R->Mapped + Offset); ++ return true; ++ } ++ return ::syscall(SYS_ptrace, PTRACE_PEEKDATA, Pid, R->StaticAddr + Offset, Out) == 0; ++ } ++ ++ bool WriteWord(pid_t Pid, size_t Offset, uint64_t Value) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (!R) { ++ return false; ++ } ++ if (R->Mapped) { ++ *reinterpret_cast(R->Mapped + Offset) = Value; ++ return true; ++ } ++ return ::syscall(SYS_ptrace, PTRACE_POKEDATA, Pid, R->StaticAddr + Offset, Value) == 0; ++ } ++ ++ bool IsFexTracee(pid_t Pid) { ++ uint64_t Magic = 0; ++ return ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue; ++ } ++ ++ bool ReadSlot(pid_t Pid, size_t Offset, uint64_t* Out) { ++ return ReadWord(Pid, Offset, Out); ++ } ++ ++ void MarkDirty(pid_t Pid, uint64_t Mask) { ++ uint64_t Dirty = 0; ++ ReadWord(Pid, offsetof(SharedState, DirtyMask), &Dirty); ++ WriteWord(Pid, offsetof(SharedState, DirtyMask), Dirty | Mask); ++ } ++ ++ constexpr size_t RegOffset(unsigned Index) { ++ return offsetof(SharedState, Regs) + Index * sizeof(uint64_t); ++ } ++ ++ bool ReadDebugReg(pid_t Pid, unsigned N, uint64_t* Out) { ++ if (N == 4 || N == 5) { ++ *Out = 0; ++ return true; ++ } ++ if (N > 7) { ++ return false; ++ } ++ return ReadWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Out); ++ } ++ ++ int WriteDebugReg(pid_t Pid, unsigned N, uint64_t Value) { ++ if (N == 4 || N == 5) { ++ return -EIO; ++ } ++ if (N <= 3) { ++ if (!DrAddressValid(Value, 0)) { ++ return -EINVAL; ++ } ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + N * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ if (N == 6) { ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 6 * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ uint64_t Dr[8] {}; ++ for (unsigned I = 0; I < 8; ++I) { ++ if (!ReadWord(Pid, offsetof(SharedState, DebugRegs) + I * sizeof(uint64_t), &Dr[I])) { ++ return -ESRCH; ++ } ++ } ++ if (!Dr7Valid(Dr, Value)) { ++ return -EINVAL; ++ } ++ return WriteWord(Pid, offsetof(SharedState, DebugRegs) + 7 * sizeof(uint64_t), Value) ? 0 : -ESRCH; ++ } ++ ++ Remote* XStateState(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && !R->XStateValid) { ++ R->XStateValid = true; ++ } ++ return R; ++ } ++ ++ Remote* FpState(pid_t Pid) { ++ std::lock_guard lk(RemotesLock); ++ Remote* R = Lookup(Pid); ++ if (R && !R->FpValid) { ++ const uint16_t Fcw = 0x37f; ++ const uint32_t Mxcsr = 0x1f80, MxcsrMask = 0xffff; ++ std::memcpy(&R->FpRegs[0], &Fcw, sizeof(Fcw)); ++ std::memcpy(&R->FpRegs[24], &Mxcsr, sizeof(Mxcsr)); ++ std::memcpy(&R->FpRegs[28], &MxcsrMask, sizeof(MxcsrMask)); ++ R->FpValid = true; ++ } ++ return R; ++ } ++} ++ ++ ++bool IsAttached() { ++ return Current->Attached != 0; ++} ++ ++bool WantsSyscallStops() { ++ return Current->SyscallStops && IsMainThread(); ++} ++ ++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]) { ++ uint64_t Regs[NumUserRegs]; ++ if (Previous.Open) { ++ BuildRegs(Frame, Previous.Nr, false, 0, Regs); ++ Stop(Previous.Nr, Previous.Args, false, 0, Regs); ++ } ++ BuildRegs(Frame, Nr, true, 0, Regs); ++ Stop(Nr, Args, true, 0, Regs); ++ ApplyTracerWrites(Frame, true); ++ ++ const uint64_t NewNr = Frame->State.gregs[FEXCore::X86State::REG_RAX]; ++ Previous.Open = Current->SyscallStops != 0; ++ Previous.Nr = NewNr; ++ std::copy(Args, Args + 6, Previous.Args); ++ return NewNr; ++} ++ ++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result) { ++ uint64_t Regs[NumUserRegs]; ++ BuildRegs(Frame, Nr, false, Result, Regs); ++ Stop(Nr, Args, false, Result, Regs); ++ const uint64_t Override = ApplyTracerWrites(Frame, false); ++ Previous.Open = false; ++ return Override != NoOverride ? Override : Result; ++} ++ ++void OnForkedChild(bool SharesAddressSpace) { ++ if (SharesAddressSpace) { ++ return; ++ } ++ Current = &StaticState; ++ StaticState.SyscallStops = 0; ++ StaticState.Attached = 0; ++ StaticState.Pending = 0; ++ Previous.Open = false; ++} ++ ++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame) { ++ SharedState& S = *Current; ++ if (S.FlushLen) { ++ const uint64_t Addr = S.FlushAddr; ++ const uint64_t Len = S.FlushLen; ++ S.FlushLen = 0; ++ FEX::HLE::_SyscallHandler->InvalidateGuestCodeRange(Frame->Thread, Addr, Len); ++ } ++} ++ ++uint64_t TakePendingRip() { ++ const uint64_t Rip = PendingRip; ++ PendingRip = 0; ++ return Rip; ++} ++ ++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal) { ++ if (Signal != SIGTRAP && Signal != SIGSEGV) { ++ return false; ++ } ++ if (!Frame->SynchronousFaultData.FaultToTopAndGeneratedException || !Current->Attached || !IsMainThread()) { ++ return false; ++ } ++ ++ uint64_t Regs[NumUserRegs]; ++ const uint64_t NoArgs[6] {}; ++ BuildRegs(Frame, ~0ULL, false, Frame->State.gregs[FEXCore::X86State::REG_RAX], Regs); ++ Regs[Rip] = Frame->State.rip; ++ ++ Current->SignalNumber = static_cast(Signal); ++ Stop(~0ULL, NoArgs, false, 0, Regs); ++ Current->SignalNumber = 0; ++ ++ const uint64_t Override = ApplyTracerWrites(Frame, false); ++ if (Override != NoOverride) { ++ Frame->State.gregs[FEXCore::X86State::REG_RAX] = Override; ++ } ++ if (const uint64_t NewRip = TakePendingRip()) { ++ Frame->State.rip = NewRip; ++ } ++ return true; ++} ++ ++void RecordExecPath(const std::string& GuestPath) { ++ if (!Current->Attached) { ++ return; ++ } ++ const size_t Len = std::min(GuestPath.size(), sizeof(Current->ExePath) - 1); ++ std::memcpy(Current->ExePath, GuestPath.data(), Len); ++ Current->ExePath[Len] = 0; ++} ++ ++ ++std::optional TraceeExePath(pid_t Pid) { ++ if (Pid <= 0 || Pid == ::getpid()) { ++ return std::nullopt; ++ } ++ std::lock_guard lk(RemotesLock); ++ auto It = ExePaths.find(Pid); ++ return It != ExePaths.end() ? std::optional(It->second) : std::nullopt; ++} ++ ++bool FixupWaitStatus(pid_t Pid, int* Status) { ++ if (!Status || Pid <= 0) { ++ return false; ++ } ++ const int St = *Status; ++ ++ if (WIFEXITED(St) || WIFSIGNALED(St)) { ++ Forget(Pid, true); ++ return false; ++ } ++ if (!WIFSTOPPED(St)) { ++ return false; ++ } ++ ++ if ((St >> 16) == 0 && (WSTOPSIG(St) == SIGTRAP || WSTOPSIG(St) == SIGSEGV) && IsFexTracee(Pid)) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(WSTOPSIG(St)))); ++ return true; ++ } ++ ++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGBUS && IsFexTracee(Pid)) { ++ siginfo_t Info {}; ++ if (HostPtrace(PTRACE_GETSIGINFO, Pid, nullptr, &Info) == 0 && Info.si_code == BUS_ADRALN) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, reinterpret_cast(static_cast(SIGBUS))); ++ return true; ++ } ++ } ++ ++ if ((St >> 16) == 0 && WSTOPSIG(St) == SIGPROF && IsFexTracee(Pid)) { ++ HostPtrace(PTRACE_CONT, Pid, nullptr, nullptr); ++ return true; ++ } ++ ++ if ((St >> 16) == X86_PTRACE_EVENT_EXEC) { ++ CaptureExecPath(Pid); ++ Forget(Pid, false); ++ } ++ ++ if (WSTOPSIG(St) == SIGSTOP) { ++ uint64_t Pending = 0; ++ if (ReadWord(Pid, offsetof(SharedState, Pending), &Pending) && Pending) { ++ uint64_t Signal = 0; ++ ReadWord(Pid, offsetof(SharedState, SignalNumber), &Signal); ++ *Status = (St & ~0xff00) | (static_cast(Signal ? Signal : (SIGTRAP | 0x80)) << 8); ++ } ++ } ++ return false; ++} ++ ++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result) { ++ switch (Request) { ++ case PTRACE_TRACEME: ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ if (*Result == 0) { ++ PublishSharedPage(); ++ Current->Attached = 1; ++ } ++ return true; ++ ++ case PTRACE_KILL: ++ case PTRACE_SEIZE: ++ case PTRACE_INTERRUPT: ++ case PTRACE_SETOPTIONS: ++ case PTRACE_GETEVENTMSG: ++ case PTRACE_SINGLESTEP: ++ case PTRACE_GETSIGINFO: *Result = HostPtrace(Request, Pid, Addr, Data); return true; ++ ++ case PTRACE_POKETEXT: ++ case PTRACE_POKEDATA: { ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ if (*Result == 0 && IsFexTracee(Pid)) { ++ const uint64_t Lo = reinterpret_cast(Addr) & ~0xfffULL; ++ const uint64_t Hi = Lo + 0x2000; ++ uint64_t OldAddr = 0, OldLen = 0; ++ ReadWord(Pid, offsetof(SharedState, FlushAddr), &OldAddr); ++ ReadWord(Pid, offsetof(SharedState, FlushLen), &OldLen); ++ uint64_t NewLo = Lo, NewHi = Hi; ++ if (OldLen) { ++ NewLo = std::min(OldAddr, Lo); ++ NewHi = std::max(OldAddr + OldLen, Hi); ++ } ++ WriteWord(Pid, offsetof(SharedState, FlushAddr), NewLo); ++ WriteWord(Pid, offsetof(SharedState, FlushLen), NewHi - NewLo); ++ } ++ return true; ++ } ++ ++ case PTRACE_CONT: ++ case PTRACE_SYSCALL: { ++ uint64_t Magic = 0; ++ if (ReadWord(Pid, offsetof(SharedState, Magic), &Magic) && Magic == SharedState::MagicValue) { ++ WriteWord(Pid, offsetof(SharedState, SyscallStops), Request == PTRACE_SYSCALL ? 1 : 0); ++ WriteWord(Pid, offsetof(SharedState, Attached), 1); ++ } ++ *Result = HostPtrace(PTRACE_CONT, Pid, Addr, Data); ++ return true; ++ } ++ ++ case PTRACE_DETACH: { ++ if (IsFexTracee(Pid)) { ++ WriteWord(Pid, offsetof(SharedState, SyscallStops), 0); ++ WriteWord(Pid, offsetof(SharedState, Attached), 0); ++ } ++ *Result = HostPtrace(Request, Pid, Addr, Data); ++ Forget(Pid, false); ++ return true; ++ } ++ ++ case PTRACE_PEEKUSER: { ++ const uintptr_t Off = reinterpret_cast(Addr); ++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) { ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ uint64_t V = 0; ++ if (Off < NumUserRegs * sizeof(uint64_t)) { ++ if (!ReadSlot(Pid, RegOffset(Off / 8), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } else if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) { ++ if (!ReadDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } ++ *static_cast(Data) = V; ++ *Result = 0; ++ return true; ++ } ++ ++ case PTRACE_POKEUSER: { ++ const uintptr_t Off = reinterpret_cast(Addr); ++ if ((Off % sizeof(uint64_t)) != 0 || Off >= UserStructSize) { ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ if (Off < NumUserRegs * sizeof(uint64_t)) { ++ if (!WriteWord(Pid, RegOffset(Off / 8), reinterpret_cast(Data))) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ MarkDirty(Pid, 1ULL << (Off / 8)); ++ *Result = 0; ++ return true; ++ } ++ if (Off >= UserDebugRegByteOffset && Off < UserDebugRegByteEnd) { ++ *Result = static_cast(WriteDebugReg(Pid, static_cast((Off - UserDebugRegByteOffset) / sizeof(uint64_t)), reinterpret_cast(Data))); ++ return true; ++ } ++ *Result = static_cast(-EIO); ++ return true; ++ } ++ ++ case X86_PTRACE_GETREGS: { ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ uint64_t V = 0; ++ if (!ReadSlot(Pid, RegOffset(i), &V)) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ static_cast(Data)[i] = V; ++ } ++ *Result = 0; ++ return true; ++ } ++ ++ case X86_PTRACE_SETREGS: { ++ uint64_t Mask = 0; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!WriteWord(Pid, RegOffset(i), static_cast(Data)[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ Mask |= 1ULL << i; ++ } ++ MarkDirty(Pid, Mask); ++ *Result = 0; ++ return true; ++ } ++ ++ case PTRACE_GETREGSET: ++ case PTRACE_SETREGSET: { ++ const auto NtType = reinterpret_cast(Addr); ++ auto* Iov = static_cast(Data); ++ if (!Iov) { ++ return false; ++ } ++ const bool Get = Request == PTRACE_GETREGSET; ++ ++ if (NtType == NT_PRSTATUS) { ++ if (Get) { ++ uint64_t Image[NumUserRegs]; ++ for (unsigned i = 0; i < NumUserRegs; ++i) { ++ if (!ReadSlot(Pid, RegOffset(i), &Image[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ } ++ const size_t Len = std::min(Iov->iov_len, sizeof(Image)); ++ std::memcpy(Iov->iov_base, Image, Len); ++ Iov->iov_len = Len; ++ } else { ++ const size_t Slots = std::min(Iov->iov_len / sizeof(uint64_t), NumUserRegs); ++ uint64_t Mask = 0; ++ for (size_t i = 0; i < Slots; ++i) { ++ if (!WriteWord(Pid, RegOffset(i), static_cast(Iov->iov_base)[i])) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ Mask |= 1ULL << i; ++ } ++ MarkDirty(Pid, Mask); ++ Iov->iov_len = NumUserRegs * sizeof(uint64_t); ++ } ++ *Result = 0; ++ return true; ++ } ++ ++ if (NtType == NT_PRFPREG) { ++ Remote* R = FpState(Pid); ++ if (!R) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ const size_t Len = std::min(Iov->iov_len, R->FpRegs.size()); ++ if (Get) { ++ std::memcpy(Iov->iov_base, R->FpRegs.data(), Len); ++ } else { ++ std::memcpy(R->FpRegs.data(), Iov->iov_base, Len); ++ } ++ Iov->iov_len = Len; ++ *Result = 0; ++ return true; ++ } ++ ++ if (NtType == NT_X86_XSTATE) { ++ Remote* R = XStateState(Pid); ++ if (!R) { ++ *Result = static_cast(-ESRCH); ++ return true; ++ } ++ const size_t Len = std::min(Iov->iov_len, R->XState.size()); ++ if (Get) { ++ std::memcpy(Iov->iov_base, R->XState.data(), Len); ++ } else { ++ std::memcpy(R->XState.data(), Iov->iov_base, Len); ++ } ++ Iov->iov_len = Len; ++ *Result = 0; ++ return true; ++ } ++ ++ *Result = static_cast(-EINVAL); ++ return true; ++ } ++ ++ default: return false; ++ } ++} ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h +new file mode 100644 +index 000000000..59194979a +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.h +@@ -0,0 +1,63 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++#include ++#include ++ ++namespace FEXCore::Core { ++struct CpuStateFrame; ++} ++ ++namespace FEX::HLE::PtraceEmu { ++ ++constexpr unsigned NumUserRegs = 27; ++ ++struct SharedState { ++ static constexpr uint64_t MagicValue = 0xFE8E5E57CAFE0001ULL; ++ ++ volatile uint64_t Magic; ++ volatile uint64_t SyscallStops; ++ volatile uint64_t Attached; ++ volatile uint64_t Pending; ++ volatile uint64_t PendingIsEntry; ++ volatile uint64_t PendingNr; ++ volatile uint64_t PendingArgs[6]; ++ volatile uint64_t PendingRet; ++ volatile uint64_t Regs[NumUserRegs]; ++ volatile uint64_t DebugRegs[8]; ++ volatile uint64_t DirtyMask; ++ volatile uint64_t SignalNumber; ++ volatile uint64_t FlushAddr; ++ volatile uint64_t FlushLen; ++ char ExePath[1024]; ++}; ++ ++ ++bool WantsSyscallStops(); ++ ++uint64_t SyscallEntryStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6]); ++ ++uint64_t SyscallExitStop(FEXCore::Core::CpuStateFrame* Frame, uint64_t Nr, const uint64_t Args[6], uint64_t Result); ++ ++void OnForkedChild(bool SharesAddressSpace); ++ ++void ApplyPendingFlush(FEXCore::Core::CpuStateFrame* Frame); ++ ++uint64_t TakePendingRip(); ++ ++bool TryGuestSignalStop(FEXCore::Core::CpuStateFrame* Frame, int Signal); ++ ++void RecordExecPath(const std::string& GuestPath); ++ ++bool IsAttached(); ++ ++ ++bool HandleRequest(int Request, pid_t Pid, void* Addr, void* Data, uint64_t* Result); ++ ++bool FixupWaitStatus(pid_t Pid, int* Status); ++ ++std::optional TraceeExePath(pid_t Pid); ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h +new file mode 100644 +index 000000000..3f36e79fd +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SMCHotPages.h +@@ -0,0 +1,90 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE { ++ ++class SMCHotPageTracker final { ++public: ++ static constexpr uint64_t PageShift = 12; ++ ++ bool RecordFault(uint64_t Address, uint32_t FaultThreshold) { ++ if (!FaultThreshold) { ++ return false; ++ } ++ const uint64_t Page = Address >> PageShift; ++ auto& Slot = Counters[Hash(Page) & (CounterSlots - 1)]; ++ ++ uint64_t Old = Slot.load(std::memory_order_relaxed); ++ uint64_t New; ++ do { ++ const uint64_t Count = (Old >> CountBits) == Page ? (Old & CountMask) + 1 : 1; ++ New = (Page << CountBits) | (Count < CountMask ? Count : CountMask); ++ } while (!Slot.compare_exchange_weak(Old, New, std::memory_order_relaxed)); ++ ++ return (New & CountMask) == FaultThreshold && MakeHot(Page); ++ } ++ ++ bool MarkHot(uint64_t Address) { ++ return MakeHot(Address >> PageShift); ++ } ++ ++ bool IsHot(uint64_t Address) const { ++ if (HotCount.load(std::memory_order_relaxed) == 0) { ++ return false; ++ } ++ ++ const uint64_t Key = (Address >> PageShift) + 1; ++ for (size_t i = 0, Idx = Hash(Key - 1); i < HotSlots; ++i, ++Idx) { ++ const uint64_t Entry = Hot[Idx & (HotSlots - 1)].load(std::memory_order_relaxed); ++ if (Entry == Key) { ++ return true; ++ } ++ if (Entry == 0) { ++ return false; ++ } ++ } ++ return false; ++ } ++ ++private: ++ static constexpr size_t CounterSlots = 4096; ++ static constexpr size_t HotSlots = 2048; ++ static constexpr unsigned CountBits = 20; ++ static constexpr uint64_t CountMask = (1ULL << CountBits) - 1; ++ static_assert((CounterSlots & (CounterSlots - 1)) == 0 && (HotSlots & (HotSlots - 1)) == 0); ++ ++ static size_t Hash(uint64_t Page) { ++ return static_cast((Page * 0x9E3779B97F4A7C15ULL) >> 40); ++ } ++ ++ bool MakeHot(uint64_t Page) { ++ if (HotCount.load(std::memory_order_relaxed) >= HotSlots / 4 * 3) { ++ return false; ++ } ++ ++ const uint64_t Key = Page + 1; ++ for (size_t i = 0, Idx = Hash(Page); i < HotSlots; ++i, ++Idx) { ++ auto& Entry = Hot[Idx & (HotSlots - 1)]; ++ uint64_t Expected = 0; ++ if (Entry.compare_exchange_strong(Expected, Key, std::memory_order_relaxed)) { ++ HotCount.fetch_add(1, std::memory_order_relaxed); ++ return true; ++ } ++ if (Expected == Key) { ++ return false; ++ } ++ } ++ return false; ++ } ++ ++ std::array, CounterSlots> Counters {}; ++ std::array, HotSlots> Hot {}; ++ std::atomic HotCount {}; ++}; ++ ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp +new file mode 100644 +index 000000000..abc3284a3 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.cpp +@@ -0,0 +1,278 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SamplingProfiler.h" ++#include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "ArchHelpers/MContext.h" ++ ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE { ++namespace { ++ struct Sample { ++ uint64_t HostPC; ++ uint64_t Info; ++ }; ++ constexpr size_t MaxSamples = 1 << 18; ++ std::atomic RecordsPtr {nullptr}; ++ Sample* Records = nullptr; ++ std::atomic Count {0}; ++ ++ struct SnapRecord { ++ uint64_t Tid; ++ uint64_t HostPC; ++ uint64_t Rip; ++ uint64_t FutexWord; ++ uint64_t FutexExpected; ++ uint64_t FutexAddr; ++ uint64_t Gregs[16]; ++ uint64_t Stack[138]; ++ }; ++ static_assert(sizeof(SnapRecord) == 160 * 8); ++ constexpr size_t MaxSnaps = 1024; ++ SnapRecord* Snaps = nullptr; ++ std::atomic SnapCount {0}; ++ std::atomic SnapMode {false}; ++ bool ExternalMode = false; ++ FEX::HLE::SignalDelegator* Delegator = nullptr; ++ std::atomic ExternalOpen {false}; ++ ++ void OpenExternalSnaps() { ++ if (ExternalOpen.exchange(true)) { ++ return; ++ } ++ char Path[64]; ++ snprintf(Path, sizeof(Path), "/dev/shm/fex-%d-snap", static_cast(getpid())); ++ const int fd = open(Path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) { ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Snaps = static_cast(Map); ++ } ++ } ++ ++ bool IsInteresting(pid_t Tid) { ++ static thread_local std::unordered_map Last; ++ char Path[64]; ++ snprintf(Path, sizeof(Path), "/proc/self/task/%d/stat", Tid); ++ FILE* F = fopen(Path, "r"); ++ if (!F) { ++ return false; ++ } ++ char Buf[512]; ++ const bool Ok = fgets(Buf, sizeof(Buf), F) != nullptr; ++ fclose(F); ++ if (!Ok) { ++ return false; ++ } ++ const char* P = strrchr(Buf, ')'); ++ unsigned long Ut = 0, St = 0; ++ if (!P || sscanf(P + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &Ut, &St) != 2) { ++ return false; ++ } ++ auto& L = Last[Tid]; ++ const bool Busy = (Ut + St) > L; ++ L = Ut + St; ++ return Busy; ++ } ++ ++ bool OpenRecords(pid_t Pid) { ++ if (Records) { ++ return true; ++ } ++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-samples"; ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(Sample) * MaxSamples) != 0) { ++ return false; ++ } ++ void* Map = mmap(nullptr, sizeof(Sample) * MaxSamples, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map == MAP_FAILED) { ++ return false; ++ } ++ Records = static_cast(Map); ++ return true; ++ } ++ ++ void TakeSnapshot(pid_t Pid) { ++ if (!Snaps) { ++ const std::string Path = "/dev/shm/fex-" + std::to_string(Pid) + "-snap"; ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0 || ftruncate(fd, sizeof(SnapRecord) * MaxSnaps) != 0) { ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(SnapRecord) * MaxSnaps, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map == MAP_FAILED) { ++ return; ++ } ++ Snaps = static_cast(Map); ++ } ++ memset(Snaps, 0, sizeof(SnapRecord) * MaxSnaps); ++ SnapCount = 0; ++ SnapMode = true; ++ if (DIR* D = opendir("/proc/self/task")) { ++ while (auto* E = readdir(D)) { ++ const pid_t Tid = atoi(E->d_name); ++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid))) { ++ syscall(SYS_tgkill, Pid, Tid, SIGPROF); ++ } ++ } ++ closedir(D); ++ } ++ usleep(700000); ++ SnapMode = false; ++ } ++ ++ void* SamplerThread(void* Arg) { ++ const uint32_t Hz = static_cast(reinterpret_cast(Arg) & 0xffff); ++ const bool All = (reinterpret_cast(Arg) >> 16) != 0; ++ const pid_t Pid = getpid(); ++ const std::string Trigger = "/dev/shm/fex-" + std::to_string(Pid) + "-sample-on"; ++ const std::string SnapTrigger = "/dev/shm/fex-" + std::to_string(Pid) + "-snapshot"; ++ for (;;) { ++ if (access(SnapTrigger.c_str(), F_OK) == 0) { ++ unlink(SnapTrigger.c_str()); ++ TakeSnapshot(Pid); ++ continue; ++ } ++ if (access(Trigger.c_str(), F_OK) != 0) { ++ usleep(100000); ++ continue; ++ } ++ if (!OpenRecords(Pid)) { ++ usleep(100000); ++ continue; ++ } ++ usleep(1000000 / Hz); ++ if (FEX::HLE::PtraceEmu::IsAttached()) { ++ continue; ++ } ++ if (All) { ++ if (DIR* D = opendir("/proc/self/task")) { ++ while (auto* E = readdir(D)) { ++ const pid_t Tid = atoi(E->d_name); ++ if (Tid > 0 && Tid != static_cast(syscall(SYS_gettid)) && IsInteresting(Tid)) { ++ syscall(SYS_tgkill, Pid, Tid, SIGPROF); ++ } ++ } ++ closedir(D); ++ } ++ } else { ++ syscall(SYS_tgkill, Pid, Pid, SIGPROF); ++ } ++ } ++ return nullptr; ++ } ++} ++ ++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External) { ++ if (!Hz) { ++ return; ++ } ++ ExternalMode = External; ++ Delegator = Signals; ++ Signals->RegisterHostSignalHandler( ++ SIGPROF, ++ [](FEXCore::Core::InternalThreadState* Thread, int, void*, void* UContext) { ++ if (ExternalMode) { ++ OpenExternalSnaps(); ++ } ++ if (ExternalMode || SnapMode.load(std::memory_order_relaxed)) { ++ uint32_t SIdx = SnapCount.fetch_add(1, std::memory_order_relaxed); ++ const uint32_t Seq = SIdx; ++ if (ExternalMode) { ++ SIdx %= MaxSnaps; ++ } ++ if (Snaps && SIdx < MaxSnaps) { ++ SnapRecord& R = Snaps[SIdx]; ++ R.Tid = static_cast(syscall(SYS_gettid)); ++ R.HostPC = ArchHelpers::Context::GetPc(UContext); ++ if (Thread) { ++ const auto& St = Thread->CurrentFrame->State; ++ R.Rip = St.rip; ++ for (unsigned i = 0; i < 16; ++i) { ++ R.Gregs[i] = St.gregs[i]; ++ } ++ iovec Local {R.Stack, sizeof(R.Stack)}; ++ iovec Remote {reinterpret_cast(St.gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)}; ++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0); ++ ++ const uint64_t Nr = St.gregs[FEXCore::X86State::REG_RAX]; ++ if (Nr == 202 || Nr == 449) { ++ uint64_t Addr = St.gregs[FEXCore::X86State::REG_RDI]; ++ uint64_t Expected = St.gregs[FEXCore::X86State::REG_RDX]; ++ if (Nr == 449) { ++ uint64_t Waiter[3] {}; ++ iovec WL {Waiter, sizeof(Waiter)}; ++ iovec WR {reinterpret_cast(Addr), sizeof(Waiter)}; ++ Addr = process_vm_readv(getpid(), &WL, 1, &WR, 1, 0) == static_cast(sizeof(Waiter)) ? Waiter[1] : 0; ++ Expected = Waiter[0]; ++ } ++ uint32_t Word = 0; ++ iovec FL {&Word, sizeof(Word)}; ++ iovec FR {reinterpret_cast(Addr), sizeof(Word)}; ++ if (Addr && process_vm_readv(getpid(), &FL, 1, &FR, 1, 0) == static_cast(sizeof(Word))) { ++ R.FutexWord = (1ULL << 63) | Word; ++ R.FutexExpected = Expected; ++ R.FutexAddr = Addr; ++ } ++ } ++ } ++ if (ExternalMode) { ++ R.FutexWord = 0; ++ R.FutexExpected = Seq; ++ R.FutexAddr = ArchHelpers::Context::GetSp(UContext); ++ if (Thread && Thread->CTX->IsAddressInCodeBuffer(Thread, R.HostPC)) { ++ R.FutexWord = 1; ++ R.Rip = Thread->CTX->RestoreRIPFromHostPC(Thread, R.HostPC); ++ const auto& Cfg = Delegator->GetConfig(); ++ for (size_t i = 0; i < Cfg.SRAGPRCount && i < 16; ++i) { ++ R.Gregs[i] = ArchHelpers::Context::GetArmReg(UContext, Cfg.SRAGPRMapping[i]); ++ } ++ iovec Local {R.Stack, sizeof(R.Stack)}; ++ iovec Remote {reinterpret_cast(R.Gregs[FEXCore::X86State::REG_RSP]), sizeof(R.Stack)}; ++ process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0); ++ } ++ } ++ } ++ return true; ++ } ++ const uint32_t Idx = Count.fetch_add(1, std::memory_order_relaxed); ++ if (Records && Idx < MaxSamples) { ++ Records[Idx] = {ArchHelpers::Context::GetPc(UContext), ++ static_cast(static_cast(syscall(SYS_gettid))) | (Thread ? (Thread->CurrentFrame->State.rip << 32) : 0)}; ++ } ++ return true; ++ }, ++ true); ++ ++ if (External) { ++ return; ++ } ++ pthread_t T; ++ pthread_attr_t Attr; ++ pthread_attr_init(&Attr); ++ pthread_attr_setdetachstate(&Attr, PTHREAD_CREATE_DETACHED); ++ pthread_create(&T, &Attr, SamplerThread, reinterpret_cast(static_cast(Hz | (AllThreads ? 0x10000 : 0)))); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h +new file mode 100644 +index 000000000..b6b433eca +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SamplingProfiler.h +@@ -0,0 +1,13 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++ ++namespace FEXCore::Core { ++struct InternalThreadState; ++} ++namespace FEX::HLE { ++class SignalDelegator; ++ ++void StartSamplingProfiler(FEX::HLE::SignalDelegator* Signals, uint32_t Hz, bool AllThreads, bool External = false); ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp +index a7dcd128d..830ae3721 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.cpp +@@ -119,6 +119,16 @@ $end_info$ + // TRACE_syscall + // - ptrace unsupported + ++#ifndef PR_SET_SYSCALL_USER_DISPATCH ++#define PR_SET_SYSCALL_USER_DISPATCH 59 ++#define PR_SYS_DISPATCH_OFF 0 ++#define PR_SYS_DISPATCH_ON 1 ++#endif ++#ifndef SYSCALL_DISPATCH_FILTER_ALLOW ++#define SYSCALL_DISPATCH_FILTER_ALLOW 0 ++#define SYSCALL_DISPATCH_FILTER_BLOCK 1 ++#endif ++ + namespace FEX::HLE { + uint64_t SeccompEmulator::Handle(FEXCore::Core::CpuStateFrame* Frame, uint32_t Op, uint32_t flags, void* arg) { + // If seccomp isn't enabled then say so. +@@ -314,6 +324,60 @@ void SeccompEmulator::DeserializeFilters(FEXCore::Core::CpuStateFrame* Frame, in + close(FD); + } + ++void SeccompEmulator::QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, ++ uint64_t SyscallNumber, uint32_t Arch) { ++ siginfo_t Info { ++ .si_signo = SIGSYS, ++ .si_errno = static_cast(Errno), ++ .si_code = Code, ++ }; ++ ++ Info.si_call_addr = reinterpret_cast(PostSyscallRIP); ++ Info.si_syscall = SyscallNumber; ++ Info.si_arch = Arch; ++ ++ Thread->SeccompTrapRIP = PostSyscallRIP; ++ ++ SignalDelegation->PrepareForcedGuestSignal(Thread, SIGSYS); ++ SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true); ++} ++ ++void SeccompEmulator::ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) { ++ uint64_t Mask = 1ULL << (Signal - 1); ++ SignalDelegation->GuestSigProcMask(Thread, SIG_UNBLOCK, &Mask, nullptr); ++ SignalDelegation->UninstallHostHandler(Signal); ++ FHU::Syscalls::tgkill(::getpid(), ::gettid(), Signal); ++} ++ ++SeccompEmulator::ExecuteFilterResult ++SeccompEmulator::ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber) { ++ auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); ++ const auto& SUD = Thread->SyscallUserDispatch; ++ const uint64_t PostSyscallRIP = Thread->Thread->CTX->RestoreRIPFromHostPC(Frame->Thread, JITPC) + 2; ++ ++ if (PostSyscallRIP - SUD.Offset < SUD.Length) { ++ return {false, 0}; ++ } ++ ++ if (SUD.Selector) { ++ uint8_t State {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&State, reinterpret_cast(SUD.Selector), sizeof(State))) { ++ ForceExitSignal(Thread, SIGSEGV); ++ return {true, SyscallNumber}; ++ } ++ if (State == SYSCALL_DISPATCH_FILTER_ALLOW) { ++ return {false, 0}; ++ } ++ if (State != SYSCALL_DISPATCH_FILTER_BLOCK) { ++ ForceExitSignal(Thread, SIGSYS); ++ return {true, SyscallNumber}; ++ } ++ } ++ ++ QueueTrapSignal(Thread, 2 , 0, PostSyscallRIP, SyscallNumber, Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386); ++ return {true, SyscallNumber}; ++} ++ + SeccompEmulator::ExecuteFilterResult + SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args) { + if (!HasFilter(Frame)) { +@@ -330,6 +394,8 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT + ::prctl(PR_SET_NO_NEW_PRIVS, 1L, 0, 0, 0); + } + ++ const uint64_t PostSyscallRIP = RIP + 2; ++ + const auto Arch = Is64BitMode() ? AUDIT_ARCH_X86_64 : AUDIT_ARCH_I386; + bool ShouldLog {}; + uint32_t SeccompResult {}; +@@ -425,18 +491,9 @@ SeccompEmulator::ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JIT + break; + } + case SECCOMP_RET_TRAP: { +- siginfo_t Info { +- .si_signo = SIGSYS, +- .si_errno = static_cast(DataMasked), +- .si_code = 1, // SYS_SECCOMP +- }; +- +- Info.si_call_addr = reinterpret_cast(RIP); +- Info.si_syscall = Args->Argument[0]; +- Info.si_arch = Arch; ++ QueueTrapSignal(Thread, 1 , DataMasked, PostSyscallRIP, Args->Argument[0], Arch); + +- SignalDelegation->QueueSignal(::getpid(), ::gettid(), SIGSYS, &Info, true); +- break; ++ return {true, Args->Argument[0]}; + } + case SECCOMP_RET_ERRNO: { + // errno return is clamped. +@@ -671,7 +728,8 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin + return -EINVAL; + } + +- if (!prog) { ++ sock_fprog UserProg; ++ if (FaultSafeUserMemAccess::CopyFromUser(&UserProg, prog, sizeof(UserProg))) { + return -EFAULT; + } + +@@ -680,12 +738,22 @@ uint64_t SeccompEmulator::SetModeFilter(FEXCore::Core::CpuStateFrame* Frame, uin + return -EACCES; + } + +- if (prog->len > BPF_MAXINSNS || prog->len == 0) { ++ if (UserProg.len > BPF_MAXINSNS || UserProg.len == 0) { + // operation specified SECCOMP_SET_MODE_FILTER, but the filter program pointed to by args was not valid or the length of the filter + // program was zero or exceeded BPF_MAXINSNS (4096) instructions. + return -EINVAL; + } + ++ fextl::vector Instructions(UserProg.len); ++ if (FaultSafeUserMemAccess::CopyFromUser(Instructions.data(), UserProg.filter, UserProg.len * sizeof(sock_filter))) { ++ return -EFAULT; ++ } ++ const sock_fprog LocalProg { ++ .len = UserProg.len, ++ .filter = Instructions.data(), ++ }; ++ prog = &LocalProg; ++ + // Don't interrupt me while I'm jitting. + auto lk = FEXCore::MaskSignalsAndLockMutex(FilterMutex); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h +index a4c7b70e0..31b489216 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Seccomp/SeccompEmulator.h +@@ -61,6 +61,8 @@ public: + }; + ExecuteFilterResult ExecuteFilter(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, FEX::HLE::SyscallArguments* Args); + ++ ExecuteFilterResult ExecuteSyscallUserDispatch(FEXCore::Core::CpuStateFrame* Frame, uint64_t JITPC, uint64_t SyscallNumber); ++ + bool HasFilter(FEXCore::Core::CpuStateFrame* Frame) const { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + return !Thread->Filters.empty(); +@@ -101,6 +103,9 @@ private: + const sock_fprog* GetStrictModeFilter() const; + void KillProcess(ThreadStateObject* Thread); + void KillThread(FEXCore::Core::CpuStateFrame* Thread); ++ void QueueTrapSignal(FEX::HLE::ThreadStateObject* Thread, int Code, uint32_t Errno, uint64_t PostSyscallRIP, uint64_t SyscallNumber, ++ uint32_t Arch); ++ void ForceExitSignal(FEX::HLE::ThreadStateObject* Thread, int Signal); + + // Multiple filter instruction count penalty. + // When multiple filters are installed there is a penalty per filter counted towards the maximum number of instructions. +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index e8e04b056..87b890e19 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -8,6 +8,8 @@ $end_info$ + + #include "LinuxSyscalls/SignalDelegator.h" + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" + + #include + #include +@@ -219,6 +221,10 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore:: + Context->UContextLocation = 0; + Context->SigInfoLocation = 0; + Context->InSyscallInfo = 0; ++ Context->ClearedSyscallInfo = 0; ++ Context->GuestSignalMask = 0; ++ Context->SeccompTrapRIP = 0; ++ Context->SavedJITStackSP = 0; + + // Store fault to top status and then reset it + Context->FaultToTopAndGeneratedException = Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException; +@@ -227,6 +233,8 @@ ArchHelpers::Context::ContextBackup* SignalDelegator::StoreThreadState(FEXCore:: + return Context; + } + ++static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread); ++ + void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thread, void* ucontext, RestoreType Type) { + uint64_t OldSP {}; + if (Type == RestoreType::TYPE_PAUSE) [[unlikely]] { +@@ -315,8 +323,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + uintptr_t NewSP = OldSP; + auto Context = reinterpret_cast(NewSP); + ++ if (Type != RestoreType::TYPE_PAUSE) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ for (size_t i = ThreadObject->TrapSignalFrameCount; i > 0; --i) { ++ if (ThreadObject->TrapSignalFrames[i - 1].ContextBackup == NewSP) { ++ ThreadObject->TrapSignalFrameCount = i - 1; ++ break; ++ } ++ } ++ } ++ + // Restore host state + ArchHelpers::Context::RestoreContext(ucontext, Context); ++ Thread->CurrentFrame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context); ++ ++ { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::SigReturn, 0, Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP], ++ Context->GuestSignalMask); ++ if (Type != RestoreType::TYPE_PAUSE && SignalMaskFix()) { ++ uint64_t NewGuestMask = Context->GuestSignalMask; ++ if (Is64BitMode && Context->UContextLocation) { ++ auto* GuestUContext = reinterpret_cast(Context->UContextLocation); ++ NewGuestMask = GuestUContext->uc_sigmask.val[0] & ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1))); ++ } ++ ThreadObject->SignalInfo.CurrentSignalMask.Val = NewGuestMask; ++ CheckForPendingSignals(ThreadObject); ++ } ++ } ++ ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->JITStackSP = Context->SavedJITStackSP; + + // Reset the guest state + memcpy(&Thread->CurrentFrame->State, &Context->GuestState, sizeof(FEXCore::Core::CPUState)); +@@ -327,7 +363,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + // XXX: Unsupported since it needs state reconstruction + // If we are in the JIT then SRA might need to be restored to values from the context + // We can't currently support this since it might result in tearing without real state reconstruction +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ Frame->InSyscallInfo = ArchHelpers::Context::SavedSyscallInfo(Context); + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); +@@ -343,7 +379,36 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + + bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ ++ const int SigSysCode = Signal == SIGSYS ? static_cast(info)->si_code : 0; ++ const bool IsTrapSignal = (SigSysCode == 1 || SigSysCode == 2 ) && ThreadObject->SeccompTrapRIP && ++ !CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)); ++ if (IsTrapSignal) { ++ const uint64_t GuestRSP = Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RSP]; ++ while (ThreadObject->TrapSignalFrameCount) { ++ const auto& Abandoned = ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount - 1]; ++ if (GuestRSP <= Abandoned.GuestFrame || GuestRSP < Abandoned.GuestRSP) { ++ break; ++ } ++ ThreadObject->JITStackSP = Abandoned.JITStackSP; ++ --ThreadObject->TrapSignalFrameCount; ++ --Thread->CurrentFrame->SignalHandlerRefCounter; ++ } ++ const uint64_t Level = ThreadObject->JITStackSP ? ThreadObject->JITStackSP : Thread->CurrentFrame->ReturningStackLocation; ++ if (Level > ArchHelpers::Context::GetSp(ucontext)) { ++ ArchHelpers::Context::SetSp(ucontext, Level); ++ } ++ } ++ + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); ++ ContextBackup->GuestSignalMask = ThreadObject->SignalInfo.CurrentSignalMask.Val; ++ ++ if (SigSysCode == 1 || SigSysCode == 2 ) { ++ ContextBackup->SeccompTrapRIP = ThreadObject->SeccompTrapRIP; ++ ThreadObject->SeccompTrapRIP = 0; ++ } ++ ContextBackup->SavedJITStackSP = ThreadObject->JITStackSP; + + auto Frame = Thread->CurrentFrame; + auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; +@@ -382,8 +447,13 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { +- ContextBackup->InSyscallInfo = Frame->InSyscallInfo; +- Frame->InSyscallInfo = 0; ++ ThreadObject->JITStackSP = ArchHelpers::Context::GetSp(ucontext); ++ ++ if (Thread->CurrentFrame->InSyscallInfo != 0) { ++ ContextBackup->ClearedSyscallInfo = Thread->CurrentFrame->InSyscallInfo; ++ ContextBackup->Flags |= ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_SYSCALLINFO_CLEARED; ++ Thread->CurrentFrame->InSyscallInfo = 0; ++ } + + if (!IsAddressInDispatcher(OldPC)) { + // This is likely to cause issues but in some cases it isn't fatal +@@ -462,6 +532,14 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + + if (Is64BitMode) { + NewGuestSP = SetupFrame_x64(Thread, ContextBackup, Frame, Signal, HostSigInfo, ucontext, GuestAction, GuestStack, NewGuestSP, eflags); ++ if (IsTrapSignal && ThreadObject->TrapSignalFrameCount < ThreadObject->MaxTrapSignalFrames) { ++ ThreadObject->TrapSignalFrames[ThreadObject->TrapSignalFrameCount++] = { ++ .GuestFrame = NewGuestSP, ++ .GuestRSP = OldGuestSP, ++ .JITStackSP = ContextBackup->SavedJITStackSP, ++ .ContextBackup = reinterpret_cast(ContextBackup), ++ }; ++ } + } else { + const bool SigInfoFrame = (GuestAction->sa_flags & SA_SIGINFO) == SA_SIGINFO; + if (SigInfoFrame) { +@@ -483,8 +561,8 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + // This way signal handlers always go back to their original operating mode. + // Doesn't matter for 32-bit processes as they can only be 32-bit, but does + // matter for 64-bit processes as they could have potentially installed a 32-bit code segment. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; +- Frame->State.ss_idx = 0; ++ Frame->State.cs_idx = Is64BitMode ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; + Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx)); + Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx)); + +@@ -690,7 +768,7 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* + auto SigInfo = *static_cast(Info); + + if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) { +- ERROR_AND_DIE_FMT("Received invalid data to syscall. Crashing now!"); ++ return true; + } + + #ifdef ARCHITECTURE_arm64 +@@ -714,10 +792,21 @@ bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* + + void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObject, int Signal, void* Info, void* UContext) { + auto Thread = ThreadObject->Thread; ++ ++ if (PtraceEmu::TryGuestSignalStop(Thread->CurrentFrame, Signal)) { ++ Thread->CurrentFrame->SynchronousFaultData.FaultToTopAndGeneratedException = false; ++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA); ++ ArchHelpers::Context::SetFillSRASingleInst(UContext, false); ++ ArchHelpers::Context::SetState(UContext, reinterpret_cast(Thread->CurrentFrame)); ++ return; ++ } ++ + ucontext_t* _context = (ucontext_t*)UContext; + auto SigInfo = *static_cast(Info); + + auto MustDeferSignal = (Thread->CurrentFrame->State.DeferredSignalRefCount.Load() != 0); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::HostArrive, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ++ (static_cast(MustDeferSignal) << 32) | static_cast(SigInfo.si_code)); + if (Signal == SIGSEGV && SigInfo.si_code == SEGV_ACCERR && SigInfo.si_addr == reinterpret_cast(&Thread->InterruptFaultPage)) { + if (!MustDeferSignal) { + // We just reached the end of the outermost signal-deferring section and faulted to check for pending signals. +@@ -781,6 +870,8 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again + sigmask_val[0] = GetNewSigMask(Signal); + ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Deferred, Signal, 0, 0); ++ + // Now update the faulting page permissions so it will fault on write. + mprotect(reinterpret_cast(&Thread->InterruptFaultPage), sizeof(Thread->InterruptFaultPage), PROT_NONE); + +@@ -793,6 +884,7 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + // This signal is masked, must defer until the guest updates the signal mask. + // Add it to the pending signal list + ThreadObject->SignalInfo.PendingSignals |= 1ULL << (Signal - 1); ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Masked, Signal, ThreadObject->SignalInfo.CurrentSignalMask.Val, ThreadObject->SignalInfo.PendingSignals); + return; + } + +@@ -814,6 +906,21 @@ void SignalDelegator::HandleGuestSignal(FEX::HLE::ThreadStateObject* ThreadObjec + if (Handler.GuestHandler && + Handler.GuestHandler(Thread, Signal, &SigInfo, UContext, &Handler.GuestAction, &ThreadObject->SignalInfo.GuestAltStack)) { + uint64_t NewMask = GetNewSigMask(Signal); ++ if (SignalMaskFix()) { ++ uint64_t GuestNew = ThreadObject->SignalInfo.CurrentSignalMask.Val | Handler.GuestAction.sa_mask.Val; ++ if (!(Handler.GuestAction.sa_flags & SA_NODEFER)) { ++ GuestNew |= 1ULL << (Signal - 1); ++ } ++ GuestNew &= ~((1ULL << (SIGKILL - 1)) | (1ULL << (SIGSTOP - 1))); ++ ThreadObject->SignalInfo.CurrentSignalMask.Val = GuestNew; ++ NewMask = GuestNew; ++ for (size_t i = 0; i < MAX_SIGNALS; ++i) { ++ if (HostHandlers[i + 1].Required.load(std::memory_order_relaxed)) { ++ NewMask &= ~(1ULL << i); ++ } ++ } ++ } ++ SigTrace::Log(ThreadObject->ThreadInfo.TID, SigTrace::Delivered, Signal, reinterpret_cast(Handler.GuestAction.sigaction_handler.sigaction), NewMask); + + // Update our host signal mask so we don't hit race conditions with signals + // This allows us to maintain the expected signal mask through the guest signal handling and then all the way back again +@@ -961,6 +1068,30 @@ void SignalDelegator::UninstallHostHandler(int Signal) { + ::syscall(SYS_rt_sigaction, Signal, &SignalHandler.OldAction, nullptr, 8); + } + ++void SignalDelegator::ForceGuestSigSegv(uint64_t BadSP) { ++ static std::atomic Logged {false}; ++ if (!Logged.exchange(true, std::memory_order_relaxed)) { ++ LogMan::Msg::EFmt("Cannot write the guest signal frame at stack pointer 0x{:x}; forcing SIGSEGV " ++ "(Linux force_sigsegv). The guest stack pointer is not a live, writable mapping.", ++ BadSP); ++ } ++ ++ SignalHandler& Handler = HostHandlers[SIGSEGV]; ++ Handler.GuestAction.sigaction_handler.handler = SIG_DFL; ++ Handler.OldAction.handler = SIG_DFL; ++ ::signal(SIGSEGV, SIG_DFL); ++ ++ CTX->FlushAndCloseCodeMap(); ++ FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ ++ uint64_t SegvMask = 1ULL << (SIGSEGV - 1); ++ ::syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &SegvMask, nullptr, 8); ++ ::raise(SIGSEGV); ++ ++ ::syscall(SYS_exit, 128 + SIGSEGV); ++ FEX_UNREACHABLE; ++} ++ + void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask) { + bool WasIgnored {}; + bool WasMasked {}; +@@ -995,11 +1126,34 @@ void SignalDelegator::QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* + } + } + ++void SignalDelegator::PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal) { ++ const uint64_t SignalMask = 1ULL << (Signal - 1); ++ const bool Blocked = Thread->SignalInfo.CurrentSignalMask.Val & SignalMask; ++ ++ GuestSigAction Action {}; ++ RegisterGuestSignalHandler(Signal, nullptr, &Action); ++ const bool Ignored = Action.sigaction_handler.handler == SIG_IGN; ++ ++ if (!Blocked && !Ignored) { ++ return; ++ } ++ ++ Action.sigaction_handler.handler = SIG_DFL; ++ RegisterGuestSignalHandler(Signal, &Action, nullptr); ++ if (Blocked) { ++ GuestSigProcMask(Thread, SIG_UNBLOCK, &SignalMask, nullptr); ++ } ++} ++ + SignalDelegator::SignalDelegator(FEXCore::Context::Context* _CTX, const std::string_view ApplicationName, bool SupportsAVX, bool SupportsSVE256) + : CTX {_CTX} + , ApplicationName {ApplicationName} + , SupportsAVX {SupportsAVX} + , SupportsSVE256 {SupportsSVE256} { ++ if (SignalTrace()) { ++ SigTrace::Init(); ++ } ++ + // Signal zero isn't real + HostHandlers[0].Installed = true; + +@@ -1162,23 +1316,36 @@ void SignalDelegator::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + } + } + +-void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { +- FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16); +- +- Thread->SignalInfo.AltStackPtr = nullptr; +- ++void SignalDelegator::ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread) { + stack_t altstack {}; + altstack.ss_flags = SS_DISABLE; +- +- // Uninstall the alt stack + const int Result = sigaltstack(&altstack, nullptr); + if (Result == -1) { + LogMan::Msg::EFmt("Failed to uninstall alternative signal stack {}", strerror(errno)); + } + ++ FEXCore::Allocator::munmap(Thread->SignalInfo.AltStackPtr, SIGSTKSZ * 16); ++ Thread->SignalInfo.AltStackPtr = nullptr; ++ Thread->SignalInfo.AltStackReleaseDeferred = false; ++} ++ ++void SignalDelegator::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ stack_t Current {}; ++ if (sigaltstack(nullptr, &Current) == 0 && (Current.ss_flags & SS_ONSTACK)) { ++ Thread->SignalInfo.AltStackReleaseDeferred = true; ++ } else { ++ ReleaseAltStack(Thread); ++ } ++ + FEXCore::Allocator::UninstallTLSData(Thread->Thread); + } + ++void SignalDelegator::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ if (Thread->SignalInfo.AltStackReleaseDeferred) { ++ ReleaseAltStack(Thread); ++ } ++} ++ + void SignalDelegator::FrontendRegisterHostSignalHandler(int Signal, bool Required) { + // Linux signal handlers are per-process rather than per thread + // Multiple threads could be calling in to this +@@ -1321,6 +1488,7 @@ static void CheckForPendingSignals(const FEX::HLE::ThreadStateObject* Thread) { + if (PendingSignals != 0) { + for (int i = 0; i < 64; ++i) { + if (PendingSignals & (1ULL << i)) { ++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::Reraise, i + 1, Thread->SignalInfo.CurrentSignalMask.Val, Thread->SignalInfo.PendingSignals); + FHU::Syscalls::tgkill(Thread->ThreadInfo.PID, Thread->ThreadInfo.TID, i + 1); + // We might not even return here which is spooky + } +@@ -1361,6 +1529,9 @@ uint64_t SignalDelegator::GuestSigProcMask(FEX::HLE::ThreadStateObject* Thread, + } + + ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &HostMask, nullptr, 8); ++ if (Thread->Thread->CurrentFrame->SignalHandlerRefCounter != 0) { ++ SigTrace::Log(Thread->ThreadInfo.TID, SigTrace::ProcMask, how, *set, Thread->SignalInfo.CurrentSignalMask.Val); ++ } + } + + if (oldset) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +index 43898e700..0d5b5597d 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -65,6 +65,8 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseAltStack(FEX::HLE::ThreadStateObject* Thread); + + /** + * @brief Registers a signal handler for the host to handle a signal +@@ -109,6 +111,10 @@ public: + void UninstallHostHandler(int Signal); + void QueueSignal(pid_t tgid, pid_t tid, int Signal, siginfo_t* info, bool IgnoreMask); + ++ void PrepareForcedGuestSignal(FEX::HLE::ThreadStateObject* Thread, int Signal); ++ ++ [[noreturn]] void ForceGuestSigSegv(uint64_t BadSP); ++ + void SetVDSOSymbols() { + // Get symbols from VDSO. + VDSOPointers = FEX::VDSO::GetVDSOSymbols(); +@@ -187,6 +193,8 @@ private: + FEXCore::Context::Context* CTX; + + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); ++ FEX_CONFIG_OPT(SignalMaskFix, SIGNALMASKFIX); ++ FEX_CONFIG_OPT(SignalTrace, SIGNALTRACE); + const fextl::string ApplicationName; + FEX_CONFIG_OPT(HalfBarrierTSOEnabled, HALFBARRIERTSOENABLED); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +index 38dc524f1..d0bcdbecb 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -7,6 +7,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/Syscalls.h" + + #include + #include +@@ -14,11 +15,15 @@ $end_info$ + #include + #include + #include ++#include + ++#include + #include + #include + #include + #include ++#include ++#include + + namespace FEX::HLE { + constexpr uint32_t X86_SA_RESTORER = 0x04000000; +@@ -106,26 +111,42 @@ template + static void SetXStateInfo(T* xstate, bool is_avx_enabled) { + auto* fpstate = &xstate->fpstate; + +- fpstate->sw_reserved.magic1 = is_avx_enabled ? FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1 : 0; +- fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.magic1 = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_1; + + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_FP | FEXCore::x86_64::fpx_sw_bytes::FEATURE_SSE; + if (is_avx_enabled) { + fpstate->sw_reserved.xfeatures |= FEXCore::x86_64::fpx_sw_bytes::FEATURE_YMM; + } + +- fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if constexpr (std::is_same_v) { ++ if (!is_avx_enabled) { ++ fpstate->sw_reserved.xstate_size = sizeof(FEXCore::x86_64::_libc_fpstate); ++ fpstate->sw_reserved.extended_size = sizeof(FEXCore::x86_64::_libc_fpstate) + sizeof(uint32_t); ++ return; ++ } + +- if (is_avx_enabled) { +- xstate->xstate_hdr.xfeatures = 0; +- xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ const uint32_t UserSize = offsetof(FEXCore::x86_64::xstate, ymmh) + sizeof(FEXCore::x86_64::ymmh_state); ++ fpstate->sw_reserved.xstate_size = UserSize; ++ fpstate->sw_reserved.extended_size = UserSize + sizeof(uint32_t); ++ ++ xstate->xstate_hdr.xfeatures = fpstate->sw_reserved.xfeatures; ++ ++ *reinterpret_cast(reinterpret_cast(fpstate) + UserSize) = ++ FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } else { ++ fpstate->sw_reserved.extended_size = is_avx_enabled ? sizeof(T) : 0; ++ fpstate->sw_reserved.xstate_size = fpstate->sw_reserved.extended_size; ++ if (is_avx_enabled) { ++ xstate->xstate_hdr.xfeatures = 0; ++ xstate->magic2.magic = FEXCore::x86_64::fpx_sw_bytes::FP_XSTATE_MAGIC_2; ++ } + } + } + + void SignalDelegator::ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, + const uint64_t* GuestGPRs, size_t Count, uint64_t Mask) { + #ifdef ARCHITECTURE_arm64 +- const uint32_t Spilled = Context->InSyscallInfo & 0xFFFF; ++ const uint32_t Spilled = ArchHelpers::Context::SavedSyscallInfo(Context) & 0xFFFF; + const bool AllSpilled = Spilled == 0xFFFF; + if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { + return; +@@ -153,14 +174,19 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + auto* guest_uctx = reinterpret_cast(Context->UContextLocation); + [[maybe_unused]] auto* guest_siginfo = reinterpret_cast(Context->SigInfoLocation); + +- // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { ++ CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); ++ ++ if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -176,9 +202,6 @@ void SignalDelegator::RestoreFrame_x64(FEXCore::Core::InternalThreadState* Threa + Frame->State.cs_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.cs_idx)); + Frame->State.ss_cached = Frame->State.CalculateGDTBase(*Frame->State.GetSegmentFromIndex(Frame->State, Frame->State.ss_idx)); + +- // XXX: Full context setting +- CTX->SetFlagsFromCompactedEFLAGS(Thread, guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL]); +- + #define COPY_REG(x) Frame->State.gregs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; + COPY_REG(R8); + COPY_REG(R9); +@@ -256,12 +279,15 @@ void SignalDelegator::RestoreFrame_ia32(FEXCore::Core::InternalThreadState* Thre + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + SigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->sc.ip || Context->FaultToTopAndGeneratedException || Context->SeccompTrapRIP) { + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -345,13 +371,17 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + FEXCore::Core::CpuStateFrame* Frame, void* ucontext) { + RTSigFrame_i32* guest_uctx = reinterpret_cast(Context->UContextLocation); + // If the guest modified the RIP then we need to take special precautions here +- if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { ++ if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException || ++ Context->SeccompTrapRIP) { + + // Restore previous `InSyscallInfo` structure. + Frame->InSyscallInfo = 0; + + // Hack! Go back to the top of the dispatcher top + // This is only safe inside the JIT rather than anything outside of it ++ if (!(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ ArchHelpers::Context::SetSp(ucontext, Context->SavedJITStackSP ? Context->SavedJITStackSP : Frame->ReturningStackLocation); ++ } + ArchHelpers::Context::SetPc(ucontext, Config.AbsoluteLoopTopAddressFillSRA); + ArchHelpers::Context::SetFillSRASingleInst(ucontext, false); + // Set our state register to point to our guest thread data +@@ -431,9 +461,42 @@ void SignalDelegator::RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Th + } + } + ++static bool GuestFrameWritable(uint64_t Begin, uint64_t End) { ++ if (End < Begin) { ++ return false; ++ } ++ ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ ++ constexpr uint64_t PageSize = 4096; ++ constexpr uint64_t MaxPages = 4096; ++ const uint64_t FirstPage = Begin & ~(PageSize - 1); ++ const uint64_t LastPage = End & ~(PageSize - 1); ++ ++ auto lk = FEXCore::MaskSignalsAndLockMutex(VMATracking.Mutex); ++ ++ for (uint64_t Page = FirstPage, PageCount = 0; Page <= LastPage; Page += PageSize, ++PageCount) { ++ if (PageCount >= MaxPages) { ++ return false; ++ } ++ ++ const auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry == VMATracking.VMAs.end()) { ++ return false; ++ } ++ ++ if (!Entry->second.Prot.Writable || (Entry->first + Entry->second.Length) < (Page + PageSize)) { ++ return false; ++ } ++ } ++ ++ return true; ++} ++ + uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* ContextBackup, + FEXCore::Core::CpuStateFrame* Frame, int Signal, siginfo_t* HostSigInfo, void* ucontext, + GuestSigAction* GuestAction, stack_t* GuestStack, uint64_t NewGuestSP, const uint32_t eflags) { ++ const uint64_t RequestedGuestSP = NewGuestSP; + + // Back up past the redzone, which is 128bytes + // 32-bit doesn't have a redzone +@@ -475,6 +538,16 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + ContextBackup->UContextLocation = UContextLocation; + ContextBackup->SigInfoLocation = SigInfoLocation; + ++ const uint64_t UContextEnd = UContextLocation + sizeof(FEXCore::x86_64::ucontext_t); ++ const uint64_t FPStateEnd = ++ FPStateLocation + (SupportsAVX ? sizeof(FEXCore::x86_64::xstate) : sizeof(FEXCore::x86_64::_libc_fpstate)); ++ const uint64_t HostStackEnd = HostStackLocation + sizeof(uint64_t); ++ const uint64_t FrameEnd = std::max({UContextEnd, FPStateEnd, HostStackEnd}); ++ ++ if (!GuestFrameWritable(UContextLocation, FrameEnd)) { ++ ForceGuestSigSegv(RequestedGuestSP); ++ } ++ + FEXCore::x86_64::ucontext_t* guest_uctx = reinterpret_cast(UContextLocation); + siginfo_t* guest_siginfo = reinterpret_cast(SigInfoLocation); + // Store where the host context lives in the guest stack. +@@ -488,7 +561,8 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + auto* xstate = reinterpret_cast(FPStateLocation); + SetXStateInfo(xstate, SupportsAVX); + +- guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_EFL] = eflags; + // This stores the CS/GS/FS selectors. It ALSO stores the SS selector in the top 16 bits...For some reason. + // Despite the naming, the endianness is swapped from what you'd expect. +@@ -568,6 +642,9 @@ uint64_t SignalDelegator::SetupFrame_x64(FEXCore::Core::InternalThreadState* Thr + guest_uctx->uc_stack.ss_sp = GuestStack->ss_sp; + guest_uctx->uc_stack.ss_size = GuestStack->ss_size; + ++ memset(guest_uctx->uc_sigmask.val, 0, sizeof(guest_uctx->uc_sigmask.val)); ++ guest_uctx->uc_sigmask.val[0] = ContextBackup->GuestSignalMask; ++ + // Apparently RAX is always set to zero in case of badly misbehaving C applications and variadics. + Frame->State.gregs[FEXCore::X86State::REG_RAX] = 0; + Frame->State.gregs[FEXCore::X86State::REG_RDI] = Signal; +@@ -643,7 +720,7 @@ uint64_t SignalDelegator::SetupFrame_ia32(FEXCore::Core::InternalThreadState* Th + guest_uctx->sc.err = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->sc.ip = ContextBackup->OriginalRIP; ++ guest_uctx->sc.ip = ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->sc.flags = eflags; + guest_uctx->sc.sp_at_signal = 0; + +@@ -779,7 +856,8 @@ uint64_t SignalDelegator::SetupRTFrame_ia32(FEXCore::Core::InternalThreadState* + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_ERR] = ConvertSignalToError(ucontext, Signal, HostSigInfo); + } + +- guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ContextBackup->OriginalRIP; ++ guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] = ++ ContextBackup->SeccompTrapRIP ? ContextBackup->SeccompTrapRIP : ContextBackup->OriginalRIP; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EFL] = eflags; + guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_UESP] = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + guest_uctx->uc.uc_mcontext.cr2 = 0; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +new file mode 100644 +index 000000000..5db61d312 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.cpp +@@ -0,0 +1,45 @@ ++// SPDX-License-Identifier: MIT ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++Rec* Buf = nullptr; ++std::atomic Idx {0}; ++ ++namespace { ++ std::string PathFor(pid_t Pid) { ++ return "/dev/shm/fex-" + std::to_string(Pid) + "-sigtrace"; ++ } ++} ++ ++void Init() { ++ if (Buf) { ++ return; ++ } ++ const std::string Path = PathFor(getpid()); ++ const int fd = open(Path.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); ++ if (fd < 0) { ++ return; ++ } ++ if (ftruncate(fd, sizeof(Rec) * Recs) != 0) { ++ close(fd); ++ return; ++ } ++ void* Map = mmap(nullptr, sizeof(Rec) * Recs, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ close(fd); ++ if (Map != MAP_FAILED) { ++ Buf = static_cast(Map); ++ } ++} ++ ++void CleanupForExit() { ++ if (!Buf) { ++ return; ++ } ++ unlink(PathFor(getpid()).c_str()); ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +new file mode 100644 +index 000000000..d1a1bb8a6 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalTrace.h +@@ -0,0 +1,54 @@ ++// SPDX-License-Identifier: MIT ++#pragma once ++ ++#include ++#include ++ ++namespace FEX::HLE::SigTrace { ++enum Event : uint16_t { ++ HostArrive = 1, ++ Masked = 2, ++ Deferred = 3, ++ Delivered = 4, ++ SigReturn = 5, ++ ProcMask = 6, ++ Reraise = 7, ++ Kill = 8, ++ Read16 = 9, ++ Write16 = 10, ++ EpollCtl = 11, ++}; ++ ++struct Rec { ++ uint64_t Tsc; ++ uint32_t Tid; ++ uint16_t Ev; ++ uint16_t Sig; ++ uint64_t A; ++ uint64_t B; ++}; ++ ++constexpr uint32_t Recs = 1u << 19; ++extern Rec* Buf; ++extern std::atomic Idx; ++ ++void Init(); ++ ++void CleanupForExit(); ++ ++inline bool Enabled() { ++ return Buf != nullptr; ++} ++ ++inline void Log(uint32_t Tid, uint16_t Ev, uint16_t Sig, uint64_t A, uint64_t B) { ++ if (!Buf) { ++ return; ++ } ++ uint64_t Tsc = 0; ++#if defined(__aarch64__) ++ asm volatile("mrs %0, cntvct_el0" : "=r"(Tsc)); ++#endif ++ Rec& R = Buf[Idx.fetch_add(1, std::memory_order_relaxed) & (Recs - 1)]; ++ R = {Tsc, Tid, Ev, Sig, A, B}; ++} ++} +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 4a77d8716..607ab0b97 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -15,6 +15,8 @@ $end_info$ + + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/Utils/Threads.h" +@@ -235,6 +237,11 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + return -ENOENT; + } + ++ if (PtraceEmu::IsAttached()) { ++ char Resolved[PATH_MAX]; ++ PtraceEmu::RecordExecPath(pathname[0] == '/' ? std::string(pathname) : std::string(realpath(Filename.c_str(), Resolved) ? Resolved : pathname)); ++ } ++ + int pid = getpid(); + + char PidSelfPath[50]; +@@ -332,7 +339,8 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + // - seccomp inheritance + // - FEXServer FD inheritance (unshare(CLONE_NEWNET)) + // - FD_CLOEXEC set on FD on anonymous file FD. +- const bool NeedsEnvpCopy = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || HasSeccomp || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsExecveFD = (IsFDExec && !(IsBinfmtCompatible || IsOtherELF)) || NeedsFDCopy || NeedsLoaderFD; ++ const bool NeedsEnvpCopy = NeedsExecveFD || HasSeccomp; + + // We are trying to execute a shebang handled by a different architecture interpreter (e.g. /usr/bin/python from the host FS). + // In this case we just defer to the kernel. +@@ -348,7 +356,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + } + } + +- if (!IsBinfmtCompatible || NeedsFDCopy) { ++ if (NeedsExecveFD) { + if (NeedsFDCopy) { + // FEX needs the FD to live past execve when binfmt_misc isn't used, + // so duplicate the FD if FD_CLOEXEC is set, which removes the FD_CLOEXEC flag. +@@ -439,9 +447,7 @@ uint64_t ExecveHandler(FEXCore::Core::CpuStateFrame* Frame, const char* pathname + + // It is valid to provide nullptr first argument. + if (*OldArgv) { +- // The direct fallback uses the executable path as argv[0]. An FD-backed load uses the +- // binfmt preserve-argv0 layout, so the caller-supplied argv[0] has to stay in the vector. +- if (!NeedsLoaderFD && !IsFDExec) { ++ if (!IsFDExec && !NeedsLoaderFD) { + ++OldArgv; + } + while (*OldArgv) { +@@ -814,6 +820,9 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler( ++ SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); ++ + ExtendedMetaData = FEX::VolatileMetadata::ParseExtendedVolatileMetadata(FEXCore::Config::Get_EXTENDEDVOLATILEMETADATA()()); + } + +@@ -835,6 +844,14 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + Thread->Thread->CurrentFrame->State.gregs[FEXCore::X86State::REG_RAX] = Result & Mask; + }; + ++ if (FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch.Enabled) [[unlikely]] { ++ const auto Result = SeccompEmulator.ExecuteSyscallUserDispatch(Frame, JITPC, GetArg(Is64Bit, Frame, 0)); ++ if (Result.EarlyReturn) { ++ SetResult(Frame, Result.Result); ++ return; ++ } ++ } ++ + if (SeccompEmulator.HasFilter(Frame)) { + FEX::HLE::SyscallArguments Args { + .Argument = +@@ -856,9 +873,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + } + +- const auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ auto SyscallNum = GetArg(Is64Bit, Frame, 0); ++ ++ uint64_t TraceArgs[6] {}; ++ const bool ReportStops = Is64Bit && PtraceEmu::WantsSyscallStops(); ++ if (ReportStops) { ++ for (unsigned i = 0; i < 6; ++i) { ++ TraceArgs[i] = GetArg(Is64Bit, Frame, i + 1); ++ } ++ SyscallNum = PtraceEmu::SyscallEntryStop(Frame, SyscallNum, TraceArgs); ++ } ++ + if (SyscallNum >= Definitions.size()) { +- SetResult(Frame, -ENOSYS); ++ uint64_t Result = -ENOSYS; ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ SetResult(Frame, Result); + return; + } + +@@ -891,6 +922,23 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + #ifdef DEBUG_STRACE + Strace(Frame, Result); + #endif ++ ++ if constexpr (Is64Bit) { ++ PtraceEmu::ApplyPendingFlush(Frame); ++ if (Result == 0 && (SyscallNum == 56 || SyscallNum == 57 || SyscallNum == 58 || SyscallNum == 435)) { ++ constexpr uint64_t CloneVM = 0x100; ++ uint64_t Flags = 0; ++ if (SyscallNum == 56) { ++ Flags = GetArg(Is64Bit, Frame, 1); ++ } else if (SyscallNum == 435) { ++ Flags = *reinterpret_cast(GetArg(Is64Bit, Frame, 1)); ++ } ++ PtraceEmu::OnForkedChild((Flags & CloneVM) != 0); ++ } ++ if (ReportStops && PtraceEmu::WantsSyscallStops()) { ++ Result = PtraceEmu::SyscallExitStop(Frame, SyscallNum, TraceArgs, Result); ++ } ++ } + SetResult(Frame, Result); + } + +@@ -906,9 +954,12 @@ void SyscallHandler::HandleSyscall(FEXCore::Core::CpuStateFrame* Frame) { + HandleSyscallImpl(Frame, JITPC); + } + +- // Skip past the `syscall` or `int 0x80` instruction. Both of which are 2-bytes. + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); +- Thread->Thread->CurrentFrame->State.rip += 2; ++ if (const uint64_t NewRip = PtraceEmu::TakePendingRip()) { ++ Thread->Thread->CurrentFrame->State.rip = NewRip; ++ } else { ++ Thread->Thread->CurrentFrame->State.rip += 2; ++ } + } + + #ifdef DEBUG_STRACE +@@ -969,6 +1020,8 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + // Code maps are closed upon fork in the child + FM.SetProtectedCodeMapFD(-1); + ++ FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(LiveThread)->SyscallUserDispatch = {}; ++ + VMATracking.Mutex.StealAndDropActiveLocks(); + CodeCachePatchingMutex.StealAndDropActiveLocks(); + } else { +@@ -985,10 +1038,16 @@ void SyscallHandler::UnlockAfterFork(FEXCore::Core::InternalThreadState* LiveThr + void SyscallHandler::RegisterTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->RegisterTLSState(Thread); + ThunkHandler->RegisterTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(Thread); + } + + void SyscallHandler::UninstallTLSState(FEX::HLE::ThreadStateObject* Thread) { + SignalDelegation->UninstallTLSState(Thread); ++ FEX::HLE::ThreadManager::SetCurrentThreadObject(nullptr); ++} ++ ++void SyscallHandler::ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread) { ++ SignalDelegation->ReleaseDeferredTLSState(Thread); + } + + static bool isHEX(char c) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +index f55bce4fc..d643b4975 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.h +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/ThreadManager.h" + #include "LinuxSyscalls/Seccomp/SeccompEmulator.h" ++#include "LinuxSyscalls/SMCHotPages.h" + #include "LinuxSyscalls/SyscallsVMATracking.h" + #include "ArchHelpers/MContext.h" + +@@ -203,6 +204,7 @@ public: + FEX_CONFIG_OPT(RootFSPath, ROOTFS); + FEX_CONFIG_OPT(Is64BitMode, IS64BIT_MODE); + FEX_CONFIG_OPT(SMCChecks, SMCCHECKS); ++ FEX_CONFIG_OPT(SMCHotPageFaults, SMCHOTPAGEFAULTS); + FEX_CONFIG_OPT(NeedsSeccomp, NEEDSSECCOMP); + FEX_CONFIG_OPT(EnableCodeCaching, ENABLECODECACHINGWIP); + FEX_CONFIG_OPT(EnableDiskCache, DISKCACHE); +@@ -287,8 +289,13 @@ public: + + ///// VMA (Virtual Memory Area) tracking ///// + static bool HandleSegfault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* info, void* ucontext); ++ static void InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping); + void MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + void ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length); ++ bool IsSMCHotPage(uint64_t Address) override; ++ ++ void PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length); + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) override; + std::optional + LookupExecutableFileSection(FEXCore::Core::InternalThreadState* Thread, uint64_t GuestAddr) final override; +@@ -304,6 +311,7 @@ public: + + void RegisterTLSState(FEX::HLE::ThreadStateObject* Thread); + void UninstallTLSState(FEX::HLE::ThreadStateObject* Thread); ++ void ReleaseDeferredTLSState(FEX::HLE::ThreadStateObject* Thread); + + SourcecodeResolver* GetSourcecodeResolver() override { + return this; +@@ -363,6 +371,8 @@ private: + // std::mutex CodeCachePatchingMutex; + FEXCore::ForkableUniqueMutex CodeCachePatchingMutex; + ++ SMCHotPageTracker SMCHotPages; ++ + FEX::CodeLoader* LocalLoader {}; + bool NeedToCheckXID {true}; + +@@ -607,11 +617,13 @@ uint64_t GetDentsEmulation(int fd, T* dirp, uint32_t count); + namespace FaultSafeUserMemAccess { + // These are little helper functions for cases when FEX needs to copy data to or from the application in a robust fashion. + // CopyFromUser and CopyToUser are memcpy routines that expect to safely SIGSEGV when reading or writing application memory respectively. +- // Returns zero if the memcpy completed, or crashes with SIGABRT and a log message if it faults. + [[nodiscard]] + size_t CopyFromUser(void* Dest, const void* Src, size_t Size); + [[nodiscard]] + size_t CopyToUser(void* Dest, const void* Src, size_t Size); ++ ++ [[nodiscard]] ++ bool IsStringReadable(const char* Src); + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED && defined(ARCHITECTURE_arm64) + // These helpers just check if the user pointer is readable and writable. + // This is useful in an assert build that can be safely sprinkled through the syscall handler without overhead in release builds. +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +index 9acf01ff5..1601de1ef 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FD.cpp +@@ -38,6 +38,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(open, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Open(pathname, flags, mode); + SYSCALL_ERRNO(); +@@ -59,6 +62,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(access, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Access(pathname, mode); + SYSCALL_ERRNO(); + }); +@@ -80,22 +86,34 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(openat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfs, const char* pathname, int flags, uint32_t mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + flags = FEX::HLE::RemapFromX86Flags(flags); + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Openat(dirfs, pathname, flags, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(readlinkat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlinkat(dirfd, pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat(dirfd, pathname, mode); + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL(faccessat2, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, int mode, int flags) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.FAccessat2(dirfd, pathname, mode, flags); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +index 64c9aae22..9eee296ec 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/FS.cpp +@@ -52,6 +52,9 @@ void RegisterFS(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(readlink, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, char* buf, size_t bufsiz) -> uint64_t { ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Readlink(pathname, buf, bufsiz); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +index 1b61282d3..f83006c0a 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Info.cpp +@@ -6,6 +6,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + +@@ -34,9 +35,11 @@ using cap_user_header_t = void*; + using cap_user_data_t = void*; + + void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* buf) -> uint64_t { ++ REGISTER_SYSCALL_IMPL(uname, [](FEXCore::Core::CpuStateFrame* Frame, struct utsname* ubuf) -> uint64_t { + auto Thread = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame); + ++ struct utsname Out {}; ++ auto buf = &Out; + struct utsname Local {}; + if (::uname(&Local) == 0) { + memcpy(buf->nodename, Local.nodename, sizeof(Local.nodename)); +@@ -66,6 +69,9 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + // Tell the guest that we are a 64bit kernel + strcpy(buf->machine, "x86_64"); + } ++ if (FaultSafeUserMemAccess::CopyToUser(ubuf, &Out, sizeof(Out))) { ++ return -EFAULT; ++ } + return 0; + }); + +@@ -97,13 +103,14 @@ void RegisterInfo(FEX::HLE::SyscallHandler* Handler) { + ptrace, [](FEXCore::Core::CpuStateFrame* Frame, int /*enum __ptrace_request*/ request, pid_t pid, void* addr, void* data) -> uint64_t { + uint64_t Result {}; + ++ if (PtraceEmu::HandleRequest(request, pid, addr, data, &Result)) { ++ return Result; ++ } ++ + switch (request) { + case PTRACE_PEEKTEXT: + case PTRACE_PEEKDATA: +- case PTRACE_POKETEXT: +- case PTRACE_POKEDATA: + case PTRACE_ATTACH: +- case PTRACE_DETACH: + // Passthrough these requests. Allows Wine to run the Ubisoft launcher. + Result = ::syscall(SYSCALL_DEF(ptrace), request, pid, addr, data); + SYSCALL_ERRNO(); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 21816674e..602e17570 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -9,6 +9,13 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" ++#include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/SignalTrace.h" ++ ++#include ++#include ++#include ++#include + + #include + #include +@@ -252,8 +259,23 @@ uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t a + } + + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(read, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(read), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Read16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); ++ REGISTER_SYSCALL_IMPL(write, [](FEXCore::Core::CpuStateFrame* Frame, int fd, const void* buf, size_t count) -> uint64_t { ++ uint64_t Result = ::syscall(SYSCALL_DEF(write), fd, buf, count); ++ if (count == 16 && SigTrace::Enabled()) { ++ const int Errno = errno; ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Write16, fd, Result, Result == 16 ? *static_cast(buf) : (1ULL << 63) | Errno); ++ } ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(lseek, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_yield, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(msync, SyscallPassthrough3); +@@ -264,14 +286,26 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(socket, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(connect, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(sendto, SyscallPassthrough6); +- REGISTER_SYSCALL_IMPL(recvfrom, SyscallPassthrough6); ++ REGISTER_SYSCALL_IMPL(recvfrom, ++ [](FEXCore::Core::CpuStateFrame* Frame, int sockfd, void* buf, size_t len, int flags, struct sockaddr* src_addr, ++ socklen_t* addrlen) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, len); ++ uint64_t Result = ::syscall(SYSCALL_DEF(recvfrom), sockfd, buf, len, flags, src_addr, addrlen); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(shutdown, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(bind, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(listen, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(getsockname, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(getpeername, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(socketpair, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(kill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(kill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, pid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(kill), pid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(semget, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(msgget, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(msgsnd, SyscallPassthrough4); +@@ -334,7 +368,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(fgetxattr, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL(flistxattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(fremovexattr, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(tkill, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(tkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, 0); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tkill), tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(sched_setaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getaffinity, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(io_setup, SyscallPassthrough2); +@@ -344,7 +384,13 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(remap_file_pages, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(timer_getoverrun, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(timer_delete, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(tgkill, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(tgkill, [](FEXCore::Core::CpuStateFrame* Frame, pid_t tgid, pid_t tid, int sig) -> uint64_t { ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::Kill, sig, tid, tgid); ++ } ++ uint64_t Result = ::syscall(SYSCALL_DEF(tgkill), tgid, tid, sig); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL(mbind, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(set_mempolicy, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(get_mempolicy, SyscallPassthrough5); +@@ -459,7 +505,11 @@ namespace x64 { + RegisterCommon(Handler); + REGISTER_SYSCALL_IMPL_X64(ftruncate, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(ioctl, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL_X64(pread_64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, size_t count, off_t offset) -> uint64_t { ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); ++ uint64_t Result = ::syscall(SYSCALL_DEF(pread_64), fd, buf, count, offset); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(pwrite_64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(readv, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(writev, SyscallPassthrough3); +@@ -473,7 +523,14 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(recvmsg, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL_X64(setsockopt, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X64(getsockopt, SyscallPathPassthrough5); +- REGISTER_SYSCALL_IMPL_X64(wait4, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(wait4, [](FEXCore::Core::CpuStateFrame* Frame, pid_t pid, int* status, int options, struct rusage* ru) -> uint64_t { ++ uint64_t Result; ++ do { ++ Result = ::syscall(SYSCALL_DEF(wait4), pid, status, options, ru); ++ Result = Result == -1 ? -errno : Result; ++ } while (static_cast(Result) > 0 && PtraceEmu::FixupWaitStatus(static_cast(Result), status)); ++ SYSCALL_ERRNO(); ++ }); + REGISTER_SYSCALL_IMPL_X64(semop, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(getrlimit, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X64(getrusage, SyscallPassthrough2); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +index 8723026ef..1956b0d52 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Signals.cpp +@@ -25,13 +25,27 @@ struct GuestSigAction; + namespace FEX::HLE { + void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(rt_sigprocmask, [](FEXCore::Core::CpuStateFrame* Frame, int how, const uint64_t* set, uint64_t* oldset) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), +- how, set, oldset); ++ uint64_t NewSet; ++ uint64_t OldSet; ++ if (set && FaultSafeUserMemAccess::CopyFromUser(&NewSet, set, sizeof(NewSet))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigProcMask( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), how, set ? &NewSet : nullptr, oldset ? &OldSet : nullptr); ++ if (Result == 0 && oldset && FaultSafeUserMemAccess::CopyToUser(oldset, &OldSet, sizeof(OldSet))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigpending, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* set, size_t sigsetsize) -> uint64_t { +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending(FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), set, +- sigsetsize); ++ uint64_t Pending {}; ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->GuestSigPending( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), &Pending, sigsetsize); ++ if (Result == 0 && FaultSafeUserMemAccess::CopyToUser(set, &Pending, std::min(sigsetsize, sizeof(Pending)))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL(rt_sigsuspend, [](FEXCore::Core::CpuStateFrame* Frame, uint64_t* unewset, size_t sigsetsize) -> uint64_t { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +index 2c3edeef1..5ce7ee8bd 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Stubs.cpp +@@ -27,7 +27,9 @@ struct CpuStateFrame; + + namespace FEX::HLE { + void RegisterStubs(FEX::HLE::SyscallHandler* Handler) { +- REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { SYSCALL_STUB(restart_syscall); }); ++ REGISTER_SYSCALL_IMPL(restart_syscall, [](FEXCore::Core::CpuStateFrame* Frame) -> uint64_t { ++ return -EINTR; ++ }); + + REGISTER_SYSCALL_IMPL(rseq, [](FEXCore::Core::CpuStateFrame* Frame, struct rseq* rseq, uint32_t rseq_len, int flags, uint32_t sig) -> uint64_t { + // We don't support this +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +index 068fee23e..5f4a60480 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Thread.cpp +@@ -8,6 +8,7 @@ $end_info$ + #include "CodeLoader.h" + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -43,6 +44,12 @@ $end_info$ + #include + #include + ++#ifndef PR_SET_SYSCALL_USER_DISPATCH ++#define PR_SET_SYSCALL_USER_DISPATCH 59 ++#define PR_SYS_DISPATCH_OFF 0 ++#define PR_SYS_DISPATCH_ON 1 ++#endif ++ + ARG_TO_STR(idtype_t, "%u") + + namespace FEX::HLE { +@@ -500,6 +507,30 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return FEX::HLE::_SyscallHandler->SeccompEmulator.Handle(Frame, Operation, 0, reinterpret_cast(arg3)); + } + case PR_GET_SECCOMP: return FEX::HLE::_SyscallHandler->SeccompEmulator.GetSeccomp(Frame); ++ case PR_SET_SYSCALL_USER_DISPATCH: { ++ auto& SUD = FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame)->SyscallUserDispatch; ++ switch (arg2) { ++ case PR_SYS_DISPATCH_OFF: ++ if (arg3 || arg4 || arg5) { ++ return -EINVAL; ++ } ++ SUD = {}; ++ return 0; ++ case PR_SYS_DISPATCH_ON: ++ if (arg3 && arg3 + arg4 <= arg3) { ++ return -EINVAL; ++ } ++ if (arg5 && arg5 >= SyscallHandler::TASK_MAX_64BIT) { ++ return -EFAULT; ++ } ++ SUD.Offset = arg3; ++ SUD.Length = arg4; ++ SUD.Selector = arg5; ++ SUD.Enabled = true; ++ return 0; ++ default: return -EINVAL; ++ } ++ } + case PR_GET_AUXV: { + if (arg4 || arg5) { + return -EINVAL; +@@ -532,6 +563,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.gs_cached = addr; ++ Frame->State.gs_idx = 0; + Result = 0; + break; + case 0x1002: // ARCH_SET_FS +@@ -540,22 +572,27 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + return -EPERM; + } + Frame->State.fs_cached = addr; ++ Frame->State.fs_idx = 0; + Result = 0; + break; + case 0x1003: // ARCH_GET_FS +- *reinterpret_cast(addr) = Frame->State.fs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.fs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x1004: // ARCH_GET_GS +- *reinterpret_cast(addr) = Frame->State.gs_cached; +- Result = 0; ++ Result = FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(addr), &Frame->State.gs_cached, sizeof(uint64_t)) ? -EFAULT : 0; + break; + case 0x3001: // ARCH_CET_STATUS + Result = -EINVAL; // We don't support CET, return EINVAL + break; + case 0x1011: // ARCH_GET_CPUID ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return 1; ++ } + return (Frame->State.CoreFlags & FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED) == FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED ? 1 : 0; + case 0x1012: // ARCH_SET_CPUID ++ if (!FEX::HLE::_SyscallHandler->TM.EnableCPUIDFaulting()) { ++ return -ENODEV; ++ } + if (addr == 0) { + // Disable CPUID (thus enabling CPUID faulting) + Frame->State.CoreFlags = Frame->State.CoreFlags & ~FEXCore::Core::CoreFlagsEnum::CPUID_ENABLED; +@@ -584,6 +621,7 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + // Save telemetry if we're exiting. + FEX::HLE::_SyscallHandler->GetSignalDelegator()->SaveTelemetry(); + FEX::HLE::_SyscallHandler->TM.CleanupForExit(); ++ FEX::HLE::SigTrace::CleanupForExit(); + + syscall(SYSCALL_DEF(exit_group), status); + // This will never be reached +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index 5d6c850d8..f9e85a26f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -42,6 +42,40 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + } + } + ++void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, ++ const FEX::HLE::VMATracking::VMAEntry& Mapping) { ++ auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }; ++ ++ if (Mapping.Flags.Shared) { ++ LOGMAN_THROW_A_FMT(Mapping.Resource, "VMA tracking error"); ++ ++ auto Offset = FaultBase - EntryBase + Mapping.Offset; ++ ++ auto VMA = Mapping.Resource->FirstVMA; ++ LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); ++ ++ do { ++ if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { ++ auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; ++ ++ if (VMA->Prot.Writable) { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBaseMirrored, _SyscallHandler->SMCHotPageFaults()); ++ } ++ } while ((VMA = VMA->ResourceNextVMA)); ++ } else { ++ _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); ++ _SyscallHandler->SMCHotPages.RecordFault(FaultBase, _SyscallHandler->SMCHotPageFaults()); ++ } ++} ++ + // Handles segfaults from: + // - call-ret shadow stack overflow + // - guest-side self-modifying code (SMC) +@@ -52,9 +86,11 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); + auto CallRetStackInfo = ThreadObject->GetCallRetStackInfo(); + if (FaultAddress >= CallRetStackInfo.AllocationBase && FaultAddress < CallRetStackInfo.AllocationEnd) { +- // Reset REG_CALLRET_SP to the default location to allow for underflows/overflows +- ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); +- return true; ++ const uint64_t CallRetSP = ArchHelpers::Context::GetArmReg(ucontext, 25); ++ if (FaultAddress - (CallRetSP - 16) < 32) { ++ ArchHelpers::Context::SetArmReg(ucontext, 25, CallRetStackInfo.DefaultLocation); ++ return true; ++ } + } + + { +@@ -84,41 +120,16 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + + auto FaultBase = FEXCore::AlignDown(FaultAddress, FEXCore::Utils::FEX_PAGE_SIZE); +- +- auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { +- auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); +- LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); +- }; +- +- if (Entry->second.Flags.Shared) { +- LOGMAN_THROW_A_FMT(Entry->second.Resource, "VMA tracking error"); +- +- auto Offset = FaultBase - Entry->first + Entry->second.Offset; +- +- auto VMA = Entry->second.Resource->FirstVMA; +- LOGMAN_THROW_A_FMT(VMA, "VMA tracking error"); +- +- // Flush all mirrors, remap the page writable as needed +- do { +- if (VMA->Offset <= Offset && (VMA->Offset + VMA->Length) > Offset) { +- auto FaultBaseMirrored = Offset - VMA->Offset + VMA->Base; +- +- if (VMA->Prot.Writable) { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBaseMirrored, FEXCore::Utils::FEX_PAGE_SIZE); +- } +- } +- } while ((VMA = VMA->ResourceNextVMA)); +- } else { +- _SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE, UnprotectRegionCallback); +- } ++ InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); + + FEXCORE_PROFILE_INSTANT_INCREMENT(Thread, AccumulatedSMCCount, 1); + ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress > MaxStoreSize ? FaultAddress - MaxStoreSize : 0; ++ + auto CTX = Thread->CTX; + if (CTX->IsAddressInCodeBuffer(Thread, ArchHelpers::Context::GetPc(ucontext)) && !CTX->IsCurrentBlockSingleInst(Thread) && +- CTX->IsAddressInCurrentBlock(Thread, FaultAddress & FEXCore::Utils::FEX_PAGE_MASK, FEXCore::Utils::FEX_PAGE_SIZE)) { ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { + // If we are not in a single-instruction block, and the SMC write address could intersect with the current block, + // reconstruct the context and repeat the faulting instruction as a single-instruction block so any SMC it performs + // is immediately picked up. +@@ -134,6 +145,48 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThreadState* Thread, const void* Buf, size_t Length) { ++ if (SMCChecks != FEXCore::Config::CONFIG_SMC_MTRACK || Length == 0) [[likely]] { ++ return; ++ } ++ ++ const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); ++ const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? ++ UINT64_MAX : ++ reinterpret_cast(Buf) + Length - 1; ++ const uint64_t End = FEXCore::AlignDown(Last, FEXCore::Utils::FEX_PAGE_SIZE) + (Last >= UINT64_MAX - FEXCore::Utils::FEX_PAGE_SIZE ? 0 : FEXCore::Utils::FEX_PAGE_SIZE); ++ ++ auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ auto Entry = VMATracking.VMAs.upper_bound(Start); ++ if (Entry != VMATracking.VMAs.begin() && std::prev(Entry)->first + std::prev(Entry)->second.Length > Start) { ++ --Entry; ++ } ++ ++ for (; Entry != VMATracking.VMAs.end() && Entry->first < End; ++Entry) { ++ const auto& Mapping = Entry->second; ++ if (!Mapping.Prot.Writable || !(Mapping.Prot.Executable || Mapping.Flags.Shared)) [[likely]] { ++ continue; ++ } ++ const uint64_t From = std::max(Start, Entry->first); ++ const uint64_t To = std::min(End, Entry->first + Mapping.Length); ++ if (Mapping.Flags.Shared) { ++ for (uint64_t Page = From; Page < To; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ InvalidateWrittenCodePage(Thread, Page, Entry->first, Mapping); ++ } ++ } else { ++ TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ } ++} ++ ++bool SyscallHandler::IsSMCHotPage(uint64_t Address) { ++ return SMCHotPages.IsHot(Address); ++} ++ + void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState* Thread, uint64_t Start, uint64_t Length) { + const auto Base = Start & FEXCore::Utils::FEX_PAGE_MASK; + const auto Top = FEXCore::AlignUp(Start + Length, FEXCore::Utils::FEX_PAGE_SIZE); +@@ -143,6 +196,18 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + return; + } + ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ if (SMCHotPages.IsHot(Page)) { ++ if (Page > Base) { ++ MarkGuestExecutableRange(Thread, Base, Page - Base); ++ } ++ if (Page + FEXCore::Utils::FEX_PAGE_SIZE < Top) { ++ MarkGuestExecutableRange(Thread, Page + FEXCore::Utils::FEX_PAGE_SIZE, Top - (Page + FEXCore::Utils::FEX_PAGE_SIZE)); ++ } ++ return; ++ } ++ } ++ + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + + // Find the first mapping at or after the range ends, or ::end(). +@@ -407,16 +472,24 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto lk = FEXCore::GuardSignalDeferringSectionWithFallback(VMATracking.Mutex, Thread); + +- if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ if (!Is64Bit) { + Result = Get32BitAllocator()->Munmap(addr, length); + if (FEX::HLE::HasSyscallError(Result)) { + return Result; + } + } else { ++ constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ const uint64_t Addr = reinterpret_cast(addr); ++ if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { ++ return -EINVAL; ++ } + Result = ::munmap(addr, length); + if (Result == -1) { + return -errno; + } ++ if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { ++ Get32BitAllocator()->TrackUnmapped(addr, length); ++ } + } + TrackMunmap(Thread, addr, length); + PendingResourceDeletion = VMATracking.HasPendingResourceDeletions(); +@@ -514,6 +587,21 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); ++ ++ fextl::vector UnlockedCode; ++ constexpr uint64_t MaxUnlockedCodePages = 64; ++ const auto Base = reinterpret_cast(addr) & FEXCore::Utils::FEX_PAGE_MASK; ++ const auto Top = FEXCore::AlignUp(reinterpret_cast(addr) + len, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (SMCChecks == FEXCore::Config::CONFIG_SMC_MTRACK && SMCHotPageFaults() && (prot & PROT_WRITE) && (prot & PROT_EXEC) && ++ Top > Base && (Top - Base) / FEXCore::Utils::FEX_PAGE_SIZE <= MaxUnlockedCodePages) { ++ for (auto Page = Base; Page < Top; Page += FEXCore::Utils::FEX_PAGE_SIZE) { ++ auto Entry = VMATracking.FindVMAEntry(Page); ++ if (Entry != VMATracking.VMAs.end() && Entry->second.Prot.Executable && !Entry->second.Prot.Writable) { ++ UnlockedCode.push_back(Page); ++ } ++ } ++ } ++ + Result = ::mprotect(addr, len, prot); + if (Result == -1) { + return -errno; +@@ -523,6 +611,10 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + if (prot & PROT_WRITE) { + ProtectWritableAliasOfCode(reinterpret_cast(addr), FEXCore::AlignUp(len, FEXCore::Utils::FEX_PAGE_SIZE)); + } ++ ++ for (auto Page : UnlockedCode) { ++ SMCHotPages.MarkHot(Page); ++ } + } + + InvalidateCodeRangeIfNecessary(Thread, reinterpret_cast(addr), len, false); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 8e7d466ed..2e59f2fb5 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" +@@ -158,6 +159,16 @@ void ThreadManager::StatAlloc::UnlockAfterFork(FEXCore::Core::InternalThreadStat + ThreadObject->Thread->ThreadStats = AllocateSlot(ThreadObject->ThreadInfo.TID); + } + ++static thread_local FEX::HLE::ThreadStateObject* CurrentThreadObject {}; ++ ++FEX::HLE::ThreadStateObject* ThreadManager::GetCurrentThreadObject() { ++ return CurrentThreadObject; ++} ++ ++void ThreadManager::SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread) { ++ CurrentThreadObject = Thread; ++} ++ + uint64_t ThreadManager::SetSignalMask(uint64_t Mask) { + ::syscall(SYSCALL_DEF(rt_sigprocmask), SIG_SETMASK, &Mask, &Mask, 8); + return Mask; +@@ -197,6 +208,16 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + Frame->State.callret_sp = ThreadStateObject->GetCallRetStackInfo().DefaultLocation; + + ThreadStateObject->Thread->FrontendPtr = ThreadStateObject; ++ ++ { ++ static std::atomic ThreadCount {0}; ++ FEX_CONFIG_OPT(ProfileSampleHz, PROFILESAMPLEHZ); ++ FEX_CONFIG_OPT(ProfileSampleAllThreads, PROFILESAMPLEALLTHREADS); ++ FEX_CONFIG_OPT(ProfileSampleMinThreads, PROFILESAMPLEMINTHREADS); ++ if (ProfileSampleHz() && ThreadCount.fetch_add(1) + 1 == std::max(ProfileSampleMinThreads(), 1)) { ++ StartSamplingProfiler(SignalDelegation, ProfileSampleHz(), ProfileSampleAllThreads(), ProfileSampleMinThreads() == 0); ++ } ++ } + if (ProfileStats()) { + ThreadStateObject->Thread->ThreadStats = Stat.AllocateSlot(ThreadStateObject->ThreadInfo.TID); + } +@@ -222,8 +243,8 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + } + } else { + // Without any thread data to inherit, setup the default gdt. +- // Default code segment indexes match the numbers that the Linux kernel uses. +- Frame->State.cs_idx = FEXCore::Core::CPUState::DEFAULT_USER_CS << 3; ++ Frame->State.cs_idx = ++ Is64BitMode() ? FEXCore::Core::CPUState::DEFAULT_USER_CS_SEL : FEXCore::Core::CPUState::DEFAULT_USER32_CS_SEL; + auto GDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.cs_idx); + FEXCore::Core::CPUState::SetGDTBase(GDT, 0); + FEXCore::Core::CPUState::SetGDTLimit(GDT, 0xF'FFFFU); +@@ -237,6 +258,14 @@ ThreadManager::CreateThread(const FEXCore::Core::CPUState* NewThreadState, uint6 + GDT->L = 0; // L = Long Mode = 32-bit + GDT->D = 1; // D = Default Operand Size = 32-bit + } ++ ++ Frame->State.ss_idx = FEXCore::Core::CPUState::DEFAULT_USER_DS_SEL; ++ auto SSGDT = FEXCore::Core::CPUState::GetSegmentFromIndex(Frame->State, Frame->State.ss_idx); ++ FEXCore::Core::CPUState::SetGDTBase(SSGDT, 0); ++ FEXCore::Core::CPUState::SetGDTLimit(SSGDT, 0xF'FFFFU); ++ SSGDT->L = 0; ++ SSGDT->D = 1; ++ Frame->State.ss_cached = FEXCore::Core::CPUState::CalculateGDTBase(*SSGDT); + } + + if (InheritThread) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 408cddf71..0a46703ca 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -15,6 +15,7 @@ $end_info$ + + #include + #include ++#include + #include + #include + #include +@@ -68,6 +69,7 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + SignalDelegator* Delegator {}; + + void* AltStackPtr {}; ++ bool AltStackReleaseDeferred {}; + stack_t GuestAltStack { + .ss_sp = nullptr, + .ss_flags = SS_DISABLE, // By default the guest alt stack is disabled +@@ -93,6 +95,27 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + fextl::vector Filters {}; + std::atomic PrctlSetPending {false}; + ++ uint64_t SeccompTrapRIP {}; ++ ++ struct { ++ uint64_t Offset; ++ uint64_t Length; ++ uint64_t Selector; ++ bool Enabled; ++ } SyscallUserDispatch {}; ++ ++ uint64_t JITStackSP {}; ++ ++ struct TrapSignalFrame { ++ uint64_t GuestFrame; ++ uint64_t GuestRSP; ++ uint64_t JITStackSP; ++ uint64_t ContextBackup; ++ }; ++ static constexpr size_t MaxTrapSignalFrames = 16; ++ TrapSignalFrame TrapSignalFrames[MaxTrapSignalFrames] {}; ++ size_t TrapSignalFrameCount {}; ++ + // personality emulation. + uint32_t persona {}; + +@@ -190,6 +213,11 @@ public: + return static_cast(Thread->FrontendPtr); + } + ++ static FEX::HLE::ThreadStateObject* GetCurrentThreadObject(); ++ static void SetCurrentThreadObject(FEX::HLE::ThreadStateObject* Thread); ++ ++ FEX_CONFIG_OPT(EnableCPUIDFaulting, ENABLECPUIDFAULTING); ++ + FEX::HLE::ThreadStateObject* CreateThread(const FEXCore::Core::CPUState* NewThreadState = nullptr, uint64_t ParentTID = 0, + FEX::HLE::ThreadStateObject* InheritThread = nullptr); + void TrackThread(FEX::HLE::ThreadStateObject* Thread) { +@@ -220,29 +248,38 @@ public: + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ const bool HadCode = CTX->InvalidateCodeBuffersCodeRange(Start, Length); ++ if (HadCode) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + } + + void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length, + FEXCore::Context::CodeRangeInvalidationFn after_callback) { ++ InvalidationStats Stats(CallingThread); + std::lock_guard lk(ThreadCreationMutex); + + // Potential deferred since Thread might not be valid. + // Thread object isn't valid very early in frontend's initialization. + // To be more optimal the frontend should provide this code with a valid Thread object earlier. + auto CodeInvalidationlk = FEXCore::GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread); +- CTX->InvalidateCodeBuffersCodeRange(Start, Length); +- for (auto& Thread : Threads) { +- CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length); ++ if (CTX->InvalidateCodeBuffersCodeRange(Start, Length)) { ++ for (auto& Thread : Threads) { ++ CTX->InvalidateThreadCachedCodeRange(Thread->Thread, Start, Length, true); ++ } ++ } else { ++ CTX->InvalidateExecutableRangeCaches(); + } + + // Callback while holding the locks. +@@ -254,6 +291,20 @@ public: + } + + private: ++ struct InvalidationStats { ++ explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) ++ : Thread {Thread} ++ , Begin {Thread && Thread->ThreadStats ? FEXCore::SHMStats::GetCycleCounter() : 0} {} ++ ~InvalidationStats() { ++ if (Thread && Thread->ThreadStats) { ++ Thread->ThreadStats->AccumulatedInvalidationCount += 1; ++ Thread->ThreadStats->AccumulatedInvalidationTime += FEXCore::SHMStats::GetCycleCounter() - Begin; ++ } ++ } ++ FEXCore::Core::InternalThreadState* Thread; ++ uint64_t Begin; ++ }; ++ + StatAlloc Stat; + FEXCore::Context::Context* CTX; + FEX::HLE::SignalDelegator* SignalDelegation; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +index 8b9c25948..3b37e4a3e 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Utils/Threads.cpp +@@ -347,6 +347,7 @@ namespace PThreads { + Thread->detach(); + + if (LongJumpExit) { ++ FEX::HLE::_SyscallHandler->ReleaseDeferredTLSState(ThreadObject); + // We have ownership of the thread object. Make sure to clean it up to prevent memory leaks. + FEX::HLE::_SyscallHandler->TM.DestroyThread(ThreadObject, true); + if (Status == 0) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +index 361bfbec1..25b3b0742 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x32/FD.cpp +@@ -802,6 +802,7 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X32( + pread_64, [](FEXCore::Core::CpuStateFrame* Frame, int fd, void* buf, uint32_t count, uint32_t offset_low, uint32_t offset_high) -> uint64_t { + uint64_t Offset = (uint64_t(offset_high) << 32) | offset_low; ++ FEX::HLE::_SyscallHandler->PrepareGuestBufferForKernelWrite(Frame->Thread, buf, count); + uint64_t Result = ::pread64(fd, buf, count, Offset); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +index d1ab9cdf8..84c612940 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/EPoll.cpp +@@ -6,6 +6,7 @@ tags: LinuxSyscalls|syscalls-x86-64 + $end_info$ + */ + ++#include "LinuxSyscalls/SignalTrace.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Types.h" + #include "LinuxSyscalls/x64/Syscalls.h" +@@ -14,6 +15,7 @@ $end_info$ + #include + + #include ++#include + #include + #include + #include +@@ -50,6 +52,9 @@ void RegisterEpoll(FEX::HLE::SyscallHandler* Handler) { + EventPtr = &Event; + } + uint64_t Result = ::syscall(SYSCALL_DEF(epoll_ctl), epfd, op, fd, EventPtr); ++ if (SigTrace::Enabled()) { ++ SigTrace::Log(::syscall(SYS_gettid), SigTrace::EpollCtl, op, fd, (EventPtr ? EventPtr->events : 0) | (Result << 32)); ++ } + if (Result != -1 && event) { + FaultSafeUserMemAccess::VerifyIsWritable(event, sizeof(FEX::HLE::epoll_event_x86)); + *event = Event; +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +index 91b5a103d..4eab76a59 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/FD.cpp +@@ -63,14 +63,16 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(stat, [](FEXCore::Core::CpuStateFrame* Frame, const char* pathname, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Stat(pathname, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -79,36 +81,41 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + struct stat host_stat; + uint64_t Result = ::fstat(fd, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64(lstat, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, FEX::HLE::x64::guest_stat* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Lstat(path, &host_stat); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); + + REGISTER_SYSCALL_IMPL_X64( + newfstatat, [](FEXCore::Core::CpuStateFrame* Frame, int dirfd, const char* pathname, FEX::HLE::x64::guest_stat* buf, int flag) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(pathname); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(pathname, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname)) { ++ return -EFAULT; ++ } + struct stat host_stat; + uint64_t Result = FEX::HLE::_SyscallHandler->FM.NewFSStatAt(dirfd, pathname, &host_stat, flag); + if (Result != -1) { +- SYSCALL_EFAULT_IF_NULL(buf); +- FaultSafeUserMemAccess::VerifyIsWritable(buf, sizeof(*buf)); +- *buf = host_stat; ++ FEX::HLE::x64::guest_stat guest = host_stat; ++ if (FaultSafeUserMemAccess::CopyToUser(buf, &guest, sizeof(guest))) { ++ return -EFAULT; ++ } + } + SYSCALL_ERRNO(); + }); +@@ -140,8 +147,9 @@ void RegisterFD(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL_X64(statfs, [](FEXCore::Core::CpuStateFrame* Frame, const char* path, struct statfs* buf) -> uint64_t { +- SYSCALL_EFAULT_IF_NULL(path); +- FaultSafeUserMemAccess::VerifyIsStringReadableMaxSize(path, PATH_MAX); ++ if (!FaultSafeUserMemAccess::IsStringReadable(path)) { ++ return -EFAULT; ++ } + uint64_t Result = FEX::HLE::_SyscallHandler->FM.Statfs(path, buf); + SYSCALL_ERRNO(); + }); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +index 36726ece6..c7b39bb46 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Signals.cpp +@@ -25,10 +25,18 @@ void RegisterSignals(FEX::HLE::SyscallHandler* Handler) { + if (sigsetsize != 8) { + return -EINVAL; + } +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(act, sizeof(GuestSigAction)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(oldact, sizeof(GuestSigAction)); ++ GuestSigAction NewAct; ++ GuestSigAction OldAct; ++ if (act && FaultSafeUserMemAccess::CopyFromUser(&NewAct, act, sizeof(NewAct))) { ++ return -EFAULT; ++ } + +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act, oldact); ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSignalHandler(signum, act ? &NewAct : nullptr, ++ oldact ? &OldAct : nullptr); ++ if (Result == 0 && oldact && FaultSafeUserMemAccess::CopyToUser(oldact, &OldAct, sizeof(OldAct))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + REGISTER_SYSCALL_IMPL_X64( +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +index c25ff5b94..0ec2933bc 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/x64/Thread.cpp +@@ -233,6 +233,22 @@ enum Modify_ldt_func : int32_t { + LDT_WRITE = 0x11, + }; + ++static bool GatherStringArray(char* const* User, fextl::vector& Out) { ++ for (size_t i = 0;; ++i) { ++ const char* Str; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Str, &User[i], sizeof(Str))) { ++ return false; ++ } ++ Out.push_back(Str); ++ if (!Str) { ++ return true; ++ } ++ if (!FaultSafeUserMemAccess::IsStringReadable(Str)) { ++ return false; ++ } ++ } ++} ++ + void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL_X64(modify_ldt, [](FEXCore::Core::CpuStateFrame* Frame, int func, void* ptr, unsigned long bytecount) -> uint64_t { + switch (func) { +@@ -278,10 +294,17 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + })); + + REGISTER_SYSCALL_IMPL_X64(sigaltstack, [](FEXCore::Core::CpuStateFrame* Frame, const stack_t* ss, stack_t* old_ss) -> uint64_t { +- FaultSafeUserMemAccess::VerifyIsReadableOrNull(ss, sizeof(*ss)); +- FaultSafeUserMemAccess::VerifyIsWritableOrNull(old_ss, sizeof(*old_ss)); +- return FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( +- FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss, old_ss); ++ stack_t NewStack; ++ stack_t OldStack; ++ if (ss && FaultSafeUserMemAccess::CopyFromUser(&NewStack, ss, sizeof(NewStack))) { ++ return -EFAULT; ++ } ++ uint64_t Result = FEX::HLE::_SyscallHandler->GetSignalDelegator()->RegisterGuestSigAltStack( ++ FEX::HLE::ThreadManager::GetStateObjectFromCPUState(Frame), ss ? &NewStack : nullptr, old_ss ? &OldStack : nullptr); ++ if (Result == 0 && old_ss && FaultSafeUserMemAccess::CopyToUser(old_ss, &OldStack, sizeof(OldStack))) { ++ return -EFAULT; ++ } ++ return Result; + }); + + // launch a new process under fex +@@ -290,20 +313,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + auto* const* ArgsPtr = argv ? const_cast(Args.data()) : nullptr; +@@ -319,20 +331,9 @@ void RegisterThread(FEX::HLE::SyscallHandler* Handler) { + fextl::vector Args; + fextl::vector Envp; + +- if (argv) { +- for (int i = 0; argv[i]; i++) { +- Args.push_back(argv[i]); +- } +- +- Args.push_back(nullptr); +- } +- +- if (envp) { +- for (int i = 0; envp[i]; i++) { +- Envp.push_back(envp[i]); +- } +- +- Envp.push_back(nullptr); ++ if (!FaultSafeUserMemAccess::IsStringReadable(pathname) || (argv && !GatherStringArray(argv, Args)) || ++ (envp && !GatherStringArray(envp, Envp))) { ++ return -EFAULT; + } + + FEX::HLE::ExecveAtArgs AtArgs { diff --git a/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch b/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch new file mode 100644 index 0000000000..0d62f092d4 --- /dev/null +++ b/tools/fex/patches/0022-proc-maps-guest-only-on-small-address-space-hosts.patch @@ -0,0 +1,132 @@ +From: maxjivi05 +Subject: [PATCH] List only guest mappings in /proc//maps on hosts below 47 address bits + +Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index eb12945e4..65b0521c9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -17,7 +17,11 @@ $end_info$ + #include + #include + #include ++#include + #include ++#include ++#include ++#include + #include + #include + #include +@@ -25,9 +29,13 @@ $end_info$ + + #include + ++#include + #include + #include + #include ++#include ++#include ++#include + #include + #include + #include +@@ -609,6 +617,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx) + + EmulatedFDManager::~EmulatedFDManager() {} + ++static bool IsSelfProcPath(const char* Path) { ++ const char* P = Path + 6; ++ if (!isdigit(*P)) { ++ return true; ++ } ++ return strtol(P, nullptr, 10) == ::getpid(); ++} ++ ++static bool IsHostArchModule(const char* Path, fextl::unordered_map& Seen) { ++ auto Known = Seen.find(Path); ++ if (Known != Seen.end()) { ++ return Known->second; ++ } ++ bool Host = false; ++ int FD = ::open(Path, O_RDONLY | O_CLOEXEC); ++ if (FD >= 0) { ++ Elf64_Ehdr Header {}; ++ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast(offsetof(Elf64_Ehdr, e_version)) && ++ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) { ++#if defined(__aarch64__) ++ Host = Header.e_machine == EM_AARCH64; ++#else ++ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386; ++#endif ++ } ++ ::close(FD); ++ } ++ Seen.emplace(Path, Host); ++ return Host; ++} ++ + static bool IsProcMapsPath(const char* Path) { + if (strncmp(Path, "/proc/", 6) != 0) { + return false; +@@ -661,14 +700,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, + ::close(HostFD); + + constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; ++ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47; ++ const bool Self = IsSelfProcPath(pathname); ++ fextl::vector> GuestRanges; ++ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(FEX::HLE::_SyscallHandler->VMATracking.Mutex); ++ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size()); ++ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) { ++ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) { ++ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length); ++ } else { ++ GuestRanges.emplace_back(Base, Base + VMA.Length); ++ } ++ } ++ } ++ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) { ++ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start, ++ [](uint64_t Value, const std::pair& Range) { return Value < Range.first; }); ++ if (It != GuestRanges.begin() && std::prev(It)->second > Start) { ++ return true; ++ } ++ return It != GuestRanges.end() && It->first < End; ++ }; ++ fextl::unordered_map ModuleArch; + fextl::string Out; + Out.reserve(In.size()); + size_t Pos = 0; + while (Pos < In.size()) { + size_t Eol = In.find('\n', Pos); + const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1; +- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16); +- if (Start < X86_64TaskSizeMax) { ++ char* Cursor {}; ++ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16); ++ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start; ++ bool Keep = Start < X86_64TaskSizeMax; ++ if (Keep && HostSharesGuestRange) { ++ if (Self) { ++ Keep = IsGuestRange(Start, Stop); ++ } else { ++ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol; ++ size_t Name = In.find_first_of("/[", Pos); ++ if (Name != fextl::string::npos && Name < LineEnd) { ++ fextl::string Path(In, Name, LineEnd - Name); ++ if (Path.starts_with("[anon:FEX")) { ++ Keep = false; ++ } else if (Path[0] == '/') { ++ Keep = !IsHostArchModule(Path.c_str(), ModuleArch); ++ } ++ } ++ } ++ } ++ if (Keep) { + Out.append(In, Pos, End - Pos); + } + Pos = End; diff --git a/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch b/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch new file mode 100644 index 0000000000..d0550e8db0 --- /dev/null +++ b/tools/fex/patches/0023-proc-status-seccomp-of-calling-thread.patch @@ -0,0 +1,53 @@ +From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:21:23 -0500 +Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + .../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++- + .../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++ + 2 files changed, 15 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 65b0521c9..ce36b988b 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -797,7 +797,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + Buf[Len] = '\0'; + + uint32_t SeccompMode = SECCOMP_MODE_DISABLED; +- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) { ++ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr; ++ if (!Thread) { ++ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject(); ++ } ++ if (Thread) { + SeccompMode = Thread->SeccompMode; + } + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 0a46703ca..9c5f9f1c2 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -290,6 +290,16 @@ public: + return &Threads; + } + ++ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) { ++ std::lock_guard lk(ThreadCreationMutex); ++ for (auto* Thread : Threads) { ++ if (Thread->ThreadInfo.TID == TID) { ++ return Thread; ++ } ++ } ++ return nullptr; ++ } ++ + private: + struct InvalidationStats { + explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread) +-- +2.43.0 + diff --git a/tools/fex/patches/0024-read-host-status-directly.patch b/tools/fex/patches/0024-read-host-status-directly.patch new file mode 100644 index 0000000000..8a5268c7e7 --- /dev/null +++ b/tools/fex/patches/0024-read-host-status-directly.patch @@ -0,0 +1,105 @@ +From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:25:20 -0500 +Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system + call + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++ + .../EmulatedFiles/EmulatedFiles.cpp | 3 +- + .../LinuxSyscalls/PtraceEmu.cpp | 3 +- + 3 files changed, 34 insertions(+), 2 deletions(-) + +diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h +index dae3d3bcc..c0f3eb3ed 100644 +--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h ++++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h +@@ -4,6 +4,7 @@ + #include + + #include ++#include + #include + #include + #include +@@ -123,4 +124,33 @@ inline int32_t gettid() { + + #endif + ++#ifndef _WIN32 ++inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) { ++#if defined(__aarch64__) ++ register long x0 asm("x0") = dirfd; ++ register long x1 asm("x1") = reinterpret_cast(pathname); ++ register long x2 asm("x2") = flags; ++ register long x3 asm("x3") = 0; ++ register long x8 asm("x8") = SYS_openat; ++ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory"); ++ if (x0 < 0) { ++ errno = static_cast(-x0); ++ return -1; ++ } ++ return static_cast(x0); ++#elif defined(__x86_64__) ++ long ret; ++ register long r10 asm("r10") = 0; ++ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory"); ++ if (ret < 0) { ++ errno = static_cast(-ret); ++ return -1; ++ } ++ return static_cast(ret); ++#else ++ return static_cast(::syscall(SYS_openat, dirfd, pathname, flags)); ++#endif ++} ++#endif ++ + } // namespace FHU::Syscalls +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index ce36b988b..19bfc814f 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -14,6 +14,7 @@ $end_info$ + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h" + ++#include + #include + #include + #include +@@ -785,7 +786,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + char Buf[8192]; + ssize_t Len = 0; + { +- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC); + if (HostFD >= 0) { + Len = ::read(HostFD, Buf, sizeof(Buf) - 1); + ::close(HostFD); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +index ca4c86063..49ece24a3 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -3,6 +3,7 @@ + #include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/Syscalls.h" + ++#include + #include + #include + +@@ -133,7 +134,7 @@ namespace { + } + + bool HasHostTracer() { +- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC); ++ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return true; + } +-- +2.43.0 + diff --git a/tools/fex/patches/0025-ptrace-state-across-exec.patch b/tools/fex/patches/0025-ptrace-state-across-exec.patch new file mode 100644 index 0000000000..6c1bcc618f --- /dev/null +++ b/tools/fex/patches/0025-ptrace-state-across-exec.patch @@ -0,0 +1,104 @@ +From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:41:52 -0500 +Subject: [PATCH] Hand the tracee's ptrace state across exec + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). + +--- + .../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++- + 1 file changed, 53 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +index 49ece24a3..62acdb0da 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp +@@ -266,6 +266,38 @@ namespace { + ::close(fd); + } + ++ bool AdoptionTried = false; ++ ++ void AdoptSharedPage() { ++ if (AdoptionTried || Current != &StaticState || !IsMainThread()) { ++ return; ++ } ++ AdoptionTried = true; ++ const int fd = OpenSidecar("state", ::getpid(), O_RDWR); ++ if (fd < 0) { ++ return; ++ } ++ if (!HasHostTracer()) { ++ ::close(fd); ++ return; ++ } ++ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ++ ::close(fd); ++ if (Page == MAP_FAILED) { ++ return; ++ } ++ auto* S = static_cast(Page); ++ if (S->Magic != SharedState::MagicValue) { ++ ::munmap(Page, 4096); ++ return; ++ } ++ S->Pending = 0; ++ S->DirtyMask = 0; ++ S->SignalNumber = 0; ++ S->FlushLen = 0; ++ Current = S; ++ } ++ + struct Remote { + uint8_t* Mapped = nullptr; + uintptr_t StaticAddr = 0; +@@ -332,6 +364,22 @@ namespace { + return &Remotes.emplace(Pid, std::move(R)).first->second; + } + ++ bool KeepAcrossExec(pid_t Pid) { ++ { ++ std::lock_guard lk(RemotesLock); ++ auto It = Remotes.find(Pid); ++ if (It != Remotes.end()) { ++ return It->second.Mapped != nullptr; ++ } ++ } ++ const int fd = OpenSidecar("state", Pid, O_RDONLY); ++ if (fd < 0) { ++ return false; ++ } ++ ::close(fd); ++ return true; ++ } ++ + void Forget(pid_t Pid, bool Exited) { + std::lock_guard lk(RemotesLock); + auto It = Remotes.find(Pid); +@@ -470,10 +518,12 @@ namespace { + + + bool IsAttached() { ++ AdoptSharedPage(); + return Current->Attached != 0; + } + + bool WantsSyscallStops() { ++ AdoptSharedPage(); + return Current->SyscallStops && IsMainThread(); + } + +@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) { + + if ((St >> 16) == X86_PTRACE_EVENT_EXEC) { + CaptureExecPath(Pid); +- Forget(Pid, false); ++ if (!KeepAcrossExec(Pid)) { ++ Forget(Pid, false); ++ } + } + + if (WSTOPSIG(St) == SIGSTOP) { +-- +2.43.0 + diff --git a/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch b/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch new file mode 100644 index 0000000000..0ebaff5209 --- /dev/null +++ b/tools/fex/patches/0026-emulated-proc-files-behind-host-memfd.patch @@ -0,0 +1,78 @@ +From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 18:58:13 -0500 +Subject: [PATCH] Serve emulated proc files by the requested path when the host + returns a memfd + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). +--- + .../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++---- + .../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +- + 2 files changed, 8 insertions(+), 5 deletions(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +index 62b6a2d27..b76e96e58 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp +@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint + return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode); + } + +-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) { ++bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) { + char Tmp[PATH_MAX + 1]; + + if (fd < 0) { +@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) { + + // And try to open via EmuFD + auto EmuFd = EmuFD.Open(Tmp, flags, mode); ++ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) { ++ EmuFd = EmuFD.Open(RequestedPath, flags, mode); ++ } + if (EmuFd == -1) { + return false; + } +@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) { + fd = ::open(SelfPath, flags, mode); + } + +- ReplaceEmuFd(fd, flags, mode); ++ ReplaceEmuFd(fd, flags, mode, SelfPath); + } else { + fd = ::open(SelfPath, flags, mode); + } +@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i + fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode); + } + +- ReplaceEmuFd(fd, flags, mode); ++ ReplaceEmuFd(fd, flags, mode, SelfPath); + } else { + fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode); + } +@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho + fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize); + } + +- ReplaceEmuFd(fd, how->flags, how->mode); ++ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath); + } else { + fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize); + } +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h +index b11f096f7..a86539972 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h +@@ -102,7 +102,7 @@ public: + fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const; + fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const; + +- bool ReplaceEmuFd(int fd, int flags, uint32_t mode); ++ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath); + + #if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED + void TrackFEXFD(int FD) noexcept { +-- +2.43.0 + diff --git a/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch b/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch new file mode 100644 index 0000000000..b19386b095 --- /dev/null +++ b/tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch @@ -0,0 +1,3258 @@ +From 4e237204720bf57c8e4b7dae1ff74b5e341763e6 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Wed, 2 Dec 2026 20:01:44 -0500 +Subject: [PATCH] Map fixed guest memory above a small host address space + +Hosts with 39-bit or 42-bit user address spaces cannot place x86-64 +mappings that ask for a fixed address above that limit. Such mappings +are now backed by host memory at any address, and guest accesses to +them are redirected through a per-thread single-instruction trampoline. +Syscall arguments that point into these mappings are translated, and +writes to code in them invalidate translated blocks. + +Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT). +--- + Source/Tools/LinuxEmulation/CMakeLists.txt | 1 + + .../LinuxSyscalls/GuestHighMemory.cpp | 2754 +++++++++++++++++ + .../LinuxSyscalls/GuestHighMemory.h | 74 + + .../LinuxSyscalls/SignalDelegator.cpp | 5 + + .../LinuxEmulation/LinuxSyscalls/Syscalls.cpp | 53 +- + .../LinuxSyscalls/Syscalls/Memory.cpp | 30 + + .../LinuxSyscalls/SyscallsSMCTracking.cpp | 61 +- + .../LinuxSyscalls/ThreadManager.cpp | 2 + + .../LinuxSyscalls/ThreadManager.h | 34 + + 9 files changed, 2984 insertions(+), 30 deletions(-) + create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp + create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h + +diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt +index 3f02104..acf4c4c 100644 +--- a/Source/Tools/LinuxEmulation/CMakeLists.txt ++++ b/Source/Tools/LinuxEmulation/CMakeLists.txt +@@ -18,6 +18,7 @@ add_library(LinuxEmulation STATIC + LinuxSyscalls/Seccomp/BPFEmitter.cpp + LinuxSyscalls/Seccomp/Dumper.cpp + LinuxSyscalls/SignalDelegator.cpp ++ LinuxSyscalls/GuestHighMemory.cpp + LinuxSyscalls/Syscalls.cpp + LinuxSyscalls/SyscallsSMCTracking.cpp + LinuxSyscalls/SyscallsVMATracking.cpp +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp +new file mode 100644 +index 0000000..4483499 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp +@@ -0,0 +1,2754 @@ ++#include "LinuxSyscalls/GuestHighMemory.h" ++#include "LinuxSyscalls/Syscalls.h" ++#include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/x64/SyscallsEnum.h" ++#include "ArchHelpers/MContext.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace FEX::HLE::GuestHighMemory { ++namespace { ++ constexpr uint64_t TaskTop = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE; ++ constexpr uint32_t MaxRegions = 1024; ++ ++ struct Region { ++ std::atomic Guest; ++ std::atomic Size; ++ std::atomic Host; ++ std::atomic Code; ++ std::atomic Prot; ++ }; ++ ++ struct RegionView { ++ uint64_t Guest; ++ uint64_t Size; ++ uint64_t Host; ++ uint32_t Index; ++ bool Code; ++ uint8_t Prot; ++ }; ++ ++ struct HostRange { ++ uint64_t Start; ++ uint64_t Size; ++ }; ++ ++ constexpr uint32_t MaxAccessPieces = 2; ++ ++ struct AccessPiece { ++ uint64_t Guest; ++ uint64_t Host; ++ uint64_t Size; ++ uint8_t Prot; ++ bool Code; ++ }; ++ ++ Region Regions[MaxRegions]; ++ std::atomic Count {0}; ++ HostRange Retired[MaxRegions]; ++ uint32_t RetiredCount {}; ++ std::atomic Sequence {0}; ++ ++ uint64_t HostLimit() { ++ static const uint64_t Limit = [] { ++ const auto Bits = FEXCore::Allocator::GetHostVABits(); ++ return Bits >= 47 ? TaskTop : (1ULL << Bits); ++ }(); ++ return Limit; ++ } ++ ++ void BeginWrite() { ++ Sequence.fetch_add(1, std::memory_order_acq_rel); ++ } ++ ++ void EndWrite() { ++ Sequence.fetch_add(1, std::memory_order_release); ++ } ++ ++ bool FindLocked(uint64_t Address, RegionView* Out) { ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Address >= Guest && Address - Guest < Size) { ++ Out->Guest = Guest; ++ Out->Size = Size; ++ Out->Host = Regions[i].Host.load(std::memory_order_relaxed); ++ Out->Code = Regions[i].Code.load(std::memory_order_relaxed); ++ Out->Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ Out->Index = i; ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ template ++ auto ReadConsistent(Fn&& Body) { ++ for (;;) { ++ const auto Before = Sequence.load(std::memory_order_acquire); ++ if (Before & 1) { ++ continue; ++ } ++ const auto Result = Body(); ++ std::atomic_thread_fence(std::memory_order_acquire); ++ if (Sequence.load(std::memory_order_relaxed) == Before) { ++ return Result; ++ } ++ } ++ } ++ ++ bool SpanLocked(uint64_t Address, uint64_t Length, uint64_t* Host) { ++ RegionView View; ++ if (!FindLocked(Address, &View)) { ++ *Host = Address; ++ return true; ++ } ++ *Host = View.Host + (Address - View.Guest); ++ if (Length > TaskTop - Address) { ++ return false; ++ } ++ const auto End = Address + Length; ++ auto GuestEnd = View.Guest + View.Size; ++ auto HostEnd = View.Host + View.Size; ++ while (End > GuestEnd) { ++ if (!FindLocked(GuestEnd, &View) || View.Host != HostEnd) { ++ return false; ++ } ++ GuestEnd += View.Size; ++ HostEnd += View.Size; ++ } ++ return true; ++ } ++ ++ uint32_t PlanAccessLocked(uint64_t Address, uint64_t Size, AccessPiece* Pieces) { ++ uint32_t Parts = 0; ++ uint64_t Done = 0; ++ while (Done < Size) { ++ RegionView View; ++ if (Parts == MaxAccessPieces || !FindLocked(Address + Done, &View)) { ++ return 0; ++ } ++ const auto Offset = Address + Done - View.Guest; ++ const auto Length = std::min(Size - Done, View.Size - Offset); ++ Pieces[Parts++] = {Address + Done, View.Host + Offset, Length, View.Prot, View.Code}; ++ Done += Length; ++ } ++ return Parts; ++ } ++ ++ template ++ uint64_t ApplyToRegionsLocked(uint64_t Address, uint64_t Length, uint64_t WrapError, Fn&& Apply) { ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return -EINVAL; ++ } ++ if (Length == 0) { ++ return 0; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0 || Size > UINT64_MAX - Address) { ++ return WrapError; ++ } ++ const auto End = Address + std::min(Size, TaskTop - Address); ++ uint64_t Covered = 0; ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd <= Address || Guest >= End) { ++ continue; ++ } ++ const auto OverlapStart = std::max(Guest, Address); ++ const auto OverlapEnd = std::min(RegionEnd, End); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed) + (OverlapStart - Guest); ++ if (Apply(reinterpret_cast(Host), OverlapEnd - OverlapStart, i) != 0) { ++ return -errno; ++ } ++ Covered += OverlapEnd - OverlapStart; ++ } ++ return Covered == Size ? 0 : -ENOMEM; ++ } ++ ++ uint64_t NeighbourHint(uint64_t Address, uint64_t Size) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionSize = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ if (Guest + RegionSize == Address) { ++ return Host + RegionSize; ++ } ++ if (Guest == Address + Size && Host >= Size) { ++ return Host - Size; ++ } ++ } ++ return 0; ++ } ++ ++ void SetEntry(uint32_t i, uint64_t Guest, uint64_t Size, uint64_t Host, bool Code, uint8_t Prot) { ++ Regions[i].Guest.store(Guest, std::memory_order_relaxed); ++ Regions[i].Size.store(Size, std::memory_order_relaxed); ++ Regions[i].Host.store(Host, std::memory_order_relaxed); ++ Regions[i].Code.store(Code, std::memory_order_relaxed); ++ Regions[i].Prot.store(Prot, std::memory_order_relaxed); ++ } ++ ++ void RemoveEntry(uint32_t i) { ++ const auto Last = Count.load(std::memory_order_relaxed) - 1; ++ if (i != Last) { ++ SetEntry(i, Regions[Last].Guest.load(std::memory_order_relaxed), Regions[Last].Size.load(std::memory_order_relaxed), ++ Regions[Last].Host.load(std::memory_order_relaxed), Regions[Last].Code.load(std::memory_order_relaxed), ++ Regions[Last].Prot.load(std::memory_order_relaxed)); ++ } ++ Count.store(Last, std::memory_order_release); ++ } ++ ++ bool AddEntry(uint64_t Guest, uint64_t Size, uint64_t Host, bool Code, uint8_t Prot) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ if (Entries >= MaxRegions) { ++ return false; ++ } ++ SetEntry(Entries, Guest, Size, Host, Code, Prot); ++ Count.store(Entries + 1, std::memory_order_release); ++ return true; ++ } ++ ++ bool HasRoomLocked(uint64_t Address, uint64_t Length, uint32_t Added) { ++ const auto End = Address + Length; ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ uint64_t After = Entries + Added; ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd <= Address || Guest >= End) { ++ continue; ++ } ++ if (Guest >= Address && RegionEnd <= End) { ++ --After; ++ } else if (Guest < Address && RegionEnd > End) { ++ ++After; ++ } ++ } ++ return After <= MaxRegions; ++ } ++ ++ void ReleaseRetiredLocked() { ++ uint32_t i = 0; ++ while (i < RetiredCount) { ++ if (::munmap(reinterpret_cast(Retired[i].Start), Retired[i].Size) == 0) { ++ Retired[i] = Retired[--RetiredCount]; ++ } else { ++ ++i; ++ } ++ } ++ } ++ ++ void UnmapHost(uint64_t Start, uint64_t Size) { ++ if (::munmap(reinterpret_cast(Start), Size) == 0) { ++ return; ++ } ++ ::madvise(reinterpret_cast(Start), Size, MADV_DONTNEED); ++ for (uint32_t i = 0; i < RetiredCount; ++i) { ++ if (Retired[i].Start + Retired[i].Size == Start) { ++ Retired[i].Size += Size; ++ return; ++ } ++ if (Start + Size == Retired[i].Start) { ++ Retired[i] = {Start, Retired[i].Size + Size}; ++ return; ++ } ++ } ++ if (RetiredCount < MaxRegions) { ++ Retired[RetiredCount++] = {Start, Size}; ++ } ++ } ++ ++ int UnmapLocked(uint64_t Address, uint64_t Length) { ++ ReleaseRetiredLocked(); ++ if (!HasRoomLocked(Address, Length, 0)) { ++ return -ENOMEM; ++ } ++ const auto End = Address + Length; ++ uint32_t Overlapping = 0; ++ for (uint32_t i = 0; i < Count.load(std::memory_order_relaxed); ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ if (Guest < End && Guest + Regions[i].Size.load(std::memory_order_relaxed) > Address) { ++ ++Overlapping; ++ } ++ } ++ if (RetiredCount + Overlapping > MaxRegions) { ++ return -ENOMEM; ++ } ++ uint32_t i = 0; ++ while (i < Count.load(std::memory_order_relaxed)) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Size; ++ if (RegionEnd <= Address || Guest >= End) { ++ ++i; ++ continue; ++ } ++ const auto OverlapStart = std::max(Guest, Address); ++ const auto OverlapEnd = std::min(RegionEnd, End); ++ UnmapHost(Host + (OverlapStart - Guest), OverlapEnd - OverlapStart); ++ ++ if (OverlapStart == Guest && OverlapEnd == RegionEnd) { ++ RemoveEntry(i); ++ continue; ++ } ++ if (OverlapStart == Guest) { ++ SetEntry(i, OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code, Prot); ++ } else if (OverlapEnd == RegionEnd) { ++ SetEntry(i, Guest, OverlapStart - Guest, Host, Code, Prot); ++ } else { ++ if (!AddEntry(OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code, Prot)) { ++ return -ENOMEM; ++ } ++ SetEntry(i, Guest, OverlapStart - Guest, Host, Code, Prot); ++ } ++ ++i; ++ } ++ return 0; ++ } ++ ++ constexpr uint8_t TrackedProt(int Prot) { ++ return Prot & (PROT_READ | PROT_WRITE | PROT_EXEC); ++ } ++ ++ int SplitLocked(uint64_t Address, uint64_t Length) { ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0) { ++ return 0; ++ } ++ const uint64_t Boundaries[] = {Address, Address + std::min(Size, TaskTop - Address)}; ++ uint32_t Needed = 0; ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ for (const auto Boundary : Boundaries) { ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ if (Boundary > Guest && Boundary - Guest < Regions[i].Size.load(std::memory_order_relaxed)) { ++ ++Needed; ++ } ++ } ++ } ++ if (Entries + Needed > MaxRegions) { ++ return -ENOMEM; ++ } ++ for (const auto Boundary : Boundaries) { ++ for (uint32_t i = 0; i < Count.load(std::memory_order_relaxed); ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionSize = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Boundary <= Guest || Boundary - Guest >= RegionSize) { ++ continue; ++ } ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ AddEntry(Boundary, Guest + RegionSize - Boundary, Host + (Boundary - Guest), Code, Prot); ++ SetEntry(i, Guest, Boundary - Guest, Host, Code, Prot); ++ break; ++ } ++ } ++ return 0; ++ } ++ ++ void CoalesceLocked(uint64_t Address, uint64_t End) { ++ uint32_t i = 0; ++ while (i < Count.load(std::memory_order_relaxed)) { ++ const auto Entries = Count.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ const auto RegionEnd = Regions[i].Guest.load(std::memory_order_relaxed) + Size; ++ const auto HostEnd = Regions[i].Host.load(std::memory_order_relaxed) + Size; ++ const auto Code = Regions[i].Code.load(std::memory_order_relaxed); ++ const auto Prot = Regions[i].Prot.load(std::memory_order_relaxed); ++ uint32_t Next = Entries; ++ if (RegionEnd >= Address && RegionEnd <= End) { ++ for (uint32_t j = 0; j < Entries; ++j) { ++ if (Regions[j].Guest.load(std::memory_order_relaxed) == RegionEnd && Regions[j].Host.load(std::memory_order_relaxed) == HostEnd && ++ Regions[j].Code.load(std::memory_order_relaxed) == Code && Regions[j].Prot.load(std::memory_order_relaxed) == Prot) { ++ Next = j; ++ break; ++ } ++ } ++ } ++ if (Next == Entries) { ++ ++i; ++ continue; ++ } ++ Regions[i].Size.store(Size + Regions[Next].Size.load(std::memory_order_relaxed), std::memory_order_relaxed); ++ RemoveEntry(Next); ++ if (i == Entries - 1 || Next < i) { ++ i = Next; ++ } ++ } ++ } ++ ++ constexpr uint32_t RtField(uint32_t Insn) { ++ return Insn & 0x1f; ++ } ++ ++ constexpr uint32_t RnField(uint32_t Insn) { ++ return (Insn >> 5) & 0x1f; ++ } ++ ++ constexpr uint32_t Rt2Field(uint32_t Insn) { ++ return (Insn >> 10) & 0x1f; ++ } ++ ++ constexpr uint32_t RsField(uint32_t Insn) { ++ return (Insn >> 16) & 0x1f; ++ } ++ ++ constexpr bool IsLoadStore(uint32_t Insn) { ++ return (Insn & 0x0a000000) == 0x08000000; ++ } ++ ++ constexpr bool IsLiteralLoad(uint32_t Insn) { ++ return (Insn & 0x3b000000) == 0x18000000; ++ } ++ ++ constexpr bool IsExclusive(uint32_t Insn) { ++ if ((Insn & 0x3f800000) != 0x08000000) { ++ return false; ++ } ++ return (Insn & (1U << 21)) == 0 || (Insn & (1U << 31)) != 0; ++ } ++ ++ constexpr bool IsSingleRegister(uint32_t Insn) { ++ return (Insn & 0x3a000000) == 0x38000000 || (Insn & 0x3f200c00) == 0x19000000; ++ } ++ ++ constexpr bool IsWrite(uint32_t Insn) { ++ if ((Insn & 0x3b200c00) == 0x38200000) { ++ return ((Insn >> 12) & 0xf) != 0xc; ++ } ++ if ((Insn & 0x3f200000) == 0x08200000 && Rt2Field(Insn) == 0x1f) { ++ return true; ++ } ++ if (IsSingleRegister(Insn)) { ++ const auto Opc = (Insn >> 22) & 3; ++ return ((Insn >> 26) & 1) ? (Opc & 1) == 0 : Opc == 0; ++ } ++ return (Insn & (1U << 22)) == 0; ++ } ++ ++ constexpr bool IsOrderedAccess(uint32_t Insn) { ++ if ((Insn & 0x3f200c00) == 0x19000000) { ++ const auto Opc = (Insn >> 22) & 3; ++ const auto SizeBits = Insn >> 30; ++ return Opc < 2 || (Opc == 2 && SizeBits < 3) || (Opc == 3 && SizeBits < 2); ++ } ++ return (Insn & 0x3fbf7c00) == 0x089f7c00 || (Insn & 0x3ffffc00) == 0x38bfc000; ++ } ++ ++ constexpr uint64_t ExtendOrdered(uint32_t Insn, uint64_t Value) { ++ const auto Bits = 8U << (Insn >> 30); ++ const auto Opc = (Insn >> 22) & 3; ++ if ((Insn & 0x3f200c00) != 0x19000000 || Bits == 64 || Opc < 2) { ++ return Value; ++ } ++ const auto Signed = static_cast(static_cast(Value << (64 - Bits)) >> (64 - Bits)); ++ return Opc == 3 ? Signed & 0xffffffffULL : Signed; ++ } ++ ++ constexpr uint32_t ProbeInstruction(uint32_t Scratch) { ++ return 0x39400000 | (Scratch << 5) | Scratch; ++ } ++ ++ constexpr bool IsExclusiveLoad(uint32_t Insn) { ++ return (Insn & (1U << 22)) != 0; ++ } ++ ++ constexpr bool IsExclusivePair(uint32_t Insn) { ++ return (Insn & (1U << 21)) != 0; ++ } ++ ++ constexpr bool ExclusiveReachable(uint32_t Insn, uint8_t Prot) { ++ if (IsExclusiveLoad(Insn)) { ++ return (Prot & (PROT_READ | PROT_WRITE)) != 0; ++ } ++ return (Prot & PROT_WRITE) != 0; ++ } ++ ++ constexpr uint32_t ExclusiveElementSize(uint32_t Insn) { ++ return 1U << (Insn >> 30); ++ } ++ ++ uint64_t ReadReg(void* UContext, uint32_t Reg) { ++ return Reg == 31 ? 0 : ArchHelpers::Context::GetArmReg(UContext, Reg); ++ } ++ ++ void WriteReg(void* UContext, uint32_t Reg, uint64_t Value) { ++ if (Reg != 31) { ++ ArchHelpers::Context::SetArmReg(UContext, Reg, Value); ++ } ++ } ++ ++ uint64_t ElementMask(uint32_t Size) { ++ return Size == 8 ? ~0ULL : (1ULL << (Size * 8)) - 1; ++ } ++ ++ uint64_t LoadElement(uint64_t Host, uint32_t Size) { ++ switch (Size) { ++ case 1: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ case 2: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ case 4: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ default: return __atomic_load_n(reinterpret_cast(Host), __ATOMIC_SEQ_CST); ++ } ++ } ++ ++ bool CompareExchange(uint64_t Host, uint32_t Size, uint64_t ExpectedLow, uint64_t ExpectedHigh, uint64_t Low, uint64_t High) { ++ switch (Size) { ++ case 1: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 2: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 4: { ++ auto Expected = static_cast(ExpectedLow); ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, static_cast(Low), false, ++ __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ case 8: { ++ auto Expected = ExpectedLow; ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, Low, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); ++ } ++ default: { ++ auto Expected = (static_cast(ExpectedHigh) << 64) | ExpectedLow; ++ const auto Desired = (static_cast(High) << 64) | Low; ++ return __atomic_compare_exchange_n(reinterpret_cast(Host), &Expected, Desired, false, __ATOMIC_SEQ_CST, ++ __ATOMIC_SEQ_CST); ++ } ++ } ++ } ++ ++ template ++ bool EmulateExclusive(MonitorType& Monitor, uint32_t Insn, uint64_t Host, void* UContext) { ++ const auto Element = ExclusiveElementSize(Insn); ++ const bool Pair = IsExclusivePair(Insn); ++ const auto Size = Pair ? Element * 2 : Element; ++ if (Host & (Size - 1)) { ++ return false; ++ } ++ ++ if (IsExclusiveLoad(Insn)) { ++ uint64_t Low {}; ++ uint64_t High {}; ++ if (Pair && Element == 8) { ++ Low = LoadElement(Host, 8); ++ High = LoadElement(Host + 8, 8); ++ WriteReg(UContext, RtField(Insn), Low); ++ WriteReg(UContext, Rt2Field(Insn), High); ++ } else if (Pair) { ++ Low = LoadElement(Host, 8); ++ WriteReg(UContext, RtField(Insn), Low & 0xffffffffULL); ++ WriteReg(UContext, Rt2Field(Insn), Low >> 32); ++ } else { ++ Low = LoadElement(Host, Element); ++ WriteReg(UContext, RtField(Insn), Low); ++ } ++ Monitor.Host = Host; ++ Monitor.Size = Size; ++ Monitor.Low = Low; ++ Monitor.High = High; ++ Monitor.Valid = true; ++ return true; ++ } ++ ++ uint64_t Low {}; ++ uint64_t High {}; ++ if (Pair && Element == 8) { ++ Low = ReadReg(UContext, RtField(Insn)); ++ High = ReadReg(UContext, Rt2Field(Insn)); ++ } else if (Pair) { ++ Low = (ReadReg(UContext, RtField(Insn)) & 0xffffffffULL) | (ReadReg(UContext, Rt2Field(Insn)) << 32); ++ } else { ++ Low = ReadReg(UContext, RtField(Insn)) & ElementMask(Element); ++ } ++ const bool Stored = Monitor.Valid && Monitor.Host == Host && Monitor.Size == Size && ++ CompareExchange(Host, Size, Monitor.Low, Monitor.High, Low, High); ++ Monitor.Valid = false; ++ WriteReg(UContext, RsField(Insn), Stored ? 0 : 1); ++ return true; ++ } ++ ++ int64_t SignedField(uint32_t Insn, uint32_t Shift, uint32_t Bits) { ++ return static_cast(static_cast(Insn >> Shift) << (64 - Bits)) >> (64 - Bits); ++ } ++ ++ bool DecodeAccess(uint32_t Insn, void* UContext, uint64_t* Address, uint32_t* Size, bool* Plain) { ++ const auto Base = ArchHelpers::Context::GetArmReg(UContext, RnField(Insn)); ++ const auto SizeBits = Insn >> 30; ++ const bool Vector = (Insn >> 26) & 1; ++ const auto Scale = Vector && ((Insn >> 23) & 1) && SizeBits == 0 ? 4U : SizeBits; ++ *Address = Base; ++ *Plain = false; ++ if ((Insn & 0x3f000000) == 0x08000000) { ++ const bool Pair = (Insn & (1U << 21)) && !(Insn & (1U << 23)); ++ *Size = Pair ? 8U << (SizeBits & 1) : 1U << SizeBits; ++ return true; ++ } ++ if ((Insn & 0x3f200c00) == 0x19000000) { ++ *Address = Base + SignedField(Insn, 12, 9); ++ *Size = 1U << SizeBits; ++ return true; ++ } ++ if ((Insn & 0x3b200c00) == 0x38200000) { ++ *Size = 1U << SizeBits; ++ return !Vector; ++ } ++ *Plain = true; ++ if ((Insn & 0x3b000000) == 0x39000000) { ++ *Address = Base + (static_cast((Insn >> 10) & 0xfff) << Scale); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3b200000) == 0x38000000) { ++ *Address = ((Insn >> 10) & 3) == 1 ? Base : Base + SignedField(Insn, 12, 9); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3b200c00) == 0x38200800) { ++ const auto Option = (Insn >> 13) & 7; ++ if ((Option & 2) == 0) { ++ return false; ++ } ++ auto Offset = ReadReg(UContext, RsField(Insn)); ++ if ((Option & 1) == 0) { ++ Offset = (Option & 4) ? static_cast(static_cast(static_cast(Offset))) : static_cast(Offset); ++ } ++ *Address = Base + (Offset << (((Insn >> 12) & 1) ? Scale : 0)); ++ *Size = 1U << Scale; ++ return true; ++ } ++ if ((Insn & 0x3a000000) == 0x28000000) { ++ if (SizeBits == 3) { ++ return false; ++ } ++ const auto Element = Vector ? 4U << SizeBits : (SizeBits == 2 ? 8U : 4U); ++ *Address = ((Insn >> 23) & 3) == 1 ? Base : Base + SignedField(Insn, 15, 7) * static_cast(Element); ++ *Size = 2 * Element; ++ return true; ++ } ++ if ((Insn & 0xbfbf0000) == 0x0c000000 || (Insn & 0xbfa00000) == 0x0c800000) { ++ uint32_t Registers = 0; ++ switch ((Insn >> 12) & 0xf) { ++ case 0x0: ++ case 0x2: Registers = 4; break; ++ case 0x4: ++ case 0x6: Registers = 3; break; ++ case 0x7: Registers = 1; break; ++ case 0x8: ++ case 0xa: Registers = 2; break; ++ default: return false; ++ } ++ *Size = Registers * ((Insn & (1U << 30)) ? 16U : 8U); ++ return true; ++ } ++ if ((Insn & 0xbf9f0000) == 0x0d000000 || (Insn & 0xbf800000) == 0x0d800000) { ++ const auto Opcode = (Insn >> 13) & 7; ++ const auto Elements = (((Opcode & 1) << 1) | ((Insn >> 21) & 1)) + 1; ++ const auto Bits = (Insn >> 10) & 3; ++ uint32_t Element = 0; ++ switch (Opcode >> 1) { ++ case 0: Element = 1; break; ++ case 1: Element = (Bits & 1) ? 0 : 2; break; ++ case 2: Element = Bits == 0 ? 4 : (Bits == 1 && !((Insn >> 12) & 1) ? 8 : 0); break; ++ default: Element = 1U << Bits; break; ++ } ++ *Size = Elements * Element; ++ return Element != 0; ++ } ++ return false; ++ } ++ ++ bool HostContiguous(const AccessPiece* Pieces, uint32_t Parts) { ++ for (uint32_t i = 1; i < Parts; ++i) { ++ if (Pieces[i - 1].Host + Pieces[i - 1].Size != Pieces[i].Host) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ bool PiecesReachable(const AccessPiece* Pieces, uint32_t Parts, bool Write) { ++ const uint8_t Need = Write ? PROT_WRITE : PROT_READ | PROT_WRITE; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ if ((Pieces[i].Prot & Need) == 0) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ template ++ uint32_t CopyPieces(uint8_t* Bounce, const PieceType* Pieces, uint32_t Parts, bool Gather) { ++ uint64_t Offset = 0; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ auto* Host = reinterpret_cast(Pieces[i].Host); ++ const auto Failed = Gather ? FaultSafeUserMemAccess::CopyFromUser(Bounce + Offset, Host, Pieces[i].Size) : ++ FaultSafeUserMemAccess::CopyToUser(Host, Bounce + Offset, Pieces[i].Size); ++ if (Failed != 0) { ++ return i; ++ } ++ Offset += Pieces[i].Size; ++ } ++ return Parts; ++ } ++ ++ template ++ uint32_t EmulateOrdered(uint32_t Insn, const PieceType* Pieces, uint32_t Parts, void* UContext) { ++ const auto Size = 1U << (Insn >> 30); ++ uint8_t Bytes[8] {}; ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ const auto Gathered = CopyPieces(Bytes, Pieces, Parts, true); ++ if (Gathered != Parts) { ++ return Gathered; ++ } ++ uint64_t Value {}; ++ if (IsWrite(Insn)) { ++ Value = ReadReg(UContext, RtField(Insn)); ++ memcpy(Bytes, &Value, Size); ++ const auto Scattered = CopyPieces(Bytes, Pieces, Parts, false); ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ return Scattered; ++ } ++ memcpy(&Value, Bytes, Size); ++ std::atomic_thread_fence(std::memory_order_seq_cst); ++ WriteReg(UContext, RtField(Insn), ExtendOrdered(Insn, Value)); ++ return Parts; ++ } ++ ++ constexpr int HeldSignals[] = {SIGSEGV, SIGBUS, SIGTRAP}; ++ ++ constexpr uint64_t HeldSignalMask() { ++ uint64_t Mask = 0; ++ for (int Sig : HeldSignals) { ++ Mask |= 1ULL << (Sig - 1); ++ } ++ return Mask; ++ } ++ ++ constexpr int HeldSignalSlot(int Signal) { ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (HeldSignals[Slot] == Signal) { ++ return Slot; ++ } ++ } ++ return -1; ++ } ++ ++ template ++ bool DeferWhileHeld(HoldState& Hold, int Signal, const siginfo_t* Info) { ++ const int Slot = HeldSignalSlot(Signal); ++ if (!Hold.Held || Info->si_code > SI_USER || Slot < 0) { ++ return false; ++ } ++ Hold.Deferred |= 1U << Slot; ++ Hold.DeferredInfo[Slot] = *Info; ++ return true; ++ } ++ ++ template ++ uint64_t ReleaseMappings(HoldState& Hold) { ++ if (!Hold.Held) { ++ return 0; ++ } ++ FEX::HLE::_SyscallHandler->VMATracking.Mutex.unlock_shared(); ++ Hold.Held = false; ++ uint64_t Requeued = 0; ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (Hold.Deferred & (1U << Slot)) { ++ Requeued |= 1ULL << (HeldSignals[Slot] - 1); ++ } ++ } ++ if (Requeued == 0) { ++ return 0; ++ } ++ ::syscall(SYS_rt_sigprocmask, SIG_BLOCK, &Requeued, nullptr, sizeof(Requeued)); ++ const auto Process = ::syscall(SYS_getpid); ++ const auto Self = ::syscall(SYS_gettid); ++ for (int Slot = 0; Slot < static_cast(std::size(HeldSignals)); ++Slot) { ++ if (Hold.Deferred & (1U << Slot)) { ++ ::syscall(SYS_rt_tgsigqueueinfo, Process, Self, HeldSignals[Slot], &Hold.DeferredInfo[Slot]); ++ } ++ } ++ Hold.Deferred = 0; ++ return Requeued; ++ } ++ ++ template ++ class MappingHold final { ++ public: ++ explicit MappingHold(HoldState& Hold, bool Deliver = false) ++ : Hold {Hold} ++ , Deliver {Deliver} { ++ const uint64_t All = ~0ULL; ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &All, &Mask, sizeof(Mask)); ++ FEX::HLE::_SyscallHandler->VMATracking.Mutex.lock_shared(); ++ Hold.Held = true; ++ const uint64_t Blocked = ~HeldSignalMask(); ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &Blocked, nullptr, sizeof(Blocked)); ++ } ++ MappingHold(const MappingHold&) = delete; ++ MappingHold& operator=(const MappingHold&) = delete; ++ ~MappingHold() { ++ if (!Kept) { ++ const uint64_t Requeued = ReleaseMappings(Hold); ++ const uint64_t Restored = Deliver ? Mask : Mask | Requeued; ++ ::syscall(SYS_rt_sigprocmask, SIG_SETMASK, &Restored, nullptr, sizeof(Restored)); ++ } ++ } ++ void Keep() { ++ Kept = true; ++ } ++ ++ private: ++ HoldState& Hold; ++ uint64_t Mask {}; ++ bool Deliver {}; ++ bool Kept {}; ++ }; ++ ++ int PickScratch(uint32_t Insn) { ++ constexpr int Candidates[] = {16, 17, 9, 10, 11, 12, 13, 14, 15, 8, 7, 6, 5, 4, 3, 2}; ++ for (auto Reg : Candidates) { ++ const auto R = static_cast(Reg); ++ if (R != RtField(Insn) && R != RnField(Insn) && R != Rt2Field(Insn) && R != RsField(Insn)) { ++ return Reg; ++ } ++ } ++ return -1; ++ } ++ ++ constexpr uint32_t TrapInstruction = 0xd4200000 | (0xf3e << 5); ++ ++ using TrapState = decltype(FEX::HLE::ThreadStateObject::HighMemoryTrap); ++ ++ bool EnsureTrapCode(TrapState& Trap) { ++ if (!Trap.Code) { ++ void* Page = FEXCore::Allocator::VirtualAlloc(FEXCore::Utils::FEX_PAGE_SIZE, true); ++ if (Page == MAP_FAILED || Page == nullptr) { ++ return false; ++ } ++ Trap.Code = static_cast(Page); ++ } ++ return true; ++ } ++ ++ void ArmTrap(TrapState& Trap, void* UContext, uint32_t Instruction, uint64_t ScratchValue, bool Probe) { ++ auto* Code = reinterpret_cast(Trap.Code); ++ Code[0] = Instruction; ++ Code[1] = TrapInstruction; ++ __builtin___clear_cache(reinterpret_cast(Code), reinterpret_cast(Code + 2)); ++ Trap.Probe = Probe; ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, ScratchValue); ++ ArchHelpers::Context::SetPc(UContext, reinterpret_cast(Code)); ++ Trap.Active = true; ++ } ++ ++ void ArmProbe(TrapState& Trap, void* UContext, uint64_t Guest, uint64_t Host) { ++ Trap.Parts = 0; ++ Trap.Delta = Host - Guest; ++ ArmTrap(Trap, UContext, ProbeInstruction(Trap.Scratch), Host, true); ++ } ++ ++ void LeaveTrap(TrapState& Trap, void* UContext, uint64_t ResumePC) { ++ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask)); ++ ArchHelpers::Context::SetPc(UContext, ResumePC); ++ Trap.Parts = 0; ++ Trap.Probe = false; ++ Trap.Active = false; ++ ReleaseMappings(Trap.Mappings); ++ } ++ ++ void RedeliverFromTrap(TrapState& Trap, siginfo_t* SigInfo, void* UContext) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore); ++ SigInfo->si_addr = reinterpret_cast(reinterpret_cast(SigInfo->si_addr) - Trap.Delta); ++ LeaveTrap(Trap, UContext, Trap.ResumePC - 4); ++ } ++ ++ constexpr uint64_t MaxIoVectors = 1024; ++ ++ enum class VectorKind : uint8_t { ++ None, ++ Io, ++ SentMessage, ++ ReceivedMessage, ++ SentMessageArray, ++ ReceivedMessageArray, ++ IoSubmit, ++ IoEvents, ++ PageList, ++ FutexWaiters, ++ FutexRequeue, ++ FileControl, ++ Capabilities, ++ PerfAttribute, ++ SchedulerAttribute, ++ HandleAt, ++ OpenHandle, ++ MountRequest, ++ LandlockRule, ++ }; ++ ++ constexpr uint8_t BitmapElements = 0xff; ++ constexpr uint8_t MessageElements = 0xfe; ++ constexpr uint8_t PageElements = 0xfd; ++ ++ struct Layout { ++ uint8_t Pointers; ++ uint64_t Lengths; ++ VectorKind Vector {VectorKind::None}; ++ uint64_t ElementSizes {}; ++ uint64_t FixedSizes {}; ++ uint8_t Strings {}; ++ }; ++ ++ struct LayoutEntry { ++ uint32_t Syscall; ++ Layout Arguments; ++ }; ++ ++ constexpr uint8_t Ptr(uint32_t Arg) { ++ return 1U << Arg; ++ } ++ ++ constexpr uint64_t CountWord = 0x10; ++ constexpr uint64_t CountSigned = 0x20; ++ ++ constexpr uint64_t Sized(uint32_t Pointer, uint32_t Length) { ++ return static_cast(Length + 1) << (Pointer * 8); ++ } ++ ++ constexpr uint64_t IntSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | ((CountWord | CountSigned) << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t UintSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | (CountWord << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t LongSized(uint32_t Pointer, uint32_t Length) { ++ return Sized(Pointer, Length) | (CountSigned << (Pointer * 8)); ++ } ++ ++ constexpr uint64_t Through(uint32_t Pointer, uint32_t Length) { ++ return static_cast(Length + 9) << (Pointer * 8); ++ } ++ ++ constexpr uint32_t LengthArgument(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & 0x7; ++ } ++ ++ constexpr bool LengthThroughPointer(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & 0x8; ++ } ++ ++ constexpr uint64_t CountKind(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.Lengths >> (Pointer * 8)) & (CountWord | CountSigned); ++ } ++ ++ constexpr uint64_t CountValue(const Layout& Arguments, uint32_t Pointer, uint64_t Raw) { ++ const auto Kind = CountKind(Arguments, Pointer); ++ int64_t Value = static_cast(Raw); ++ if (Kind == (CountWord | CountSigned)) { ++ Value = static_cast(Raw); ++ } else if (Kind == CountWord) { ++ return static_cast(Raw); ++ } else if (Kind == 0) { ++ return Raw; ++ } ++ return Value < 0 ? 0 : static_cast(Value); ++ } ++ ++ constexpr uint64_t Fixed(uint32_t Pointer, uint64_t Bytes) { ++ return Bytes << (Pointer * 10); ++ } ++ ++ constexpr uint64_t FixedSize(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.FixedSizes >> (Pointer * 10)) & 0x3ff; ++ } ++ ++ constexpr uint8_t Text(uint32_t Arg) { ++ return 1U << Arg; ++ } ++ ++ constexpr uint64_t Each(uint32_t Pointer, uint8_t Size) { ++ return static_cast(Size) << (Pointer * 8); ++ } ++ ++ constexpr uint8_t ElementSize(const Layout& Arguments, uint32_t Pointer) { ++ return (Arguments.ElementSizes >> (Pointer * 8)) & 0xff; ++ } ++ ++ constexpr uint64_t PollFdSize = 8; ++ constexpr uint64_t EpollEventSize = 12; ++ constexpr uint64_t GroupIdSize = 4; ++ constexpr uint64_t IntSize = 4; ++ constexpr uint64_t PointerSize = 8; ++ constexpr uint64_t SemaphoreOpSize = 6; ++ constexpr uint64_t IoEventSize = 32; ++ constexpr uint64_t FutexWaitSize = 24; ++ constexpr uint64_t StatSize = 144; ++ constexpr uint64_t StatfsSize = 120; ++ constexpr uint64_t StatxSize = 256; ++ constexpr uint64_t TimeSize = 16; ++ constexpr uint64_t TimePairSize = 32; ++ constexpr uint64_t TimezoneSize = 8; ++ constexpr uint64_t LongSize = 8; ++ constexpr uint64_t FdPairSize = 8; ++ constexpr uint64_t UtimbufSize = 16; ++ constexpr uint64_t SigactionSize = 32; ++ constexpr uint64_t SiginfoSize = 128; ++ constexpr uint64_t SigeventSize = 64; ++ constexpr uint64_t StackSize = 24; ++ constexpr uint64_t RlimitSize = 16; ++ constexpr uint64_t RusageSize = 144; ++ constexpr uint64_t SysinfoSize = 112; ++ constexpr uint64_t TmsSize = 32; ++ constexpr uint64_t UtsnameSize = 390; ++ constexpr uint64_t TimexSize = 208; ++ constexpr uint64_t UstatSize = 32; ++ constexpr uint64_t UserDescSize = 16; ++ constexpr uint64_t MqAttrSize = 64; ++ constexpr uint64_t IoControlBlockSize = 64; ++ constexpr uint64_t IoEventObjectOffset = 8; ++ constexpr uint64_t CapHeaderSize = 8; ++ constexpr uint64_t CapDataSize = 12; ++ constexpr uint32_t CapVersion1 = 0x19980330; ++ constexpr uint32_t CapVersion2 = 0x20071026; ++ constexpr uint32_t CapVersion3 = 0x20080522; ++ constexpr uint64_t FileLockSize = 32; ++ constexpr uint64_t IoUringParamsSize = 120; ++ constexpr uint64_t CachestatRangeSize = 16; ++ constexpr uint64_t CachestatSize = 40; ++ constexpr uint64_t LandlockPathRuleSize = 12; ++ constexpr uint64_t LandlockPortRuleSize = 16; ++ constexpr uint64_t KcmpSlotSize = 12; ++ constexpr uint64_t KexecSegmentSize = 32; ++ constexpr uint64_t SigsetArgumentSize = 16; ++ constexpr uint64_t SocketAddressSize = 128; ++ constexpr uint64_t MessageHeaderSize = 8; ++ constexpr uint64_t MaxString = 4096; ++ constexpr uint64_t StringChunk = 256; ++ constexpr uint64_t MaxPageList = 65536; ++ constexpr uint64_t MaxFutexWaiters = 128; ++ constexpr uint64_t MaxElements = 1ULL << 32; ++ ++ bool ByteLength(const Layout& Arguments, uint32_t Pointer, uint64_t Count, uint64_t* Bytes) { ++ const auto Size = ElementSize(Arguments, Pointer); ++ if (Size == 0) { ++ *Bytes = Count; ++ return true; ++ } ++ if (Size == BitmapElements) { ++ const auto Elements = static_cast(Count); ++ *Bytes = (static_cast(Elements) + 63) / 64 * 8; ++ return true; ++ } ++ if (Size == PageElements) { ++ *Bytes = Count / FEXCore::Utils::FEX_PAGE_SIZE + (Count % FEXCore::Utils::FEX_PAGE_SIZE != 0); ++ return true; ++ } ++ if (Count >= MaxElements) { ++ return false; ++ } ++ if (Size == MessageElements) { ++ *Bytes = Count + MessageHeaderSize; ++ return true; ++ } ++ *Bytes = Count * Size; ++ return true; ++ } ++ ++ constexpr LayoutEntry LayoutEntries[] = { ++ {x64::SYSCALL_x64_read, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_write, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_open, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_stat, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize), Text(0)}}, ++ {x64::SYSCALL_x64_fstat, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize)}}, ++ {x64::SYSCALL_x64_lstat, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatSize), Text(0)}}, ++ {x64::SYSCALL_x64_poll, {Ptr(0), UintSized(0, 1), VectorKind::None, Each(0, PollFdSize)}}, ++ {x64::SYSCALL_x64_rt_sigaction, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, SigactionSize) | Fixed(2, SigactionSize)}}, ++ {x64::SYSCALL_x64_rt_sigprocmask, {Ptr(1) | Ptr(2), Sized(1, 3) | Sized(2, 3)}}, ++ {x64::SYSCALL_x64_ioctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_pread_64, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pwrite_64, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_readv, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_writev, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_access, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_pipe, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, FdPairSize)}}, ++ {x64::SYSCALL_x64_select, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4), IntSized(1, 0) | IntSized(2, 0) | IntSized(3, 0), VectorKind::None, Each(1, BitmapElements) | Each(2, BitmapElements) | Each(3, BitmapElements), Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_msync, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_mincore, {Ptr(0) | Ptr(2), Sized(0, 1) | Sized(2, 1), VectorKind::None, Each(2, PageElements)}}, ++ {x64::SYSCALL_x64_shmctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_nanosleep, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_getitimer, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_setitimer, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, TimePairSize) | Fixed(2, TimePairSize)}}, ++ {x64::SYSCALL_x64_sendfile, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, LongSize)}}, ++ {x64::SYSCALL_x64_connect, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_accept, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_sendto, {Ptr(1) | Ptr(4), Sized(1, 2) | IntSized(4, 5)}}, ++ {x64::SYSCALL_x64_recvfrom, {Ptr(1) | Ptr(4) | Ptr(5), Sized(1, 2) | Through(4, 5), VectorKind::None, 0, Fixed(4, SocketAddressSize) | Fixed(5, IntSize)}}, ++ {x64::SYSCALL_x64_sendmsg, {0, 0, VectorKind::SentMessage}}, ++ {x64::SYSCALL_x64_recvmsg, {0, 0, VectorKind::ReceivedMessage}}, ++ {x64::SYSCALL_x64_bind, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_getsockname, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_getpeername, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_socketpair, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, FdPairSize)}}, ++ {x64::SYSCALL_x64_setsockopt, {Ptr(3), IntSized(3, 4)}}, ++ {x64::SYSCALL_x64_getsockopt, {Ptr(3) | Ptr(4), Through(3, 4), VectorKind::None, 0, Fixed(4, IntSize)}}, ++ {x64::SYSCALL_x64_execve, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_wait4, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, IntSize) | Fixed(3, RusageSize)}}, ++ {x64::SYSCALL_x64_uname, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UtsnameSize)}}, ++ {x64::SYSCALL_x64_semop, {Ptr(1), UintSized(1, 2), VectorKind::None, Each(1, SemaphoreOpSize)}}, ++ {x64::SYSCALL_x64_semctl, {Ptr(3)}}, ++ {x64::SYSCALL_x64_msgsnd, {Ptr(1), Sized(1, 2), VectorKind::None, Each(1, MessageElements)}}, ++ {x64::SYSCALL_x64_msgrcv, {Ptr(1), Sized(1, 2), VectorKind::None, Each(1, MessageElements)}}, ++ {x64::SYSCALL_x64_msgctl, {Ptr(2)}}, ++ {x64::SYSCALL_x64_fcntl, {0, 0, VectorKind::FileControl}}, ++ {x64::SYSCALL_x64_truncate, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_getdents, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_getcwd, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_chdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_rename, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_mkdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_rmdir, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_creat, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_link, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_unlink, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_symlink, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_readlink, {Ptr(0) | Ptr(1), IntSized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_chmod, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_chown, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_lchown, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_gettimeofday, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimezoneSize)}}, ++ {x64::SYSCALL_x64_getrlimit, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RlimitSize)}}, ++ {x64::SYSCALL_x64_getrusage, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RusageSize)}}, ++ {x64::SYSCALL_x64_sysinfo, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, SysinfoSize)}}, ++ {x64::SYSCALL_x64_times, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, TmsSize)}}, ++ {x64::SYSCALL_x64_syslog, {Ptr(1), IntSized(1, 2)}}, ++ {x64::SYSCALL_x64_getgroups, {Ptr(1), IntSized(1, 0), VectorKind::None, Each(1, GroupIdSize)}}, ++ {x64::SYSCALL_x64_setgroups, {Ptr(1), IntSized(1, 0), VectorKind::None, Each(1, GroupIdSize)}}, ++ {x64::SYSCALL_x64_getresuid, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_getresgid, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_capget, {Ptr(0), 0, VectorKind::Capabilities, 0, Fixed(0, CapHeaderSize)}}, ++ {x64::SYSCALL_x64_capset, {Ptr(0), 0, VectorKind::Capabilities, 0, Fixed(0, CapHeaderSize)}}, ++ {x64::SYSCALL_x64_rt_sigpending, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_rt_sigtimedwait, {Ptr(0) | Ptr(1) | Ptr(2), Sized(0, 3), VectorKind::None, 0, Fixed(1, SiginfoSize) | Fixed(2, TimeSize)}}, ++ {x64::SYSCALL_x64_rt_sigqueueinfo, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, SiginfoSize)}}, ++ {x64::SYSCALL_x64_rt_sigsuspend, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_sigaltstack, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, StackSize) | Fixed(1, StackSize)}}, ++ {x64::SYSCALL_x64_utime, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, UtimbufSize), Text(0)}}, ++ {x64::SYSCALL_x64_mknod, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_uselib, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_ustat, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, UstatSize)}}, ++ {x64::SYSCALL_x64_statfs, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatfsSize), Text(0)}}, ++ {x64::SYSCALL_x64_fstatfs, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, StatfsSize)}}, ++ {x64::SYSCALL_x64_sysfs, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_sched_setparam, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_sched_getparam, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_sched_setscheduler, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_sched_rr_get_interval, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_mlock, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_munlock, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_modify_ldt, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pivot_root, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64__sysctl, {Ptr(0)}}, ++ {x64::SYSCALL_x64_adjtimex, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, TimexSize)}}, ++ {x64::SYSCALL_x64_setrlimit, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, RlimitSize)}}, ++ {x64::SYSCALL_x64_chroot, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_acct, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_settimeofday, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, TimeSize) | Fixed(1, TimezoneSize)}}, ++ {x64::SYSCALL_x64_mount, {Ptr(0) | Ptr(1) | Ptr(2) | Ptr(4), 0, VectorKind::None, 0, 0, Text(0) | Text(1) | Text(2)}}, ++ {x64::SYSCALL_x64_umount2, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_swapon, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_swapoff, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_reboot, {Ptr(3), 0, VectorKind::None, 0, 0, Text(3)}}, ++ {x64::SYSCALL_x64_sethostname, {Ptr(0), IntSized(0, 1)}}, ++ {x64::SYSCALL_x64_setdomainname, {Ptr(0), IntSized(0, 1)}}, ++ {x64::SYSCALL_x64_create_module, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_init_module, {Ptr(0) | Ptr(2), Sized(0, 1), VectorKind::None, 0, 0, Text(2)}}, ++ {x64::SYSCALL_x64_delete_module, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_get_kernel_syms, {Ptr(0)}}, ++ {x64::SYSCALL_x64_query_module, {Ptr(0) | Ptr(2) | Ptr(4), Sized(2, 3)}}, ++ {x64::SYSCALL_x64_quotactl, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_nfsservctl, {Ptr(1) | Ptr(2)}}, ++ {x64::SYSCALL_x64_setxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lsetxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fsetxattr, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_getxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lgetxattr, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fgetxattr, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_listxattr, {Ptr(0) | Ptr(1), Sized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_llistxattr, {Ptr(0) | Ptr(1), Sized(1, 2), VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_flistxattr, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_removexattr, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_lremovexattr, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_fremovexattr, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_time, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, LongSize)}}, ++ {x64::SYSCALL_x64_futex, {Ptr(0) | Ptr(3) | Ptr(4), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(3, TimeSize) | Fixed(4, IntSize)}}, ++ {x64::SYSCALL_x64_sched_setaffinity, {Ptr(2), UintSized(2, 1)}}, ++ {x64::SYSCALL_x64_sched_getaffinity, {Ptr(2), UintSized(2, 1)}}, ++ {x64::SYSCALL_x64_set_thread_area, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UserDescSize)}}, ++ {x64::SYSCALL_x64_io_setup, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, LongSize)}}, ++ {x64::SYSCALL_x64_io_getevents, {Ptr(3) | Ptr(4), LongSized(3, 2), VectorKind::IoEvents, Each(3, IoEventSize), Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_io_submit, {Ptr(2), LongSized(2, 1), VectorKind::IoSubmit, Each(2, PointerSize)}}, ++ {x64::SYSCALL_x64_io_cancel, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, IoControlBlockSize) | Fixed(2, IoEventSize)}}, ++ {x64::SYSCALL_x64_get_thread_area, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, UserDescSize)}}, ++ {x64::SYSCALL_x64_lookup_dcookie, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_remap_file_pages, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_getdents64, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_semtimedop, {Ptr(1) | Ptr(3), UintSized(1, 2), VectorKind::None, Each(1, SemaphoreOpSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_timer_create, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, SigeventSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_timer_settime, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimePairSize) | Fixed(3, TimePairSize)}}, ++ {x64::SYSCALL_x64_timer_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_clock_settime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_getres, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimeSize)}}, ++ {x64::SYSCALL_x64_clock_nanosleep, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimeSize) | Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_epoll_wait, {Ptr(1), IntSized(1, 2), VectorKind::None, Each(1, EpollEventSize)}}, ++ {x64::SYSCALL_x64_epoll_ctl, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, EpollEventSize)}}, ++ {x64::SYSCALL_x64_utimes, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize), Text(0)}}, ++ {x64::SYSCALL_x64_mbind, {Ptr(0) | Ptr(3), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_set_mempolicy, {Ptr(1)}}, ++ {x64::SYSCALL_x64_get_mempolicy, {Ptr(0) | Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(0, IntSize)}}, ++ {x64::SYSCALL_x64_mq_open, {Ptr(0) | Ptr(3), 0, VectorKind::None, 0, Fixed(3, MqAttrSize), Text(0)}}, ++ {x64::SYSCALL_x64_mq_unlink, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_mq_timedsend, {Ptr(1) | Ptr(4), Sized(1, 2), VectorKind::None, 0, Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_mq_timedreceive, {Ptr(1) | Ptr(3) | Ptr(4), Sized(1, 2), VectorKind::None, 0, Fixed(3, IntSize) | Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_mq_notify, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, SigeventSize)}}, ++ {x64::SYSCALL_x64_mq_getsetattr, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, MqAttrSize) | Fixed(2, MqAttrSize)}}, ++ {x64::SYSCALL_x64_kexec_load, {Ptr(2), Sized(2, 1), VectorKind::None, Each(2, KexecSegmentSize)}}, ++ {x64::SYSCALL_x64_waitid, {Ptr(2) | Ptr(4), 0, VectorKind::None, 0, Fixed(2, SiginfoSize) | Fixed(4, RusageSize)}}, ++ {x64::SYSCALL_x64_add_key, {Ptr(0) | Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(0) | Text(1)}}, ++ {x64::SYSCALL_x64_request_key, {Ptr(0) | Ptr(1) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0) | Text(1) | Text(2)}}, ++ {x64::SYSCALL_x64_keyctl, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4)}}, ++ {x64::SYSCALL_x64_inotify_add_watch, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_migrate_pages, {Ptr(2) | Ptr(3)}}, ++ {x64::SYSCALL_x64_openat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mkdirat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mknodat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_fchownat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_futimesat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, TimePairSize), Text(1)}}, ++ {x64::SYSCALL_x64_newfstatat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, StatSize), Text(1)}}, ++ {x64::SYSCALL_x64_unlinkat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_renameat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_linkat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_symlinkat, {Ptr(0) | Ptr(2), 0, VectorKind::None, 0, 0, Text(0) | Text(2)}}, ++ {x64::SYSCALL_x64_readlinkat, {Ptr(1) | Ptr(2), IntSized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_fchmodat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_faccessat, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_pselect6, {Ptr(1) | Ptr(2) | Ptr(3) | Ptr(4) | Ptr(5), IntSized(1, 0) | IntSized(2, 0) | IntSized(3, 0), VectorKind::None, Each(1, BitmapElements) | Each(2, BitmapElements) | Each(3, BitmapElements), Fixed(4, TimeSize) | Fixed(5, SigsetArgumentSize)}}, ++ {x64::SYSCALL_x64_ppoll, {Ptr(0) | Ptr(2) | Ptr(3), UintSized(0, 1) | Sized(3, 4), VectorKind::None, Each(0, PollFdSize), Fixed(2, TimeSize)}}, ++ {x64::SYSCALL_x64_get_robust_list, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, PointerSize) | Fixed(2, PointerSize)}}, ++ {x64::SYSCALL_x64_splice, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, LongSize) | Fixed(3, LongSize)}}, ++ {x64::SYSCALL_x64_vmsplice, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_move_pages, {Ptr(2) | Ptr(3) | Ptr(4), Sized(2, 1) | Sized(3, 1) | Sized(4, 1), VectorKind::PageList, Each(2, PointerSize) | Each(3, IntSize) | Each(4, IntSize)}}, ++ {x64::SYSCALL_x64_utimensat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(2, TimePairSize), Text(1)}}, ++ {x64::SYSCALL_x64_epoll_pwait, {Ptr(1) | Ptr(4), IntSized(1, 2) | Sized(4, 5), VectorKind::None, Each(1, EpollEventSize)}}, ++ {x64::SYSCALL_x64_signalfd, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_timerfd_settime, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, TimePairSize) | Fixed(3, TimePairSize)}}, ++ {x64::SYSCALL_x64_timerfd_gettime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimePairSize)}}, ++ {x64::SYSCALL_x64_accept4, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(1, SocketAddressSize) | Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_signalfd4, {Ptr(1), Sized(1, 2)}}, ++ {x64::SYSCALL_x64_pipe2, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, FdPairSize)}}, ++ {x64::SYSCALL_x64_preadv, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pwritev, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_rt_tgsigqueueinfo, {Ptr(3), 0, VectorKind::None, 0, Fixed(3, SiginfoSize)}}, ++ {x64::SYSCALL_x64_perf_event_open, {0, 0, VectorKind::PerfAttribute}}, ++ {x64::SYSCALL_x64_recvmmsg, {Ptr(4), 0, VectorKind::ReceivedMessageArray, 0, Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_fanotify_mark, {Ptr(4), 0, VectorKind::None, 0, 0, Text(4)}}, ++ {x64::SYSCALL_x64_prlimit_64, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, Fixed(2, RlimitSize) | Fixed(3, RlimitSize)}}, ++ {x64::SYSCALL_x64_name_to_handle_at, {Ptr(1) | Ptr(3), 0, VectorKind::HandleAt, 0, Fixed(3, IntSize), Text(1)}}, ++ {x64::SYSCALL_x64_open_by_handle_at, {0, 0, VectorKind::OpenHandle}}, ++ {x64::SYSCALL_x64_clock_adjtime, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, TimexSize)}}, ++ {x64::SYSCALL_x64_sendmmsg, {0, 0, VectorKind::SentMessageArray}}, ++ {x64::SYSCALL_x64_getcpu, {Ptr(0) | Ptr(1), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_kcmp, {Ptr(4), 0, VectorKind::None, 0, Fixed(4, KcmpSlotSize)}}, ++ {x64::SYSCALL_x64_finit_module, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_sched_setattr, {0, 0, VectorKind::SchedulerAttribute}}, ++ {x64::SYSCALL_x64_sched_getattr, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_renameat2, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_seccomp, {Ptr(2)}}, ++ {x64::SYSCALL_x64_getrandom, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_memfd_create, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_kexec_file_load, {Ptr(3), Sized(3, 2)}}, ++ {x64::SYSCALL_x64_bpf, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_execveat, {Ptr(1) | Ptr(2) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_mlock2, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_copy_file_range, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, Fixed(1, LongSize) | Fixed(3, LongSize)}}, ++ {x64::SYSCALL_x64_preadv2, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pwritev2, {0, 0, VectorKind::Io}}, ++ {x64::SYSCALL_x64_pkey_mprotect, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_statx, {Ptr(1) | Ptr(4), 0, VectorKind::None, 0, Fixed(4, StatxSize), Text(1)}}, ++ {x64::SYSCALL_x64_io_pgetevents, {Ptr(3) | Ptr(4) | Ptr(5), LongSized(3, 2), VectorKind::IoEvents, Each(3, IoEventSize), Fixed(4, TimeSize) | Fixed(5, SigsetArgumentSize)}}, ++ {x64::SYSCALL_x64_rseq, {Ptr(0), UintSized(0, 1)}}, ++ {x64::SYSCALL_x64_pidfd_send_signal, {Ptr(2), 0, VectorKind::None, 0, Fixed(2, SiginfoSize)}}, ++ {x64::SYSCALL_x64_io_uring_setup, {Ptr(1), 0, VectorKind::None, 0, Fixed(1, IoUringParamsSize)}}, ++ {x64::SYSCALL_x64_io_uring_enter, {Ptr(4), Sized(4, 5)}}, ++ {x64::SYSCALL_x64_io_uring_register, {Ptr(2)}}, ++ {x64::SYSCALL_x64_open_tree, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_move_mount, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_fsopen, {Ptr(0), 0, VectorKind::None, 0, 0, Text(0)}}, ++ {x64::SYSCALL_x64_fsconfig, {Ptr(2) | Ptr(3), 0, VectorKind::None, 0, 0, Text(2)}}, ++ {x64::SYSCALL_x64_fspick, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_openat2, {Ptr(1) | Ptr(2), Sized(2, 3), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_faccessat2, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_process_madvise, {Ptr(1)}}, ++ {x64::SYSCALL_x64_epoll_pwait2, {Ptr(1) | Ptr(3) | Ptr(4), IntSized(1, 2) | Sized(4, 5), VectorKind::None, Each(1, EpollEventSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_mount_setattr, {Ptr(1) | Ptr(3), Sized(3, 4), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_quotactl_fd, {Ptr(3)}}, ++ {x64::SYSCALL_x64_landlock_create_ruleset, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_landlock_add_rule, {0, 0, VectorKind::LandlockRule}}, ++ {x64::SYSCALL_x64_futex_waitv, {Ptr(0) | Ptr(3), UintSized(0, 1), VectorKind::FutexWaiters, Each(0, FutexWaitSize), Fixed(3, TimeSize)}}, ++ {x64::SYSCALL_x64_set_mempolicy_home_node, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_cachestat, {Ptr(1) | Ptr(2), 0, VectorKind::None, 0, Fixed(1, CachestatRangeSize) | Fixed(2, CachestatSize)}}, ++ {x64::SYSCALL_x64_fchmodat2, {Ptr(1), 0, VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_futex_wake, {Ptr(0), 0, VectorKind::None, 0, Fixed(0, IntSize)}}, ++ {x64::SYSCALL_x64_futex_wait, {Ptr(0) | Ptr(4), 0, VectorKind::None, 0, Fixed(0, IntSize) | Fixed(4, TimeSize)}}, ++ {x64::SYSCALL_x64_futex_requeue, {Ptr(0), 0, VectorKind::FutexRequeue, 0, Fixed(0, 2 * FutexWaitSize)}}, ++ {x64::SYSCALL_x64_statmount, {Ptr(1), Sized(1, 2), VectorKind::MountRequest}}, ++ {x64::SYSCALL_x64_listmount, {Ptr(1), Sized(1, 2), VectorKind::MountRequest, Each(1, PointerSize)}}, ++ {x64::SYSCALL_x64_lsm_get_self_attr, {Ptr(1) | Ptr(2), Through(1, 2), VectorKind::None, 0, Fixed(2, IntSize)}}, ++ {x64::SYSCALL_x64_lsm_set_self_attr, {Ptr(1), UintSized(1, 2)}}, ++ {x64::SYSCALL_x64_lsm_list_modules, {Ptr(0) | Ptr(1), Through(0, 1), VectorKind::None, 0, Fixed(1, IntSize)}}, ++ {x64::SYSCALL_x64_mseal, {Ptr(0), Sized(0, 1)}}, ++ {x64::SYSCALL_x64_setxattrat, {Ptr(1) | Ptr(3) | Ptr(4), Sized(4, 5), VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_getxattrat, {Ptr(1) | Ptr(3) | Ptr(4), Sized(4, 5), VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ {x64::SYSCALL_x64_listxattrat, {Ptr(1) | Ptr(3), Sized(3, 4), VectorKind::None, 0, 0, Text(1)}}, ++ {x64::SYSCALL_x64_removexattrat, {Ptr(1) | Ptr(3), 0, VectorKind::None, 0, 0, Text(1) | Text(3)}}, ++ }; ++ ++ constexpr uint32_t LayoutCount() { ++ uint32_t Max = 0; ++ for (const auto& Entry : LayoutEntries) { ++ Max = std::max(Max, Entry.Syscall); ++ } ++ return Max + 1; ++ } ++ ++ constexpr std::array BuildLayouts() { ++ std::array Table {}; ++ for (const auto& Entry : LayoutEntries) { ++ Table[Entry.Syscall] = Entry.Arguments; ++ } ++ return Table; ++ } ++ ++ constexpr auto Layouts = BuildLayouts(); ++ ++ constexpr bool LayoutsAreConsistent() { ++ for (size_t i = 0; i < std::size(LayoutEntries); ++i) { ++ for (size_t j = i + 1; j < std::size(LayoutEntries); ++j) { ++ if (LayoutEntries[i].Syscall == LayoutEntries[j].Syscall) { ++ return false; ++ } ++ } ++ const auto& Arguments = LayoutEntries[i].Arguments; ++ if ((Arguments.Strings & ~Arguments.Pointers) != 0) { ++ return false; ++ } ++ for (uint32_t Arg = 0; Arg < 6; ++Arg) { ++ const bool Pointer = Arguments.Pointers & Ptr(Arg); ++ const auto Length = LengthArgument(Arguments, Arg); ++ const bool Indirect = LengthThroughPointer(Arguments, Arg); ++ const auto Bytes = FixedSize(Arguments, Arg); ++ const bool String = Arguments.Strings & Ptr(Arg); ++ const bool Elements = ElementSize(Arguments, Arg) != 0; ++ if (CountKind(Arguments, Arg) != 0 && (Length == 0 || Indirect)) { ++ return false; ++ } ++ if (!Pointer && (Length != 0 || Indirect || Bytes != 0 || Elements)) { ++ return false; ++ } ++ if (String && (Length != 0 || Indirect || Bytes != 0)) { ++ return false; ++ } ++ if (Elements && (Length == 0 || Indirect)) { ++ return false; ++ } ++ if (Length == 0) { ++ if (Indirect) { ++ return false; ++ } ++ continue; ++ } ++ if (Length > 6) { ++ return false; ++ } ++ const bool Target = Arguments.Pointers & Ptr(Length - 1); ++ if (Indirect ? !Target : (Target || Bytes != 0)) { ++ return false; ++ } ++ } ++ } ++ return true; ++ } ++ ++ constexpr bool LeavesUntranslated(std::initializer_list Syscalls) { ++ for (const auto Syscall : Syscalls) { ++ if (Syscall < Layouts.size() && (Layouts[Syscall].Pointers != 0 || Layouts[Syscall].Vector != VectorKind::None)) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ static_assert(LayoutsAreConsistent()); ++ static_assert(LeavesUntranslated({ ++ x64::SYSCALL_x64_mmap, ++ x64::SYSCALL_x64_mprotect, ++ x64::SYSCALL_x64_munmap, ++ x64::SYSCALL_x64_brk, ++ x64::SYSCALL_x64_rt_sigreturn, ++ x64::SYSCALL_x64_mremap, ++ x64::SYSCALL_x64_madvise, ++ x64::SYSCALL_x64_shmat, ++ x64::SYSCALL_x64_clone, ++ x64::SYSCALL_x64_shmdt, ++ x64::SYSCALL_x64_ptrace, ++ x64::SYSCALL_x64_prctl, ++ x64::SYSCALL_x64_arch_prctl, ++ x64::SYSCALL_x64_set_tid_address, ++ x64::SYSCALL_x64_set_robust_list, ++ x64::SYSCALL_x64_process_vm_readv, ++ x64::SYSCALL_x64_process_vm_writev, ++ x64::SYSCALL_x64_clone3, ++ x64::SYSCALL_x64_map_shadow_stack, ++ })); ++ ++ struct iovec* VectorCopy(ArgumentStorage* Storage, uint64_t Entries) { ++ if (Entries <= std::size(Storage->Inline)) { ++ return Storage->Inline; ++ } ++ Storage->Heap.resize(std::min(Entries, MaxIoVectors)); ++ return Storage->Heap.data(); ++ } ++ ++ uint64_t TranslateIoVector(uint64_t Vector, uint64_t Entries, struct iovec* Copy, uint64_t* Out, bool* Copied = nullptr) { ++ if (Entries == 0 || Entries > MaxIoVectors) { ++ return 0; ++ } ++ const auto Bytes = Entries * sizeof(struct iovec); ++ uint64_t HostVector {}; ++ if (!TranslateRange(Vector, Bytes, &HostVector)) { ++ return -EFAULT; ++ } ++ *Out = HostVector; ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(HostVector), Bytes) != 0) { ++ return 0; ++ } ++ if (Copied) { ++ *Copied = true; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Entries; ++i) { ++ const auto Base = reinterpret_cast(Copy[i].iov_base); ++ uint64_t Host {}; ++ if (!TranslateRange(Base, Copy[i].iov_len, &Host)) { ++ return -EFAULT; ++ } ++ if (Host != Base) { ++ Copy[i].iov_base = reinterpret_cast(Host); ++ Changed = true; ++ } ++ } ++ if (Changed) { ++ *Out = reinterpret_cast(Copy); ++ } ++ return 0; ++ } ++ ++ uint64_t TranslateMessageFields(struct msghdr* Message, struct iovec* Copy, bool* Changed, bool* Copied = nullptr) { ++ const auto Name = reinterpret_cast(Message->msg_name); ++ const auto Control = reinterpret_cast(Message->msg_control); ++ const auto Vector = reinterpret_cast(Message->msg_iov); ++ uint64_t HostName {}; ++ uint64_t HostControl {}; ++ uint64_t HostVector = Vector; ++ if (!TranslateRange(Name, Message->msg_namelen, &HostName) || !TranslateRange(Control, Message->msg_controllen, &HostControl)) { ++ return -EFAULT; ++ } ++ if (const auto Result = TranslateIoVector(Vector, Message->msg_iovlen, Copy, &HostVector, Copied); Result != 0) { ++ return Result; ++ } ++ *Changed = HostName != Name || HostControl != Control || HostVector != Vector; ++ Message->msg_name = reinterpret_cast(HostName); ++ Message->msg_control = reinterpret_cast(HostControl); ++ Message->msg_iov = reinterpret_cast(HostVector); ++ return 0; ++ } ++ ++ uint64_t TranslateMessage(uint64_t* Header, bool Received, ArgumentStorage* Storage) { ++ const auto GuestHeader = *Header; ++ uint64_t HostHeader {}; ++ if (!TranslateRange(GuestHeader, sizeof(struct msghdr), &HostHeader)) { ++ return -EFAULT; ++ } ++ *Header = HostHeader; ++ auto* Message = &Storage->Message; ++ if (FaultSafeUserMemAccess::CopyFromUser(Message, reinterpret_cast(HostHeader), sizeof(*Message)) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ if (const auto Result = TranslateMessageFields(Message, VectorCopy(Storage, Message->msg_iovlen), &Changed); Result != 0 || !Changed) { ++ return Result; ++ } ++ if (Received) { ++ Storage->ReceivedHeader = GuestHeader; ++ } ++ *Header = reinterpret_cast(Message); ++ return 0; ++ } ++ ++ template ++ bool WithStableMapping(uint64_t Address, Fn&& Body) { ++ auto* Thread = Contains(Address) ? FEX::HLE::ThreadManager::GetCurrentThreadObject() : nullptr; ++ if (Thread == nullptr || Thread->HighMemoryTrap.Mappings.Held) { ++ return Body(); ++ } ++ MappingHold Hold {Thread->HighMemoryTrap.Mappings, true}; ++ return Body(); ++ } ++ ++ bool CopyToGuest(uint64_t Address, const void* Value, uint64_t Size) { ++ return WithStableMapping(Address, [&] { ++ uint64_t Host {}; ++ return TranslateRange(Address, Size, &Host) && FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Host), Value, Size) == 0; ++ }); ++ } ++ ++ uint64_t TranslateMessages(uint64_t* Args, bool Received, ArgumentStorage* Storage) { ++ auto* Array = &Args[1]; ++ auto* Entries = &Args[2]; ++ const uint64_t Messages = std::min(static_cast(*Entries), MaxIoVectors); ++ if (Messages == 0) { ++ return 0; ++ } ++ constexpr uint64_t Size = sizeof(struct mmsghdr); ++ const auto GuestArray = *Array; ++ uint64_t HostArray {}; ++ if (!TranslateRange(GuestArray, Size, &HostArray)) { ++ return -EFAULT; ++ } ++ Storage->Messages.resize(Messages); ++ auto* Copy = Storage->Messages.data(); ++ uint64_t Ready = 0; ++ bool Contiguous = true; ++ uint64_t Whole {}; ++ if (TranslateRange(GuestArray, Messages * Size, &Whole) && ++ FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(Whole), Messages * Size) == 0) { ++ Ready = Messages; ++ } else { ++ for (; Ready < Messages; ++Ready) { ++ uint64_t Host {}; ++ if (!TranslateRange(GuestArray + Ready * Size, Size, &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Copy[Ready], reinterpret_cast(Host), Size) != 0) { ++ break; ++ } ++ Contiguous = Contiguous && Host == HostArray + Ready * Size; ++ } ++ } ++ if (Ready == 0) { ++ *Array = HostArray; ++ return 0; ++ } ++ uint64_t Vectors = 0; ++ for (uint64_t i = 0; i < Ready; ++i) { ++ if (Copy[i].msg_hdr.msg_iovlen <= MaxIoVectors) { ++ Vectors += Copy[i].msg_hdr.msg_iovlen; ++ } ++ } ++ Storage->Heap.resize(Vectors); ++ Storage->MessageLengths.assign(Ready, 0); ++ bool Changed = !Contiguous; ++ uint64_t Offset = 0; ++ for (uint64_t i = 0; i < Ready; ++i) { ++ const auto Length = Copy[i].msg_hdr.msg_iovlen; ++ auto* Local = Storage->Heap.data() + Offset; ++ bool Translated = false; ++ bool Copied = false; ++ if (const auto Result = TranslateMessageFields(&Copy[i].msg_hdr, Local, &Translated, &Copied); Result != 0) { ++ if (i == 0) { ++ return Result; ++ } ++ Ready = i; ++ break; ++ } ++ if (!Received && Length != 0 && !Copied) { ++ if (i == 0) { ++ *Array = HostArray; ++ return 0; ++ } ++ Ready = i; ++ break; ++ } ++ if (Copied && !Received) { ++ Copy[i].msg_hdr.msg_iov = Local; ++ for (uint64_t j = 0; j < Length; ++j) { ++ Storage->MessageLengths[i] += Local[j].iov_len; ++ } ++ } ++ if (Length <= MaxIoVectors) { ++ Offset += Length; ++ } ++ Changed = Changed || Translated; ++ } ++ Storage->Messages.resize(Ready); ++ Storage->MessageLengths.resize(Ready); ++ if (!Changed) { ++ *Array = HostArray; ++ if (HostArray != GuestArray || Ready < static_cast(*Entries)) { ++ *Entries = Ready; ++ } ++ return 0; ++ } ++ *Array = reinterpret_cast(Copy); ++ *Entries = Received ? Ready : 1; ++ Storage->GuestMessages = GuestArray; ++ Storage->ReceivedMessages = Received; ++ Storage->SendFlags = static_cast(Args[3]); ++ if (!Received && Ready > 1) { ++ Storage->Socket = fcntl(static_cast(Args[0]), F_DUPFD_CLOEXEC, 0); ++ if (Storage->Socket >= 0) { ++ Args[0] = static_cast(Storage->Socket); ++ } ++ } ++ return 0; ++ } ++ ++ bool ReturnMessageFields(uint64_t Guest, const struct msghdr& Message) { ++ return (Message.msg_name == nullptr || ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_namelen), &Message.msg_namelen, sizeof(Message.msg_namelen))) && ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_flags), &Message.msg_flags, sizeof(Message.msg_flags)) && ++ CopyToGuest(Guest + offsetof(struct msghdr, msg_controllen), &Message.msg_controllen, sizeof(Message.msg_controllen)); ++ } ++ ++ uint64_t StringLength(uint64_t Address) { ++ uint64_t Length = 0; ++ while (Length < MaxString) { ++ const auto Here = Address + Length; ++ const auto Chunk = std::min({FEXCore::Utils::FEX_PAGE_SIZE - (Here & (FEXCore::Utils::FEX_PAGE_SIZE - 1)), MaxString - Length, StringChunk}); ++ char Chars[StringChunk]; ++ uint64_t Host {}; ++ if (!TranslateRange(Here, Chunk, &Host) || (Host == Here && Contains(Here)) || ++ FaultSafeUserMemAccess::CopyFromUser(Chars, reinterpret_cast(Host), Chunk) != 0) { ++ return Length + 1; ++ } ++ if (const auto* End = static_cast(memchr(Chars, 0, Chunk)); End != nullptr) { ++ return Length + (End - Chars) + 1; ++ } ++ Length += Chunk; ++ } ++ return MaxString; ++ } ++ ++ bool PointerLength(const Layout& Arguments, uint32_t Pointer, const uint64_t* Args, uint32_t NumArgs, uint64_t* Length) { ++ if (Arguments.Strings & Ptr(Pointer)) { ++ *Length = StringLength(Args[Pointer]); ++ return true; ++ } ++ const auto LengthArg = LengthArgument(Arguments, Pointer); ++ const auto Cap = FixedSize(Arguments, Pointer); ++ if (LengthArg == 0 || LengthArg > NumArgs) { ++ *Length = Cap; ++ return true; ++ } ++ const auto Source = Args[LengthArg - 1]; ++ if (!LengthThroughPointer(Arguments, Pointer)) { ++ return ByteLength(Arguments, Pointer, CountValue(Arguments, Pointer, Source), Length); ++ } ++ *Length = 0; ++ uint32_t Value {}; ++ uint64_t Host {}; ++ if (Source == 0 || !TranslateRange(Source, sizeof(Value), &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Value, reinterpret_cast(Host), sizeof(Value)) != 0) { ++ return true; ++ } ++ *Length = Cap != 0 ? std::min(Value, Cap) : Value; ++ return true; ++ } ++ ++ uint64_t FileControlSize(uint64_t Command) { ++ switch (static_cast(Command)) { ++ case F_GETLK: ++ case F_SETLK: ++ case F_SETLKW: ++ case F_OFD_GETLK: ++ case F_OFD_SETLK: ++ case F_OFD_SETLKW: return FileLockSize; ++ case F_GETOWN_EX: ++ case F_SETOWN_EX: ++ case F_GET_RW_HINT: ++ case F_SET_RW_HINT: ++ case F_GET_FILE_RW_HINT: ++ case F_SET_FILE_RW_HINT: return LongSize; ++ default: return 0; ++ } ++ } ++ ++ struct IoControlBlock { ++ uint64_t Data; ++ uint32_t Key; ++ int32_t ReadWriteFlags; ++ uint16_t Opcode; ++ int16_t Priority; ++ uint32_t File; ++ uint64_t Buffer; ++ uint64_t Bytes; ++ int64_t Offset; ++ uint64_t Reserved; ++ uint32_t Flags; ++ uint32_t ResultFile; ++ }; ++ static_assert(sizeof(IoControlBlock) == IoControlBlockSize); ++ ++ constexpr uint16_t IoRead = 0; ++ constexpr uint16_t IoWrite = 1; ++ constexpr uint16_t IoReadVector = 7; ++ constexpr uint16_t IoWriteVector = 8; ++ ++ uint64_t TranslateIoBuffer(const IoControlBlock& Block, struct iovec* Copy, uint64_t* Out) { ++ *Out = Block.Buffer; ++ switch (Block.Opcode) { ++ case IoRead: ++ case IoWrite: return TranslateRange(Block.Buffer, Block.Bytes, Out) ? 0 : -EFAULT; ++ case IoReadVector: ++ case IoWriteVector: return TranslateIoVector(Block.Buffer, Block.Bytes, Copy, Out); ++ default: return 0; ++ } ++ } ++ ++ struct IoCopy { ++ IoControlBlock Block; ++ uint64_t Context; ++ uint64_t Guest; ++ uint64_t Generation; ++ bool Used; ++ }; ++ static_assert(offsetof(IoCopy, Block) == 0); ++ ++ constexpr size_t MaxIoCopies = 1024; ++ std::mutex IoCopyMutex; ++ std::array IoCopies {}; ++ size_t IoCopyNext {}; ++ std::atomic IoCopyCount {0}; ++ ++ struct AioContextState { ++ uint64_t Generation; ++ uint64_t Active; ++ bool Live; ++ fextl::list> Batches; ++ }; ++ ++ using AioContextTable = fextl::unordered_map; ++ ++ AioContextTable& AioContextsLocked() { ++ static auto* Table = fextl::make_unique().release(); ++ return *Table; ++ } ++ ++ uint64_t AioGeneration {}; ++ ++ uint64_t ContextGenerationLocked(uint64_t Context) { ++ const auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ return Found == Table.end() ? AioGeneration : Found->second.Generation; ++ } ++ ++ IoCopy* FindIoCopyLocked(uint64_t Address) { ++ const auto First = reinterpret_cast(IoCopies.data()); ++ if (Address < First || Address - First >= sizeof(IoCopies) || (Address - First) % sizeof(IoCopy) != 0) { ++ return nullptr; ++ } ++ auto* Copy = &IoCopies[(Address - First) / sizeof(IoCopy)]; ++ return Copy->Used ? Copy : nullptr; ++ } ++ ++ void ReleaseIoCopyLocked(IoCopy* Copy) { ++ Copy->Used = false; ++ IoCopyCount.fetch_sub(1, std::memory_order_release); ++ } ++ ++ uint64_t ClaimIoCopy(const IoControlBlock& Block, uint64_t Context, uint64_t Guest) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (size_t Tried = 0; Tried < MaxIoCopies; ++Tried) { ++ auto& Copy = IoCopies[IoCopyNext]; ++ IoCopyNext = (IoCopyNext + 1) % MaxIoCopies; ++ if (!Copy.Used) { ++ Copy = {Block, Context, Guest, ContextGenerationLocked(Context), true}; ++ IoCopyCount.fetch_add(1, std::memory_order_release); ++ return reinterpret_cast(&Copy); ++ } ++ } ++ return 0; ++ } ++ ++ void ReleaseIoCopies(const uint64_t* Copies, uint64_t Entries) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (uint64_t i = 0; i < Entries; ++i) { ++ if (auto* Copy = Copies[i] ? FindIoCopyLocked(Copies[i]) : nullptr) { ++ ReleaseIoCopyLocked(Copy); ++ } ++ } ++ } ++ ++ uint64_t ContextGeneration(uint64_t Context) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ return ContextGenerationLocked(Context); ++ } ++ ++ void ReleaseContext(uint64_t Context, uint64_t Generation) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (auto& Copy : IoCopies) { ++ if (Copy.Used && Copy.Context == Context && Copy.Generation <= Generation) { ++ ReleaseIoCopyLocked(&Copy); ++ } ++ } ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found != Table.end() && Found->second.Generation <= Generation) { ++ Table.erase(Found); ++ } ++ } ++ ++ uint64_t BeginContext(uint64_t Context) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ Table.erase(Context); ++ Table[Context] = {++AioGeneration, 0, true, {}}; ++ return AioGeneration; ++ } ++ ++ uint64_t ReportedObject(uint64_t Object) { ++ if (IoCopyCount.load(std::memory_order_acquire) != 0) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ if (auto* Copy = FindIoCopyLocked(Object)) { ++ const auto Guest = Copy->Guest; ++ ReleaseIoCopyLocked(Copy); ++ return Guest; ++ } ++ } ++ return ToGuest(Object); ++ } ++ ++ uint64_t CancelTarget(uint64_t Context, uint64_t Guest, uint64_t Host) { ++ uint32_t Key {}; ++ if (IoCopyCount.load(std::memory_order_acquire) == 0 || ++ FaultSafeUserMemAccess::CopyFromUser(&Key, reinterpret_cast(Host + offsetof(IoControlBlock, Key)), sizeof(Key)) != 0 || ++ Key != 0) { ++ return Host; ++ } ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ for (auto& Copy : IoCopies) { ++ if (Copy.Used && Copy.Context == Context && Copy.Guest == Guest) { ++ return reinterpret_cast(&Copy); ++ } ++ } ++ return Host; ++ } ++ ++ constexpr uint64_t MaxIoEvents = 65536; ++ constexpr uint64_t IoEventWords = IoEventSize / sizeof(uint64_t); ++ constexpr uint64_t AioRingMagicOffset = 16; ++ constexpr uint32_t AioRingMagic = 0xa10a10a1; ++ ++ constexpr int64_t NanosPerSecond = 1'000'000'000; ++ constexpr int64_t ReapSlice = 20'000'000; ++ constexpr int64_t MaxWaitSeconds = 1LL << 32; ++ ++ struct StashTicket { ++ uint64_t Taken; ++ uint64_t Generation; ++ }; ++ ++ uint64_t TakeEventsLocked(AioContextState& State, uint64_t* Words, uint64_t Events) { ++ uint64_t Taken = 0; ++ while (Taken < Events && !State.Batches.empty()) { ++ auto& Batch = State.Batches.front(); ++ const auto Count = std::min(Batch.size() / IoEventWords, Events - Taken); ++ std::copy_n(Batch.begin(), Count * IoEventWords, Words + Taken * IoEventWords); ++ Taken += Count; ++ if (Count * IoEventWords == Batch.size()) { ++ State.Batches.pop_front(); ++ } else { ++ Batch.erase(Batch.begin(), Batch.begin() + Count * IoEventWords); ++ } ++ } ++ return Taken; ++ } ++ ++ StashTicket ReserveEvents(uint64_t Context, uint64_t* Words, uint64_t Events, bool Take) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& State = AioContextsLocked()[Context]; ++ if (State.Generation == 0) { ++ State.Generation = ++AioGeneration; ++ } ++ ++State.Active; ++ return {Take ? TakeEventsLocked(State, Words, Events) : 0, State.Generation}; ++ } ++ ++ uint64_t TopUpEvents(uint64_t Context, uint64_t Generation, uint64_t* Words, uint64_t Events) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found == Table.end() || Found->second.Generation != Generation) { ++ return 0; ++ } ++ return TakeEventsLocked(Found->second, Words, Events); ++ } ++ ++ void SettleEvents(uint64_t Context, uint64_t Generation, ArgumentStorage* Storage, uint64_t Kept, bool Forget) { ++ auto lk = FEXCore::MaskSignalsAndLockMutex(IoCopyMutex, ~HeldSignalMask()); ++ auto& Table = AioContextsLocked(); ++ const auto Found = Table.find(Context); ++ if (Found == Table.end() || Found->second.Generation != Generation) { ++ return; ++ } ++ auto& State = Found->second; ++ --State.Active; ++ if (Kept != 0) { ++ auto& Batch = Storage->Recovery.front(); ++ Batch.swap(Storage->EventBuffer); ++ Batch.resize(Kept * IoEventWords); ++ State.Batches.splice(State.Batches.begin(), Storage->Recovery); ++ } ++ if (Forget && !State.Live && State.Active == 0 && State.Batches.empty()) { ++ Table.erase(Found); ++ } ++ } ++ ++ uint64_t WritableEvents(uint64_t Host, uint64_t Events) { ++ Events = std::min(Events, (~0ULL - Host) / IoEventSize); ++ const auto End = Host + Events * IoEventSize; ++ auto Probe = Host; ++ while (Probe < End) { ++ uint8_t Byte {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Byte, reinterpret_cast(Probe), sizeof(Byte)) != 0 || ++ FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Probe), &Byte, sizeof(Byte)) != 0) { ++ break; ++ } ++ Probe = (Probe | (FEXCore::Utils::FEX_PAGE_SIZE - 1)) + 1; ++ } ++ return (std::min(Probe, End) - Host) / IoEventSize; ++ } ++ ++ int64_t MonotonicNanos() { ++ struct timespec Now {}; ++ clock_gettime(CLOCK_MONOTONIC, &Now); ++ return Now.tv_sec * NanosPerSecond + Now.tv_nsec; ++ } ++ ++ void SetWait(ArgumentStorage* Storage, int64_t Left) { ++ const auto Wait = std::clamp(Left, 0, ReapSlice); ++ Storage->Wait[0] = Wait / NanosPerSecond; ++ Storage->Wait[1] = Wait % NanosPerSecond; ++ } ++ ++ bool StartWait(uint64_t Timeout, ArgumentStorage* Storage) { ++ int64_t Given[2] {}; ++ if (Timeout != 0 && (FaultSafeUserMemAccess::CopyFromUser(Given, reinterpret_cast(Timeout), sizeof(Given)) != 0 || ++ Given[0] < 0 || Given[1] < 0 || Given[1] >= NanosPerSecond)) { ++ return false; ++ } ++ const auto Now = MonotonicNanos(); ++ Storage->Deadline = Timeout != 0 && Given[0] < MaxWaitSeconds ? Now + Given[0] * NanosPerSecond + Given[1] : -1; ++ SetWait(Storage, Storage->Deadline < 0 ? ReapSlice : Storage->Deadline - Now); ++ Storage->Blocking = true; ++ return true; ++ } ++ ++ bool ContinueWait(ArgumentStorage* Storage) { ++ if (Storage->Deadline < 0) { ++ SetWait(Storage, ReapSlice); ++ return true; ++ } ++ const auto Left = Storage->Deadline - MonotonicNanos(); ++ SetWait(Storage, Left); ++ return Left > 0; ++ } ++ ++ uint64_t WaitForEvents(ArgumentStorage* Storage, uint64_t* Words, uint64_t Events, uint64_t Reaped) { ++ if (!FEX::HLE::ThreadManager::GetCurrentThreadObject()->SignalInfo.DeferredSignalFrames.empty()) { ++ return -EINTR; ++ } ++ const auto Result = ::syscall(Storage->EventSyscall, Storage->EventContext, Storage->Least - Reaped, Events - Reaped, ++ Words + Reaped * IoEventWords, Storage->Wait, Storage->EventMask); ++ return Result == -1 ? -errno : Result; ++ } ++ ++ uint64_t StartContext(uint64_t ContextPointer, uint64_t Ring) { ++ const auto Generation = BeginContext(Ring); ++ uint32_t Magic {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Magic, reinterpret_cast(Ring + AioRingMagicOffset), sizeof(Magic)) == 0 && ++ Magic == AioRingMagic) { ++ Magic = 0; ++ static_cast(FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Ring + AioRingMagicOffset), &Magic, sizeof(Magic))); ++ } ++ if (CopyToGuest(ContextPointer, &Ring, sizeof(Ring))) { ++ return 0; ++ } ++ static_cast(::syscall(SYS_io_destroy, Ring)); ++ ReleaseContext(Ring, Generation); ++ return -EFAULT; ++ } ++ ++ uint64_t TrackIoCopies(uint64_t Syscall, const uint64_t* Guest, uint64_t* Args, ArgumentStorage* Storage) { ++ switch (Syscall) { ++ case x64::SYSCALL_x64_io_setup: ++ if (FaultSafeUserMemAccess::CopyFromUser(&Storage->SetupId, reinterpret_cast(Args[1]), sizeof(Storage->SetupId)) != 0) { ++ return -EFAULT; ++ } ++ Storage->SetupContext = Guest[1]; ++ Args[1] = reinterpret_cast(&Storage->SetupId); ++ break; ++ case x64::SYSCALL_x64_io_getevents: ++ case x64::SYSCALL_x64_io_pgetevents: { ++ const auto Wanted = static_cast(Args[2]); ++ if (Wanted <= 0 || Guest[3] == 0) { ++ break; ++ } ++ const auto Events = std::max(WritableEvents(Args[3], std::min(Wanted, MaxIoEvents)), 1); ++ if (static_cast(Wanted) > Events) { ++ if (static_cast(Args[1]) > static_cast(Events) && static_cast(Args[1]) <= Wanted) { ++ Args[1] = Events; ++ } ++ Args[2] = Events; ++ } ++ Storage->EventBuffer.resize(Events * IoEventWords); ++ Storage->Recovery.emplace_back(); ++ Storage->Events = Guest[3]; ++ Storage->EventContext = Args[0]; ++ const auto Least = static_cast(Args[1]); ++ const bool Valid = Least >= 0 && Least <= static_cast(Events); ++ const auto Ticket = ReserveEvents(Args[0], Storage->EventBuffer.data(), Events, Valid); ++ Storage->Stashed = Ticket.Taken; ++ Storage->StashGeneration = Ticket.Generation; ++ if (Valid) { ++ Storage->Least = Least; ++ Args[1] = Ticket.Taken >= Storage->Least ? 0 : Storage->Least - Ticket.Taken; ++ if (Args[1] != 0 && StartWait(Args[4], Storage)) { ++ Storage->EventSyscall = Syscall == x64::SYSCALL_x64_io_pgetevents ? SYS_io_pgetevents : SYS_io_getevents; ++ Storage->EventMask = Args[5]; ++ Args[4] = reinterpret_cast(Storage->Wait); ++ } ++ } ++ Args[2] = Events - Ticket.Taken; ++ Args[3] = reinterpret_cast(Storage->EventBuffer.data() + Ticket.Taken * IoEventWords); ++ break; ++ } ++ case x64::SYSCALL_x64_io_cancel: Args[1] = CancelTarget(Args[0], Guest[1], Args[1]); break; ++ case x64::SYSCALL_x64_io_destroy: ++ Storage->DestroyedContext = Args[0]; ++ Storage->DestroyedGeneration = ContextGeneration(Args[0]); ++ Storage->Destroying = true; ++ break; ++ default: break; ++ } ++ return 0; ++ } ++ ++ uint64_t TranslateIoSubmit(uint64_t Context, uint64_t* Entries, uint64_t* Array, ArgumentStorage* Storage) { ++ const auto Requested = static_cast(*Entries); ++ if (Requested <= 0) { ++ return 0; ++ } ++ const auto Blocks = std::min(Requested, MaxIoVectors); ++ Storage->Words.resize(Blocks); ++ auto* List = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(List, reinterpret_cast(*Array), Blocks * PointerSize) != 0) { ++ return 0; ++ } ++ Storage->IoCopies.reserve(Blocks); ++ Storage->IoKeys.reserve(Blocks); ++ Storage->IoKeyValues.reserve(Blocks); ++ bool Refused = false; ++ bool Changed = false; ++ uint64_t Vectors = 0; ++ uint64_t Usable = 0; ++ for (; Usable < Blocks; ++Usable) { ++ IoControlBlock Block {}; ++ uint64_t Host {}; ++ if (!TranslateRange(List[Usable], sizeof(Block), &Host) || ++ FaultSafeUserMemAccess::CopyFromUser(&Block, reinterpret_cast(Host), sizeof(Block)) != 0) { ++ break; ++ } ++ const bool Vectored = (Block.Opcode == IoReadVector || Block.Opcode == IoWriteVector) && Block.Bytes <= MaxIoVectors; ++ if (Vectored) { ++ if (Block.Bytes > MaxIoVectors - Vectors) { ++ break; ++ } ++ Storage->Heap.resize(MaxIoVectors); ++ } ++ uint64_t Buffer {}; ++ if (TranslateIoBuffer(Block, Storage->Heap.data() + Vectors, &Buffer) != 0) { ++ break; ++ } ++ uint64_t Submitted = Host; ++ if (Buffer != Block.Buffer) { ++ if (FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Host + offsetof(IoControlBlock, Key)), &Block.Key, sizeof(Block.Key)) != 0) { ++ Storage->IoCopies.push_back(0); ++ Storage->IoKeys.push_back(0); ++ Storage->IoKeyValues.push_back(Block.Key); ++ Changed = Changed || Host != List[Usable]; ++ List[Usable++] = Host; ++ break; ++ } ++ Block.Buffer = Buffer; ++ Submitted = ClaimIoCopy(Block, Context, List[Usable]); ++ if (Submitted == 0) { ++ Refused = true; ++ break; ++ } ++ } ++ if (Vectored) { ++ Vectors += Block.Bytes; ++ } ++ Storage->IoCopies.push_back(Submitted != Host ? Submitted : 0); ++ Storage->IoKeys.push_back(Submitted != Host ? List[Usable] + offsetof(IoControlBlock, Key) : 0); ++ Storage->IoKeyValues.push_back(Block.Key); ++ Changed = Changed || Submitted != List[Usable]; ++ List[Usable] = Submitted; ++ } ++ if (Usable == 0) { ++ return Refused ? -EAGAIN : -EFAULT; ++ } ++ if (Changed) { ++ *Array = reinterpret_cast(List); ++ } ++ *Entries = Usable; ++ return 0; ++ } ++ ++ uint64_t TranslatePageList(uint64_t* Args, ArgumentStorage* Storage) { ++ const auto Process = static_cast(Args[0]); ++ const auto Pages = Args[1]; ++ if ((Process != 0 && Process != getpid()) || Pages == 0 || Pages > MaxPageList) { ++ return 0; ++ } ++ Storage->Words.resize(Pages); ++ auto* List = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(List, reinterpret_cast(Args[2]), Pages * PointerSize) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Pages; ++i) { ++ uint64_t Host {}; ++ if (!TranslateRange(List[i], 1, &Host)) { ++ return -EFAULT; ++ } ++ Changed = Changed || Host != List[i]; ++ List[i] = Host; ++ } ++ if (Changed) { ++ Args[2] = reinterpret_cast(List); ++ } ++ return 0; ++ } ++ ++ struct EmbeddedSize { ++ uint64_t Offset; ++ uint64_t Header; ++ uint64_t Default; ++ uint64_t Minimum; ++ uint64_t Maximum; ++ }; ++ ++ constexpr EmbeddedSize PerfAttributeSize {4, 0, 64, 64, FEXCore::Utils::FEX_PAGE_SIZE}; ++ constexpr EmbeddedSize SchedulerAttributeSize {0, 0, 48, 48, FEXCore::Utils::FEX_PAGE_SIZE}; ++ constexpr EmbeddedSize FileHandleSize {0, 8, 0, 0, 128}; ++ constexpr EmbeddedSize MountRequestSize {0, 0, 0, 24, FEXCore::Utils::FEX_PAGE_SIZE}; ++ ++ uint64_t TranslateEmbedded(uint64_t* Argument, const EmbeddedSize& Rule) { ++ if (!Contains(*Argument)) { ++ return 0; ++ } ++ const uint64_t Field = Rule.Offset + sizeof(uint32_t); ++ uint64_t Host {}; ++ if (!TranslateRange(*Argument, Field, &Host)) { ++ return -EFAULT; ++ } ++ uint64_t Span = std::max(Field, Rule.Header); ++ uint32_t Raw {}; ++ if (FaultSafeUserMemAccess::CopyFromUser(&Raw, reinterpret_cast(Host + Rule.Offset), sizeof(Raw)) == 0) { ++ const uint64_t Value = Raw == 0 ? Rule.Default : Raw; ++ if (Value >= Rule.Minimum && Value <= Rule.Maximum) { ++ Span = std::max(Field, Rule.Header + Value); ++ } ++ } ++ return TranslateRange(*Argument, Span, Argument) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateCapabilities(uint64_t* Header, uint64_t GuestHeader, uint64_t* Data, ArgumentStorage* Storage) { ++ if (!Contains(*Data)) { ++ return 0; ++ } ++ uint64_t Bytes = 0; ++ auto* Copy = Storage->CapabilityHeader; ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(*Header), sizeof(Storage->CapabilityHeader)) == 0) { ++ const auto Version = Copy[0]; ++ Bytes = Version == CapVersion1 ? CapDataSize : (Version == CapVersion2 || Version == CapVersion3) ? 2 * CapDataSize : 0; ++ Storage->CapabilityVersion = Version; ++ Storage->GuestCapabilityHeader = GuestHeader; ++ *Header = reinterpret_cast(Copy); ++ } ++ return TranslateRange(*Data, Bytes, Data) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateLandlockRule(uint64_t Type, uint64_t* Rule) { ++ const uint64_t Bytes = Type == 1 ? LandlockPathRuleSize : Type == 2 ? LandlockPortRuleSize : 0; ++ return TranslateRange(*Rule, Bytes, Rule) ? 0 : -EFAULT; ++ } ++ ++ uint64_t TranslateWaiters(uint64_t* Waiters, uint64_t Entries, ArgumentStorage* Storage) { ++ constexpr uint64_t Words = FutexWaitSize / sizeof(uint64_t); ++ if (Entries == 0 || Entries > MaxFutexWaiters) { ++ return 0; ++ } ++ Storage->Words.resize(Entries * Words); ++ auto* Copy = Storage->Words.data(); ++ if (FaultSafeUserMemAccess::CopyFromUser(Copy, reinterpret_cast(*Waiters), Entries * FutexWaitSize) != 0) { ++ return 0; ++ } ++ bool Changed = false; ++ for (uint64_t i = 0; i < Entries; ++i) { ++ auto& Address = Copy[i * Words + 1]; ++ uint64_t Host {}; ++ if (!TranslateRange(Address, 1ULL << (Copy[i * Words + 2] & 3), &Host)) { ++ return -EFAULT; ++ } ++ Changed = Changed || Host != Address; ++ Address = Host; ++ } ++ if (Changed) { ++ *Waiters = reinterpret_cast(Copy); ++ } ++ return 0; ++ } ++} // namespace ++ ++bool Contains(uint64_t Address) { ++ return Address >= HostLimit() && Address < TaskTop; ++} ++ ++bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags) { ++ if (!(Flags & MAP_FIXED) || (Flags & MAP_FIXED_NOREPLACE) || Length == 0) { ++ return false; ++ } ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return false; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ return Contains(Address) && Size <= TaskTop - Address; ++} ++ ++uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset) { ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ const int HostFlags = Flags & ~MAP_FIXED; ++ void* Host = MAP_FAILED; ++ if (const auto Hint = NeighbourHint(Address, Size); Hint != 0) { ++ Host = ::mmap(reinterpret_cast(Hint), Size, Prot, HostFlags | MAP_FIXED_NOREPLACE, FD, Offset); ++ } ++ if (Host == MAP_FAILED) { ++ Host = ::mmap(nullptr, Size, Prot, HostFlags, FD, Offset); ++ } ++ if (Host == MAP_FAILED) { ++ return -errno; ++ } ++ ++ BeginWrite(); ++ int Result = 0; ++ if (!HasRoomLocked(Address, Size, 1)) { ++ Result = -ENOMEM; ++ } else { ++ Result = UnmapLocked(Address, Size); ++ } ++ if (Result == 0 && !AddEntry(Address, Size, reinterpret_cast(Host), false, TrackedProt(Prot))) { ++ Result = -ENOMEM; ++ } ++ if (Result == 0) { ++ CoalesceLocked(Address, Address + Size); ++ } ++ EndWrite(); ++ if (Result != 0) { ++ ::munmap(Host, Size); ++ return Result; ++ } ++ return Address; ++} ++ ++uint64_t Unmap(uint64_t Address, uint64_t Length) { ++ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) { ++ return -EINVAL; ++ } ++ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE); ++ if (Size == 0 || Size > TaskTop - Address) { ++ return -EINVAL; ++ } ++ BeginWrite(); ++ const int Result = UnmapLocked(Address, Size); ++ EndWrite(); ++ return Result; ++} ++ ++uint64_t Protect(uint64_t Address, uint64_t Length, int Prot) { ++ BeginWrite(); ++ uint64_t Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [](void*, uint64_t, uint32_t) { return 0; }); ++ if (Result == 0) { ++ Result = SplitLocked(Address, Length); ++ } ++ if (Result == 0) { ++ Result = ApplyToRegionsLocked(Address, Length, -ENOMEM, [Prot](void* Host, uint64_t Size, uint32_t i) { ++ const int Applied = ::mprotect(Host, Size, Prot); ++ if (Applied == 0) { ++ Regions[i].Prot.store(TrackedProt(Prot), std::memory_order_relaxed); ++ } ++ return Applied; ++ }); ++ CoalesceLocked(Address, Address + std::min(FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE), TaskTop - Address)); ++ } ++ EndWrite(); ++ return Result; ++} ++ ++uint64_t Advise(uint64_t Address, uint64_t Length, int Advice, bool* Applied) { ++ *Applied = false; ++ return ApplyToRegionsLocked(Address, Length, -EINVAL, [Advice, Applied](void* Host, uint64_t Size, uint32_t) { ++ const int Result = ::madvise(Host, Size, Advice); ++ if (Result == 0) { ++ *Applied = true; ++ } ++ return Result; ++ }); ++} ++ ++bool DiscardsContents(int Advice) { ++ switch (Advice) { ++ case MADV_DONTNEED: ++ case MADV_FREE: ++ case MADV_REMOVE: ++ case MADV_DONTNEED_LOCKED: return true; ++ default: return false; ++ } ++} ++ ++uint64_t ToGuest(uint64_t Address) { ++ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] { ++ return Address; ++ } ++ return ReadConsistent([&] { ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Host = Regions[i].Host.load(std::memory_order_relaxed); ++ const auto Size = Regions[i].Size.load(std::memory_order_relaxed); ++ if (Address >= Host && Address - Host < Size) { ++ return Regions[i].Guest.load(std::memory_order_relaxed) + (Address - Host); ++ } ++ } ++ return Address; ++ }); ++} ++ ++bool TranslateRange(uint64_t Address, uint64_t Length, uint64_t* Host) { ++ if (Count.load(std::memory_order_relaxed) == 0 || !Contains(Address)) [[likely]] { ++ *Host = Address; ++ return true; ++ } ++ return ReadConsistent([&] { return SpanLocked(Address, Length, Host); }); ++} ++ ++void MarkCode(uint64_t Address, uint64_t Length) { ++ const auto End = Address + Length; ++ const auto Entries = Count.load(std::memory_order_acquire); ++ for (uint32_t i = 0; i < Entries; ++i) { ++ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed); ++ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed); ++ if (RegionEnd > Address && Guest < End) { ++ Regions[i].Code.store(true, std::memory_order_relaxed); ++ } ++ } ++} ++ ++uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t NumArgs, ArgumentStorage* Storage) { ++ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] { ++ return TrackIoCopies(Syscall, Args, Args, Storage); ++ } ++ if (Syscall >= Layouts.size()) { ++ return 0; ++ } ++ const auto& Arguments = Layouts[Syscall]; ++ const auto Used = std::min(NumArgs, 6); ++ uint64_t Guest[6] {}; ++ std::copy_n(Args, Used, Guest); ++ uint64_t Lengths[6] {}; ++ for (uint32_t i = 0; i < Used; ++i) { ++ if ((Arguments.Pointers & Ptr(i)) && Contains(Args[i]) && !PointerLength(Arguments, i, Args, Used, &Lengths[i])) { ++ return -EFAULT; ++ } ++ } ++ for (uint32_t i = 0; i < Used; ++i) { ++ if ((Arguments.Pointers & Ptr(i)) && !TranslateRange(Args[i], Lengths[i], &Args[i])) { ++ return -EFAULT; ++ } ++ } ++ if (const auto Failed = TrackIoCopies(Syscall, Guest, Args, Storage); Failed != 0) { ++ return Failed; ++ } ++ if (Used < 6) { ++ return 0; ++ } ++ switch (Arguments.Vector) { ++ case VectorKind::Io: return TranslateIoVector(Args[1], Args[2], VectorCopy(Storage, Args[2]), &Args[1]); ++ case VectorKind::SentMessage: return TranslateMessage(&Args[1], false, Storage); ++ case VectorKind::ReceivedMessage: return TranslateMessage(&Args[1], true, Storage); ++ case VectorKind::SentMessageArray: return TranslateMessages(Args, false, Storage); ++ case VectorKind::ReceivedMessageArray: return TranslateMessages(Args, true, Storage); ++ case VectorKind::IoSubmit: return TranslateIoSubmit(Args[0], &Args[1], &Args[2], Storage); ++ case VectorKind::IoEvents: return 0; ++ case VectorKind::PageList: return TranslatePageList(Args, Storage); ++ case VectorKind::FutexWaiters: return TranslateWaiters(&Args[0], static_cast(Args[1]), Storage); ++ case VectorKind::FutexRequeue: return TranslateWaiters(&Args[0], 2, Storage); ++ case VectorKind::FileControl: return TranslateRange(Args[2], FileControlSize(Args[1]), &Args[2]) ? 0 : -EFAULT; ++ case VectorKind::Capabilities: return TranslateCapabilities(&Args[0], Guest[0], &Args[1], Storage); ++ case VectorKind::PerfAttribute: return TranslateEmbedded(&Args[0], PerfAttributeSize); ++ case VectorKind::SchedulerAttribute: return TranslateEmbedded(&Args[1], SchedulerAttributeSize); ++ case VectorKind::HandleAt: return TranslateEmbedded(&Args[2], FileHandleSize); ++ case VectorKind::OpenHandle: return TranslateEmbedded(&Args[1], FileHandleSize); ++ case VectorKind::MountRequest: return TranslateEmbedded(&Args[0], MountRequestSize); ++ case VectorKind::LandlockRule: return TranslateLandlockRule(static_cast(Args[1]), &Args[2]); ++ case VectorKind::None: break; ++ } ++ return 0; ++} ++ ++bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread) { ++ return FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->HighMemoryTrap.Mappings.Held; ++} ++ ++uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage) { ++ struct PinnedSocket { ++ int FD; ++ ~PinnedSocket() { ++ if (FD >= 0) { ++ close(FD); ++ } ++ } ++ } Socket {std::exchange(Storage->Socket, -1)}; ++ if (!Storage->IoCopies.empty()) { ++ const auto Submitted = FEX::HLE::HasSyscallError(Result) ? 0 : std::min(Result, Storage->IoCopies.size()); ++ const auto Examined = std::min(Submitted + 1, Storage->IoCopies.size()); ++ for (uint64_t i = 0; i < Examined; ++i) { ++ if (Storage->IoKeys[i] == 0) { ++ continue; ++ } ++ const uint32_t Key = i < Submitted ? 0 : reinterpret_cast(Storage->IoCopies[i])->Key; ++ if (Key != Storage->IoKeyValues[i]) { ++ static_cast(CopyToGuest(Storage->IoKeys[i], &Key, sizeof(Key))); ++ } ++ } ++ ReleaseIoCopies(Storage->IoCopies.data() + Submitted, Storage->IoCopies.size() - Submitted); ++ } ++ if (Storage->SetupContext != 0 && Result == 0) { ++ Result = StartContext(Storage->SetupContext, Storage->SetupId); ++ } ++ if (Storage->Destroying && Result == 0) { ++ ReleaseContext(Storage->DestroyedContext, Storage->DestroyedGeneration); ++ } ++ if (Storage->GuestCapabilityHeader != 0 && Storage->CapabilityHeader[0] != Storage->CapabilityVersion && ++ !CopyToGuest(Storage->GuestCapabilityHeader, &Storage->CapabilityHeader[0], sizeof(Storage->CapabilityHeader[0]))) { ++ return -EFAULT; ++ } ++ if (Storage->Events != 0) { ++ const auto Taken = Storage->Stashed; ++ auto* Words = Storage->EventBuffer.data(); ++ if (FEX::HLE::HasSyscallError(Result) && (Result != static_cast(-EINTR) || Taken == 0)) { ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, Taken, Result == static_cast(-EINVAL)); ++ return Result; ++ } ++ const auto Events = Storage->EventBuffer.size() / IoEventWords; ++ auto Reaped = Taken; ++ while (!FEX::HLE::HasSyscallError(Result)) { ++ const auto Fresh = std::min(Result, Events - Reaped); ++ for (uint64_t i = Reaped; i < Reaped + Fresh; ++i) { ++ auto& Object = Words[i * IoEventWords + IoEventObjectOffset / sizeof(uint64_t)]; ++ Object = ReportedObject(Object); ++ } ++ Reaped += Fresh; ++ if (!Storage->Blocking || Reaped >= Storage->Least) { ++ break; ++ } ++ Reaped += TopUpEvents(Storage->EventContext, Storage->StashGeneration, Words + Reaped * IoEventWords, Events - Reaped); ++ if (Reaped >= Storage->Least || !ContinueWait(Storage)) { ++ break; ++ } ++ Result = WaitForEvents(Storage, Words, Events, Reaped); ++ if (FEX::HLE::HasSyscallError(Result) && Reaped == 0) { ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, 0, Result == static_cast(-EINVAL)); ++ return Result; ++ } ++ } ++ const bool Delivered = Reaped == 0 || CopyToGuest(Storage->Events, Words, Reaped * IoEventSize); ++ SettleEvents(Storage->EventContext, Storage->StashGeneration, Storage, Delivered ? 0 : Reaped, false); ++ if (!Delivered) { ++ return -EFAULT; ++ } ++ Result = Reaped; ++ } ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ if (Storage->GuestMessages != 0) { ++ const bool FollowUps = !Storage->ReceivedMessages && Socket.FD >= 0; ++ const auto Total = FollowUps ? Storage->Messages.size() : std::min(Result, Storage->Messages.size()); ++ uint64_t Done = 0; ++ for (; Done < Total; ++Done) { ++ auto& Message = Storage->Messages[Done]; ++ if (Done >= Result && ::sendmmsg(Socket.FD, &Message, 1, Storage->SendFlags) != 1) { ++ break; ++ } ++ const auto Guest = Storage->GuestMessages + Done * sizeof(struct mmsghdr); ++ if ((Storage->ReceivedMessages && !ReturnMessageFields(Guest + offsetof(struct mmsghdr, msg_hdr), Message.msg_hdr)) || ++ !CopyToGuest(Guest + offsetof(struct mmsghdr, msg_len), &Message.msg_len, sizeof(Message.msg_len))) { ++ return Done == 0 ? -EFAULT : Done; ++ } ++ if (FollowUps && Message.msg_len < Storage->MessageLengths[Done]) { ++ return Done + 1; ++ } ++ } ++ return Done; ++ } ++ if (Storage->ReceivedHeader != 0 && !ReturnMessageFields(Storage->ReceivedHeader, Storage->Message)) { ++ return -EFAULT; ++ } ++ return Result; ++} ++ ++bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto* SigInfo = static_cast(Info); ++ const auto FaultAddress = reinterpret_cast(SigInfo->si_addr); ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ auto& Trap = ThreadObject->HighMemoryTrap; ++ const auto PC = ArchHelpers::Context::GetPc(UContext); ++ ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (Trap.Active && PC == reinterpret_cast(Trap.Code)) { ++ RedeliverFromTrap(Trap, SigInfo, UContext); ++ return false; ++ } ++ ++ if (SigInfo->si_code <= SI_USER || !Contains(FaultAddress) || Trap.Active || Trap.Mappings.Held) { ++ return false; ++ } ++ ++ const auto Insn = *reinterpret_cast(PC); ++ if (!IsLoadStore(Insn) || IsLiteralLoad(Insn) || RnField(Insn) == 31) { ++ return false; ++ } ++ ++ uint64_t Address {}; ++ uint32_t Size {}; ++ bool Plain {}; ++ if (!DecodeAccess(Insn, UContext, &Address, &Size, &Plain)) { ++ return false; ++ } ++ ++ MappingHold Hold {Trap.Mappings}; ++ AccessPiece Pieces[MaxAccessPieces] {}; ++ const auto Parts = ReadConsistent([&] { return PlanAccessLocked(Address, Size, Pieces); }); ++ if (Parts == 0) { ++ return false; ++ } ++ ++ const bool Write = IsWrite(Insn); ++ if (Write && std::any_of(Pieces, Pieces + Parts, [](const AccessPiece& Piece) { return Piece.Code; })) { ++ auto& VMATracking = FEX::HLE::_SyscallHandler->VMATracking; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ if (!Pieces[i].Code) { ++ continue; ++ } ++ const auto Last = Pieces[i].Guest + Pieces[i].Size - 1; ++ for (auto FaultBase = FEXCore::AlignDown(Pieces[i].Guest, FEXCore::Utils::FEX_PAGE_SIZE); FaultBase <= Last; ++ FaultBase += FEXCore::Utils::FEX_PAGE_SIZE) { ++ const auto Entry = VMATracking.FindVMAEntry(FaultBase); ++ if (Entry != VMATracking.VMAs.end()) { ++ FEX::HLE::SyscallHandler::InvalidateWrittenCodePage(Thread, FaultBase, Entry->first, Entry->second); ++ } else { ++ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE); ++ } ++ } ++ } ++ ++ constexpr uint64_t MaxStoreSize = 64; ++ const uint64_t StoreWindowStart = FaultAddress - MaxStoreSize; ++ auto CTX = Thread->CTX; ++ if (CTX->IsAddressInCodeBuffer(Thread, PC) && !CTX->IsCurrentBlockSingleInst(Thread) && ++ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) { ++ ThreadObject->SignalInfo.Delegator->SpillSRA(Thread, UContext, Thread->CurrentFrame->InSyscallInfo & 0xFFFF); ++ const auto& Config = ThreadObject->SignalInfo.Delegator->GetConfig(); ++ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA); ++ ArchHelpers::Context::SetArmReg(UContext, 1, 1); ++ return true; ++ } ++ } ++ ++ if (IsExclusive(Insn)) { ++ if (Parts != 1 || !ExclusiveReachable(Insn, Pieces[0].Prot) || ++ !EmulateExclusive(Trap.Monitor, Insn, Pieces[0].Host, UContext)) { ++ return false; ++ } ++ ArchHelpers::Context::SetPc(UContext, PC + 4); ++ return true; ++ } ++ ++ const bool Bounced = !HostContiguous(Pieces, Parts); ++ if (Bounced && (!PiecesReachable(Pieces, Parts, Write) || (!Plain && !IsOrderedAccess(Insn)))) { ++ return false; ++ } ++ ++ const int Scratch = PickScratch(Insn); ++ if (Scratch < 0 || !EnsureTrapCode(Trap)) { ++ return false; ++ } ++ ++ Trap.Scratch = Scratch; ++ Trap.Base = RnField(Insn); ++ Trap.SavedScratch = ArchHelpers::Context::GetArmReg(UContext, Scratch); ++ Trap.BaseBefore = ArchHelpers::Context::GetArmReg(UContext, Trap.Base); ++ Trap.ResumePC = PC + 4; ++ Trap.Parts = 0; ++ Trap.Delta = Pieces[0].Host - Address; ++ ++ uint32_t Failed = Parts; ++ if (Bounced && !Plain) { ++ Failed = EmulateOrdered(Insn, Pieces, Parts, UContext); ++ if (Failed == Parts) { ++ ArchHelpers::Context::SetPc(UContext, PC + 4); ++ return true; ++ } ++ } else if (Bounced) { ++ Trap.BounceOffset = Address & 15; ++ Trap.Store = Write; ++ Trap.Parts = Parts; ++ for (uint32_t i = 0; i < Parts; ++i) { ++ Trap.Pieces[i].Guest = Pieces[i].Guest; ++ Trap.Pieces[i].Host = Pieces[i].Host; ++ Trap.Pieces[i].Size = Pieces[i].Size; ++ } ++ auto* Window = Trap.Bounce + Trap.BounceOffset; ++ Failed = CopyPieces(Window, Trap.Pieces, Parts, true); ++ Trap.Delta = reinterpret_cast(Window) - Address; ++ } ++ ++ auto* Mask = &ArchHelpers::Context::GetUContext(UContext)->uc_sigmask; ++ memcpy(&Trap.SavedMask, Mask, sizeof(Trap.SavedMask)); ++ const uint64_t Blocked = ~HeldSignalMask(); ++ memcpy(Mask, &Blocked, sizeof(Blocked)); ++ if (Failed != Parts) { ++ ArmProbe(Trap, UContext, Pieces[Failed].Guest, Pieces[Failed].Host); ++ } else { ++ ArmTrap(Trap, UContext, (Insn & ~(0x1fU << 5)) | (static_cast(Scratch) << 5), Trap.BaseBefore + Trap.Delta, false); ++ } ++ Hold.Keep(); ++ return true; ++} ++ ++bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto* SigInfo = static_cast(Info); ++ auto& Trap = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->HighMemoryTrap; ++ const auto PC = ArchHelpers::Context::GetPc(UContext); ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (Trap.Active && PC == reinterpret_cast(Trap.Code)) { ++ RedeliverFromTrap(Trap, SigInfo, UContext); ++ return false; ++ } ++ if (SigInfo->si_code <= SI_USER || !FaultSafeUserMemAccess::IsFaultLocation(PC)) { ++ return false; ++ } ++ ArchHelpers::Context::SetArmReg(UContext, 0, EFAULT); ++ ArchHelpers::Context::SetPc(UContext, ArchHelpers::Context::GetArmReg(UContext, 30)); ++ return true; ++} ++ ++bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread); ++ auto& Trap = ThreadObject->HighMemoryTrap; ++ auto* SigInfo = static_cast(Info); ++ if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) { ++ return true; ++ } ++ if (!Trap.Active || SigInfo->si_code != TRAP_BRKPT || ArchHelpers::Context::GetPc(UContext) != reinterpret_cast(Trap.Code) + 4) { ++ return false; ++ } ++ ++ if (Trap.Probe) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ LeaveTrap(Trap, UContext, Trap.ResumePC - 4); ++ return true; ++ } ++ ++ const auto ScratchAfter = ArchHelpers::Context::GetArmReg(UContext, Trap.Scratch); ++ if (ScratchAfter != Trap.BaseBefore + Trap.Delta) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, ScratchAfter - Trap.Delta); ++ } ++ if (Trap.Parts != 0 && Trap.Store) { ++ const auto Failed = CopyPieces(Trap.Bounce + Trap.BounceOffset, Trap.Pieces, Trap.Parts, false); ++ if (Failed != Trap.Parts) { ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore); ++ ArmProbe(Trap, UContext, Trap.Pieces[Failed].Guest, Trap.Pieces[Failed].Host); ++ return true; ++ } ++ } ++ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch); ++ LeaveTrap(Trap, UContext, Trap.ResumePC); ++ return true; ++} ++ ++void ReleaseThread(FEX::HLE::ThreadStateObject* Thread) { ++ if (Thread->HighMemoryTrap.Code) { ++ FEXCore::Allocator::munmap(Thread->HighMemoryTrap.Code, FEXCore::Utils::FEX_PAGE_SIZE); ++ Thread->HighMemoryTrap.Code = nullptr; ++ } ++} ++} // namespace FEX::HLE::GuestHighMemory +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h +new file mode 100644 +index 0000000..661b200 +--- /dev/null ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h +@@ -0,0 +1,74 @@ ++#pragma once ++ ++#include ++#include ++ ++#include ++#include ++#include ++#include ++ ++namespace FEXCore::Core { ++struct InternalThreadState; ++} ++ ++namespace FEX::HLE { ++struct ThreadStateObject; ++} ++ ++namespace FEX::HLE::GuestHighMemory { ++struct ArgumentStorage { ++ struct iovec Inline[8]; ++ fextl::vector Heap; ++ struct msghdr Message; ++ uint64_t ReceivedHeader {}; ++ fextl::vector Messages; ++ fextl::vector MessageLengths; ++ uint64_t GuestMessages {}; ++ bool ReceivedMessages {}; ++ int Socket {-1}; ++ int SendFlags {}; ++ uint32_t CapabilityHeader[2] {}; ++ uint32_t CapabilityVersion {}; ++ uint64_t GuestCapabilityHeader {}; ++ fextl::vector Words; ++ fextl::vector IoCopies; ++ fextl::vector IoKeys; ++ fextl::vector IoKeyValues; ++ fextl::vector EventBuffer; ++ fextl::list> Recovery; ++ uint64_t Events {}; ++ uint64_t EventContext {}; ++ uint64_t Stashed {}; ++ uint64_t StashGeneration {}; ++ uint64_t Least {}; ++ int64_t Deadline {}; ++ int64_t Wait[2] {}; ++ long EventSyscall {}; ++ uint64_t EventMask {}; ++ bool Blocking {}; ++ uint64_t SetupContext {}; ++ uint64_t SetupId {}; ++ uint64_t DestroyedContext {}; ++ uint64_t DestroyedGeneration {}; ++ bool Destroying {}; ++}; ++ ++bool Contains(uint64_t Address); ++bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags); ++uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset); ++uint64_t Unmap(uint64_t Address, uint64_t Length); ++uint64_t Protect(uint64_t Address, uint64_t Length, int Prot); ++uint64_t Advise(uint64_t Address, uint64_t Length, int Advice, bool* Applied); ++bool DiscardsContents(int Advice); ++uint64_t ToGuest(uint64_t Address); ++bool TranslateRange(uint64_t Address, uint64_t Length, uint64_t* Host); ++void MarkCode(uint64_t Address, uint64_t Length); ++uint64_t TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t Count, ArgumentStorage* Storage); ++uint64_t FinishSyscallArguments(uint64_t Result, ArgumentStorage* Storage); ++bool HoldsMappings(FEXCore::Core::InternalThreadState* Thread); ++bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++bool HandleBusFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext); ++void ReleaseThread(FEX::HLE::ThreadStateObject* Thread); ++} // namespace FEX::HLE::GuestHighMemory +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index 87b890e..ababed9 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -7,6 +7,7 @@ $end_info$ + */ + + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/PtraceEmu.h" + #include "LinuxSyscalls/SignalTrace.h" +@@ -765,6 +766,10 @@ uint64_t SignalDelegator::GetNewSigMask(int Signal) const { + } + + bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) { ++ if (FEX::HLE::GuestHighMemory::HandleFault(Thread, Signal, Info, UContext)) { ++ return true; ++ } ++ + auto SigInfo = *static_cast(Info); + + if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +index 607ab0b..5e684c4 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp +@@ -16,6 +16,7 @@ $end_info$ + #include "LinuxSyscalls/LinuxAllocator.h" + #include "LinuxSyscalls/SignalDelegator.h" + #include "LinuxSyscalls/PtraceEmu.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/Syscalls/Thread.h" +@@ -820,6 +821,8 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal + + SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true); + ++ SignalDelegation->RegisterHostSignalHandler(SIGTRAP, FEX::HLE::GuestHighMemory::HandleTrap, true); ++ SignalDelegation->RegisterHostSignalHandler(SIGBUS, FEX::HLE::GuestHighMemory::HandleBusFault, true); + SignalDelegation->RegisterHostSignalHandler( + SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true); + +@@ -894,30 +897,34 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint + } + + auto& Def = Definitions[SyscallNum]; ++ uint64_t A[7] {}; ++ for (unsigned i = 1; i < 7; ++i) { ++ A[i] = GetArg(Is64Bit, Frame, i); ++ } ++ FEX::HLE::GuestHighMemory::ArgumentStorage HighMemoryArguments; + uint64_t Result {}; +- switch (Def.NumArgs) { +- case 0: Result = std::invoke(Def.Ptr0, Frame); break; +- case 1: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 1)); break; +- case 2: Result = std::invoke(Def.Ptr2, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2)); break; +- case 3: Result = std::invoke(Def.Ptr3, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3)); break; +- case 4: +- Result = +- std::invoke(Def.Ptr4, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), GetArg(Is64Bit, Frame, 4)); +- break; +- case 5: +- Result = std::invoke(Def.Ptr5, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), +- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5)); +- break; +- case 6: +- Result = std::invoke(Def.Ptr6, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), +- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5), GetArg(Is64Bit, Frame, 6)); +- break; +- // for missing syscalls +- case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break; +- default: +- LOGMAN_MSG_A_FMT("Unhandled syscall: {}", GetArg(Is64Bit, Frame, 0)); +- Result = -ENOSYS; +- break; ++ if constexpr (Is64Bit) { ++ Result = FEX::HLE::GuestHighMemory::TranslateSyscallArguments(SyscallNum, &A[1], 6, &HighMemoryArguments); ++ } ++ if (!FEX::HLE::HasSyscallError(Result)) { ++ switch (Def.NumArgs) { ++ case 0: Result = std::invoke(Def.Ptr0, Frame); break; ++ case 1: Result = std::invoke(Def.Ptr1, Frame, A[1]); break; ++ case 2: Result = std::invoke(Def.Ptr2, Frame, A[1], A[2]); break; ++ case 3: Result = std::invoke(Def.Ptr3, Frame, A[1], A[2], A[3]); break; ++ case 4: Result = std::invoke(Def.Ptr4, Frame, A[1], A[2], A[3], A[4]); break; ++ case 5: Result = std::invoke(Def.Ptr5, Frame, A[1], A[2], A[3], A[4], A[5]); break; ++ case 6: Result = std::invoke(Def.Ptr6, Frame, A[1], A[2], A[3], A[4], A[5], A[6]); break; ++ // for missing syscalls ++ case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break; ++ default: ++ LOGMAN_MSG_A_FMT("Unhandled syscall: {}", GetArg(Is64Bit, Frame, 0)); ++ Result = -ENOSYS; ++ break; ++ } ++ } ++ if constexpr (Is64Bit) { ++ Result = FEX::HLE::GuestHighMemory::FinishSyscallArguments(Result, &HighMemoryArguments); + } + #ifdef DEBUG_STRACE + Strace(Frame, Result); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp +index 9397c9e..6095bf3 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Memory.cpp +@@ -5,12 +5,19 @@ tags: LinuxSyscalls|syscalls-shared + $end_info$ + */ + ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/x64/Syscalls.h" + #include "LinuxSyscalls/x32/Syscalls.h" + + #include ++#include ++#include ++#include ++#include + ++#include ++#include + #include + #include + #include +@@ -25,6 +32,29 @@ void RegisterMemory(FEX::HLE::SyscallHandler* Handler) { + }); + + REGISTER_SYSCALL_IMPL(madvise, [](FEXCore::Core::CpuStateFrame* Frame, void* addr, size_t length, int32_t advice) -> uint64_t { ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(addr))) { ++ uint64_t Result {}; ++ bool Applied {}; ++ { ++ auto lk = FEXCore::GuardSignalDeferringSection(FEX::HLE::_SyscallHandler->VMATracking.Mutex, Frame->Thread); ++ Result = FEX::HLE::GuestHighMemory::Advise(reinterpret_cast(addr), length, advice, &Applied); ++ } ++ if (Applied && FEX::HLE::GuestHighMemory::DiscardsContents(advice)) { ++ const auto Base = reinterpret_cast(addr); ++ const auto Size = std::min(FEXCore::AlignUp(length, FEXCore::Utils::FEX_PAGE_SIZE), UINT64_MAX - Base); ++ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Frame->Thread, Base, Size, [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } ++ auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); ++ LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); ++ }); ++ } ++ if (!FEX::HLE::HasSyscallError(Result)) { ++ FEX::HLE::_SyscallHandler->TrackMadvise(Frame->Thread, (uintptr_t)addr, length, advice); ++ } ++ return Result; ++ } + uint64_t Result = ::madvise(addr, length, advice); + + if (Result != -1) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +index f9e85a2..2dff836 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp +@@ -21,6 +21,7 @@ $end_info$ + + #include "LinuxSyscalls/Syscalls.h" + #include "LinuxSyscalls/SignalDelegator.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + + #include + #include +@@ -45,6 +46,9 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread + void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase, + const FEX::HLE::VMATracking::VMAEntry& Mapping) { + auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } + auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); + }; +@@ -93,6 +97,10 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread, + } + } + ++ if (FEX::HLE::GuestHighMemory::Contains(FaultAddress) || FEX::HLE::GuestHighMemory::HoldsMappings(Thread)) { ++ return false; ++ } ++ + { + // Can't use the deferred signal lock in the SIGSEGV handler. + auto lk = FEXCore::MaskSignalsAndLockMutex(_SyscallHandler->VMATracking.Mutex); +@@ -150,6 +158,7 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr + return; + } + ++ Buf = reinterpret_cast(FEX::HLE::GuestHighMemory::ToGuest(reinterpret_cast(Buf))); + const uint64_t Start = FEXCore::AlignDown(reinterpret_cast(Buf), FEXCore::Utils::FEX_PAGE_SIZE); + const uint64_t Last = reinterpret_cast(Buf) + Length - 1 < reinterpret_cast(Buf) ? + UINT64_MAX : +@@ -176,6 +185,9 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr + } + } else { + TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) { ++ if (FEX::HLE::GuestHighMemory::Contains(Start)) { ++ return; ++ } + auto rv = mprotect(reinterpret_cast(Start), Length, PROT_READ | PROT_WRITE); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length); + }); +@@ -227,6 +239,10 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + const auto ProtectBase = std::max(MapBase, Base); + const auto ProtectSize = std::min(MapTop, Top) - ProtectBase; + ++ const bool HighRange = FEX::HLE::GuestHighMemory::Contains(ProtectBase); ++ if (HighRange) { ++ FEX::HLE::GuestHighMemory::MarkCode(ProtectBase, ProtectSize); ++ } + if (Mapping->second.Flags.Shared) { + LOGMAN_THROW_A_FMT(Mapping->second.Resource, "VMA tracking error"); + +@@ -245,13 +261,17 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState + + const auto MirroredBase = std::max(VMAOffsetBase, OffsetBase); + const auto MirroredSize = std::min(OffsetTop, VMAOffsetTop) - MirroredBase; ++ if (FEX::HLE::GuestHighMemory::Contains(MirroredBase - VMAOffsetBase + VMABase)) { ++ FEX::HLE::GuestHighMemory::MarkCode(MirroredBase - VMAOffsetBase + VMABase, MirroredSize); ++ continue; ++ } + + auto rv = mprotect((void*)(MirroredBase - VMAOffsetBase + VMABase), MirroredSize, PROT_READ); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", MirroredBase, MirroredSize); + } + } while ((VMA = VMA->ResourceNextVMA)); + +- } else if (Mapping->second.Prot.Writable) { ++ } else if (!HighRange && Mapping->second.Prot.Writable) { + int rv = mprotect((void*)ProtectBase, ProtectSize, PROT_READ); + + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", ProtectBase, ProtectSize); +@@ -293,6 +313,10 @@ void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length) + + const auto OverlapBase = std::max(VMA->Offset, OffsetBase); + const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop); ++ if (FEX::HLE::GuestHighMemory::Contains(MapBase + (OverlapBase - OffsetBase))) { ++ FEX::HLE::GuestHighMemory::MarkCode(MapBase + (OverlapBase - OffsetBase), OverlapTop - OverlapBase); ++ continue; ++ } + auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ); + LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase); + } +@@ -429,6 +453,11 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState + return reinterpret_cast(Result); + } + LOGMAN_THROW_A_FMT(Is64Bit || (Result >> 32) == 0 || (Result >> 32) == 0xFFFFFFFF, "values must fit to 32 bits"); ++ } else if (FEX::HLE::GuestHighMemory::ClaimsMapping(reinterpret_cast(addr), length, flags)) { ++ Result = FEX::HLE::GuestHighMemory::Map(reinterpret_cast(addr), length, prot, flags, fd, offset); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return reinterpret_cast(Result); ++ } + } else { + Result = reinterpret_cast(::mmap(reinterpret_cast(addr), length, prot, flags, fd, offset)); + if (Result == ~0ULL) { +@@ -483,9 +512,16 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread + if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) { + return -EINVAL; + } +- Result = ::munmap(addr, length); +- if (Result == -1) { +- return -errno; ++ if (FEX::HLE::GuestHighMemory::Contains(Addr)) { ++ Result = FEX::HLE::GuestHighMemory::Unmap(Addr, length); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ } else { ++ Result = ::munmap(addr, length); ++ if (Result == -1) { ++ return -errno; ++ } + } + if (reinterpret_cast(addr) < 0x1'0000'0000ULL) { + Get32BitAllocator()->TrackUnmapped(addr, length); +@@ -511,6 +547,10 @@ uint64_t SyscallHandler::GuestMremap(bool Is64Bit, FEXCore::Core::InternalThread + { + auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread); + if (Is64Bit) { ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(old_address)) || ++ ((flags & MREMAP_FIXED) && FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(new_address)))) { ++ return -EINVAL; ++ } + Result = reinterpret_cast(::mremap(old_address, old_size, new_size, flags, new_address)); + if (Result == -1) { + return -errno; +@@ -602,9 +642,16 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa + } + } + +- Result = ::mprotect(addr, len, prot); +- if (Result == -1) { +- return -errno; ++ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast(addr))) { ++ Result = FEX::HLE::GuestHighMemory::Protect(reinterpret_cast(addr), len, prot); ++ if (FEX::HLE::HasSyscallError(Result)) { ++ return Result; ++ } ++ } else { ++ Result = ::mprotect(addr, len, prot); ++ if (Result == -1) { ++ return -errno; ++ } + } + + TrackMprotect(Thread, addr, len, prot); +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +index 2e59f2f..ee28680 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp +@@ -1,6 +1,7 @@ + // SPDX-License-Identifier: MIT + + #include "LinuxSyscalls/ThreadManager.h" ++#include "LinuxSyscalls/GuestHighMemory.h" + #include "LinuxSyscalls/SamplingProfiler.h" + + #include "LinuxSyscalls/Syscalls.h" +@@ -330,6 +331,7 @@ void ThreadManager::HandleThreadDeletion(FEX::HLE::ThreadStateObject* Thread, bo + FEXCore::Allocator::munmap(Thread->ldt_entries, Thread->ldt_entry_count * FEX::HLE::SyscallHandler::LDT_ENTRY_SIZE); + } + ++ FEX::HLE::GuestHighMemory::ReleaseThread(Thread); + CTX->DestroyThread(Thread->Thread); + FEX::HLE::_SyscallHandler->SeccompEmulator.FreeSeccompFilters(Thread); + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +index 9c5f9f1..e43dfc7 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -104,6 +104,40 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + bool Enabled; + } SyscallUserDispatch {}; + ++ struct { ++ uint8_t* Code; ++ uint64_t ResumePC; ++ uint64_t SavedScratch; ++ uint64_t BaseBefore; ++ uint64_t Delta; ++ uint64_t SavedMask; ++ uint32_t Scratch; ++ uint32_t Base; ++ bool Active; ++ bool Store; ++ bool Probe; ++ struct { ++ bool Held; ++ uint32_t Deferred; ++ siginfo_t DeferredInfo[3]; ++ } Mappings; ++ uint32_t Parts; ++ uint32_t BounceOffset; ++ struct { ++ uint64_t Guest; ++ uint64_t Host; ++ uint64_t Size; ++ } Pieces[2]; ++ alignas(16) uint8_t Bounce[96]; ++ struct { ++ uint64_t Host; ++ uint64_t Low; ++ uint64_t High; ++ uint32_t Size; ++ bool Valid; ++ } Monitor; ++ } HighMemoryTrap {}; ++ + uint64_t JITStackSP {}; + + struct TrapSignalFrame { +-- +2.43.0 + diff --git a/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch b/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch new file mode 100644 index 0000000000..899b071568 --- /dev/null +++ b/tools/fex/patches/0028-guest-cmdline-without-checkpoint-restore.patch @@ -0,0 +1,58 @@ +From 0510284085165d39ef0eabb83e7604fe1bb74c76 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 03:26:13 -0500 +Subject: [PATCH] Show the guest command line when the argument area cannot be + remapped + +Kernels built without checkpoint/restore support refuse PR_SET_MM_MAP, +so /proc/pid/cmdline kept showing the FEX invocation instead of the +guest program and the argv rewrites it makes. For 64-bit guests whose +arguments fit, the guest argument strings now live in the original +argument area and argv points there, which needs no privilege. +--- + Source/Tools/FEXInterpreter/ELFCodeLoader.h | 23 ++++++++++++++++++++- + 1 file changed, 22 insertions(+), 1 deletion(-) + +diff --git a/Source/Tools/FEXInterpreter/ELFCodeLoader.h b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +index b1a72d227..6d2157365 100644 +--- a/Source/Tools/FEXInterpreter/ELFCodeLoader.h ++++ b/Source/Tools/FEXInterpreter/ELFCodeLoader.h +@@ -874,13 +874,34 @@ public: + + int r = prctl(PR_SET_MM, PR_SET_MM_MAP, &map, sizeof(map), 0L); + if (r != 0) { +- LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, errno); ++ int Error = errno; ++ if (Is64BitMode() && MoveArgumentDataToHostArea(NewArgStart, ArgSize)) { ++ return; ++ } ++ LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (prctl failed: result {}, errno {})", r, Error); + } + } else { + LogMan::Msg::EFmt("Failed to remap /proc/pid/cmdline data (GetCurrentMap failed)"); + } + } + ++ bool MoveArgumentDataToHostArea(uintptr_t GuestArgStart, uint64_t ArgSize) { ++ struct prctl_mm_map map {}; ++ if (!GetCurrentMap(map) || map.arg_end <= map.arg_start || ArgSize > map.arg_end - map.arg_start) { ++ return false; ++ } ++ ++ auto HostArgs = reinterpret_cast(map.arg_start); ++ memmove(HostArgs, reinterpret_cast(GuestArgStart), ArgSize); ++ memset(HostArgs + ArgSize, 0, map.arg_end - map.arg_start - ArgSize); ++ ++ auto ArgumentPointers = reinterpret_cast(StackPointer + sizeof(uint64_t)); ++ for (size_t i = 0; i < ApplicationArgs.size(); ++i) { ++ ArgumentPointers[i] = ArgumentPointers[i] - GuestArgStart + map.arg_start; ++ } ++ return true; ++ } ++ + // Setups the stack initial data (argv, envp, auxv) + void SetupStack() { + StackPointer += StackSize(); +-- +2.43.0 + diff --git a/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch b/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch new file mode 100644 index 0000000000..61cf5004df --- /dev/null +++ b/tools/fex/patches/0029-proc-mount-tables-describe-the-container-procfs.patch @@ -0,0 +1,310 @@ +From fc926d0e9c63a3d5290a5d816029513349de78f6 Mon Sep 17 00:00:00 2001 +From: maxjivi05 +Date: Thu, 3 Dec 2026 08:03:20 -0500 +Subject: [PATCH] Describe the container's procfs in emulated mount tables + +Android mounts /proc with hidepid=invisible,gid=3009 so an app cannot see the +processes of other users. Every process of the container runs as the app's +user, so the container sees all of its own processes, as it would through a +procfs of its own in a PID namespace. The emulated /proc//mounts and +mountinfo now list the proc mount without the host instance's access options +(hidepid, gid, subset). Every other mount is passed through unchanged. +--- + .../EmulatedFiles/EmulatedFiles.cpp | 230 +++++++++++++----- + .../EmulatedFiles/EmulatedFiles.h | 1 + + 2 files changed, 170 insertions(+), 61 deletions(-) + +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +index 19bfc814f..85f1b3e15 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp +@@ -37,6 +37,7 @@ $end_info$ + #include + #include + #include ++#include + #include + #include + #include +@@ -649,6 +650,149 @@ static bool IsHostArchModule(const char* Path, fextl::unordered_map 0) { ++ Out.append(Buf, Len); ++ } else if (Len == 0) { ++ break; ++ } else if (errno != EINTR) { ++ LogMan::Msg::EFmt("Emulated /proc file: reading {} failed: {}", Path, errno); ++ ::close(HostFD); ++ return false; ++ } ++ } ++ ::close(HostFD); ++ return true; ++} ++ ++static int32_t SealedFileOf(const char* pathname, int32_t flags, const fextl::string& Data) { ++ int NewFD = GenTmpFD(pathname, flags); ++ if (NewFD < 0) { ++ LogMan::Msg::EFmt("Emulated /proc file: memfd_create failed: {}", errno); ++ return -1; ++ } ++ for (size_t Done = 0; Done < Data.size();) { ++ const ssize_t Wrote = ::write(NewFD, Data.data() + Done, Data.size() - Done); ++ if (Wrote > 0) { ++ Done += Wrote; ++ } else if (Wrote < 0 && errno == EINTR) { ++ continue; ++ } else { ++ LogMan::Msg::EFmt("Emulated /proc file: writing the synthesized file failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ } ++ if (::lseek(NewFD, 0, SEEK_SET) != 0) { ++ LogMan::Msg::EFmt("Emulated /proc file: lseek failed: {}", errno); ++ ::close(NewFD); ++ return -1; ++ } ++ SealTmpFD(NewFD); ++ return NewFD; ++} ++ ++static const char* ProcFileOfPid(const char* Path) { ++ if (strncmp(Path, "/proc/", 6) != 0) { ++ return nullptr; ++ } ++ const char* P = Path + 6; ++ if (strncmp(P, "self/", 5) == 0) { ++ return P + 5; ++ } ++ if (strncmp(P, "thread-self/", 12) == 0) { ++ return P + 12; ++ } ++ if (!isdigit(*P)) { ++ return P; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ if (*P++ != '/') { ++ return nullptr; ++ } ++ if (strncmp(P, "task/", 5) == 0) { ++ P += 5; ++ if (!isdigit(*P)) { ++ return nullptr; ++ } ++ while (isdigit(*P)) { ++ ++P; ++ } ++ if (*P++ != '/') { ++ return nullptr; ++ } ++ } ++ return P; ++} ++ ++static bool IsProcMountTablePath(const char* Path) { ++ const char* File = ProcFileOfPid(Path); ++ return File && (strcmp(File, "mounts") == 0 || strcmp(File, "mountinfo") == 0); ++} ++ ++static fextl::string ContainerProcOptions(std::string_view Options) { ++ fextl::string Out; ++ size_t Pos = 0; ++ while (Pos <= Options.size()) { ++ size_t Comma = Options.find(',', Pos); ++ if (Comma == std::string_view::npos) { ++ Comma = Options.size(); ++ } ++ const std::string_view Option = Options.substr(Pos, Comma - Pos); ++ if (!Option.empty() && !Option.starts_with("hidepid=") && !Option.starts_with("gid=") && !Option.starts_with("subset=")) { ++ if (!Out.empty()) { ++ Out += ','; ++ } ++ Out.append(Option); ++ } ++ Pos = Comma + 1; ++ } ++ return Out; ++} ++ ++static fextl::string ContainerMountLine(std::string_view Line, bool MountInfo) { ++ fextl::vector Fields; ++ size_t Pos = 0; ++ while (Pos < Line.size()) { ++ size_t Space = Line.find(' ', Pos); ++ if (Space == std::string_view::npos) { ++ Space = Line.size(); ++ } ++ Fields.push_back(Line.substr(Pos, Space - Pos)); ++ Pos = Space + 1; ++ } ++ size_t Type = 2; ++ if (MountInfo) { ++ auto Dash = std::find(Fields.begin(), Fields.end(), std::string_view("-")); ++ Type = static_cast(Dash - Fields.begin()) + 1; ++ } ++ const size_t Options = MountInfo ? Type + 2 : Type + 1; ++ if (Options >= Fields.size() || Fields[Type] != "proc") { ++ return fextl::string(Line); ++ } ++ fextl::string Out; ++ for (size_t i = 0; i < Fields.size(); ++i) { ++ if (i) { ++ Out += ' '; ++ } ++ if (i == Options) { ++ Out += ContainerProcOptions(Fields[i]); ++ } else { ++ Out.append(Fields[i]); ++ } ++ } ++ return Out; ++} ++ + static bool IsProcMapsPath(const char* Path) { + if (strncmp(Path, "/proc/", 6) != 0) { + return false; +@@ -673,6 +817,9 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + if (pathname && IsProcMapsPath(pathname)) { + return ProcMaps(CTX, AT_FDCWD, pathname, flags, mode); + } ++ if (pathname && IsProcMountTablePath(pathname)) { ++ return ProcMounts(CTX, AT_FDCWD, pathname, flags, mode); ++ } + return -1; + } + +@@ -680,25 +827,10 @@ int32_t EmulatedFDManager::Open(const char* pathname, int flags, uint32_t mode) + } + + int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +- int HostFD = ::open(pathname, O_RDONLY | O_CLOEXEC); +- if (HostFD < 0) { +- return -1; +- } + fextl::string In; +- char Buf[65536]; +- for (;;) { +- const ssize_t Len = ::read(HostFD, Buf, sizeof(Buf)); +- if (Len > 0) { +- In.append(Buf, Len); +- } else if (Len == 0) { +- break; +- } else if (errno != EINTR) { +- LogMan::Msg::EFmt("ProcMaps: reading {} failed: {}", pathname, errno); +- ::close(HostFD); +- return -1; +- } ++ if (!ReadHostFile(pathname, In)) { ++ return -1; + } +- ::close(HostFD); + + constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096; + const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47; +@@ -756,30 +888,29 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, + Pos = End; + } + +- int NewFD = GenTmpFD(pathname, flags); +- if (NewFD < 0) { +- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); ++ return SealedFileOf(pathname, flags, Out); ++} ++ ++int32_t EmulatedFDManager::ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { ++ fextl::string In; ++ if (!ReadHostFile(pathname, In)) { + return -1; + } +- for (size_t Done = 0; Done < Out.size();) { +- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); +- if (Wrote > 0) { +- Done += Wrote; +- } else if (Wrote < 0 && errno == EINTR) { +- continue; +- } else { +- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); +- ::close(NewFD); +- return -1; ++ const char* File = ProcFileOfPid(pathname); ++ const bool MountInfo = File && strcmp(File, "mountinfo") == 0; ++ fextl::string Out; ++ Out.reserve(In.size()); ++ size_t Pos = 0; ++ while (Pos < In.size()) { ++ size_t Eol = In.find('\n', Pos); ++ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol; ++ Out += ContainerMountLine(std::string_view(In).substr(Pos, LineEnd - Pos), MountInfo); ++ if (Eol != fextl::string::npos) { ++ Out += '\n'; + } ++ Pos = LineEnd + 1; + } +- if (::lseek(NewFD, 0, SEEK_SET) != 0) { +- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- SealTmpFD(NewFD); +- return NewFD; ++ return SealedFileOf(pathname, flags, Out); + } + + int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +@@ -832,30 +963,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd + Cursor = Eol + 1; + } + +- int NewFD = GenTmpFD(pathname, flags); +- if (NewFD < 0) { +- LogMan::Msg::EFmt("ProcMaps: memfd_create failed: {}", errno); +- return -1; +- } +- for (size_t Done = 0; Done < Out.size();) { +- const ssize_t Wrote = ::write(NewFD, Out.data() + Done, Out.size() - Done); +- if (Wrote > 0) { +- Done += Wrote; +- } else if (Wrote < 0 && errno == EINTR) { +- continue; +- } else { +- LogMan::Msg::EFmt("ProcMaps: writing the synthesized file failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- } +- if (::lseek(NewFD, 0, SEEK_SET) != 0) { +- LogMan::Msg::EFmt("ProcMaps: lseek failed: {}", errno); +- ::close(NewFD); +- return -1; +- } +- SealTmpFD(NewFD); +- return NewFD; ++ return SealedFileOf(pathname, flags, Out); + } + + int32_t EmulatedFDManager::ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +index b98ef4bda..b1ec241a7 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.h +@@ -35,6 +35,7 @@ private: + + static int32_t ProcAuxv(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + static int32_t ProcMaps(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); ++ static int32_t ProcMounts(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + static int32_t ProcStatus(FEXCore::Context::Context* ctx, int32_t fd, const char* pathname, int32_t flags, mode_t mode); + const uint32_t ThreadsConfig; + }; diff --git a/tools/fex/probes/guest-high-memory.c b/tools/fex/probes/guest-high-memory.c new file mode 100644 index 0000000000..fa4450183a --- /dev/null +++ b/tools/fex/probes/guest-high-memory.c @@ -0,0 +1,92 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +#define HIGH ((uintptr_t)0x7e0000000000ULL) +#define ALIAS ((uintptr_t)0x7e0000100000ULL) +#define THREADS 4 +#define ITERS 200000 + +static volatile uint64_t *counter; +static volatile uint64_t *cas; +static int fails; + +static void check(const char *name, int ok) { + printf("%s %s\n", ok ? "PASS" : "FAIL", name); + if (!ok) fails++; +} + +static void *worker(void *arg) { + (void)arg; + for (int i = 0; i < ITERS; i++) { + __atomic_fetch_add(counter, 1, __ATOMIC_SEQ_CST); + uint64_t old = __atomic_load_n(cas, __ATOMIC_RELAXED); + while (!__atomic_compare_exchange_n(cas, &old, old + 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_RELAXED)) { + } + } + return NULL; +} + +int main(void) { + alarm(60); + uint8_t *high = mmap((void *)HIGH, 65536, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + if (high == MAP_FAILED) { + printf("NOTCLAIMED errno=%d\n", errno); + return 0; + } + check("fixed-high-map", high == (uint8_t *)HIGH); + memset(high, 0x5a, 65536); + check("load-store", high[100] == 0x5a && high[65535] == 0x5a); + + counter = (uint64_t *)(high + 64); + cas = (uint64_t *)(high + 128); + *counter = 0; + *cas = 0; + pthread_t t[THREADS]; + for (int i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, worker, NULL); + for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL); + check("atomic-add", *counter == (uint64_t)THREADS * ITERS); + check("atomic-cmpxchg", *cas == (uint64_t)THREADS * ITERS); + + int p[2]; + check("pipe", pipe(p) == 0); + memcpy(high + 4096, "hello ", 6); + memcpy(high + 8192, "world", 5); + struct iovec out[2] = {{high + 4096, 6}, {high + 8192, 5}}; + ssize_t w = writev(p[1], out, 2); + memset(high + 12288, 0, 64); + struct iovec in[2] = {{high + 12288, 3}, {high + 12291, 8}}; + ssize_t r = w == 11 ? readv(p[0], in, 2) : -1; + check("writev-readv", w == 11 && r == 11 && memcmp(high + 12288, "hello world", 11) == 0); + + int wrote = write(p[1], "abcdef", 6) == 6; + check("write", wrote); + check("read", wrote && read(p[0], high + 20000, 6) == 6 && memcmp(high + 20000, "abcdef", 6) == 0); + + high[30000] = 7; + check("madvise-dontneed", madvise(high + 28672, 4096, MADV_DONTNEED) == 0 && high[30000] == 0); + + int fd = memfd_create("code", 0); + check("memfd", fd >= 0 && ftruncate(fd, 4096) == 0); + static const uint8_t code[] = {0xb8, 0x01, 0x00, 0x00, 0x00, 0xc3}; + check("pwrite", pwrite(fd, code, sizeof code, 0) == (ssize_t)sizeof code); + uint8_t *low = mmap(NULL, 4096, PROT_READ | PROT_EXEC, MAP_SHARED, fd, 0); + uint8_t *alias = mmap((void *)ALIAS, 4096, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, 0); + check("alias-map", low != MAP_FAILED && alias == (uint8_t *)ALIAS); + int (*fn)(void) = (int (*)(void))low; + int before = fn(); + alias[1] = 2; + __atomic_thread_fence(__ATOMIC_SEQ_CST); + int after = fn(); + printf("alias before=%d after=%d\n", before, after); + check("smc-through-high-alias", before == 1 && after == 2); + + printf("%s\n", fails ? "RESULT FAIL" : "RESULT PASS"); + return fails != 0; +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index 0b432bb5d3..6160d52bb0 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -664,7 +664,7 @@ def data_dir(env): return DATA_DIR -def guest_environment(fex, env): +def guest_environment(fex, env, keep_compat=False): result = dict(env) data = data_dir(env) for directory in (CONFIG_DIR, data, CACHE_DIR): @@ -672,7 +672,7 @@ def guest_environment(fex, env): result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/" result["FEX_APP_DATA_LOCATION"] = data + "/" result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/" - if result.get("STEAM_COMPAT_DATA_PATH"): + if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat: short = data if data != DATA_DIR else "/tmp/fex" os.makedirs(short, exist_ok=True) result["STEAM_COMPAT_DATA_PATH"] = short @@ -750,9 +750,12 @@ def vulkan_thunk_loads(fex, folder): def required_runtime(program): - text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or "" - match = re.search(r'"require_tool_appid"\s+"(\d+)"', text) - return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID + folder = os.path.dirname(program) + for name in ("toolmanifest.vdf.droiddeck-orig", "toolmanifest.vdf"): + match = re.search(r'"require_tool_appid"\s+"(\d+)"', read_text(os.path.join(folder, name)) or "") + if match and match.group(1) in RUNTIMES: + return match.group(1) + return SNIPER_APPID def resolve(program, env): @@ -761,7 +764,7 @@ def resolve(program, env): return shutil.which(program, path=env.get("PATH")) or program -def launch(command, env, mode, decide=None): +def launch(command, env, mode, decide=None, keep_compat=False): program = resolve(command[0], env) use = mode == "on" or (mode == "auto" and needs_fex(decide or program)) if not use: @@ -769,7 +772,7 @@ def launch(command, env, mode, decide=None): fex = prepare(required_runtime(program)) if fex is None: return 126 - guest = guest_environment(fex, env) + guest = guest_environment(fex, env, keep_compat) x86_64 = elf_arch(program) != "i386" thunks = "on" if "FEX_THUNKCONFIG" in guest else "off" folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program) @@ -963,7 +966,7 @@ def parse_run(args): def main(argv): if not argv: - say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status") + say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | update | status") return 2 action, args = argv[0], list(argv[1:]) if action == "steam": @@ -975,6 +978,10 @@ def main(argv): if not command: return 2 return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto")) + if action == "proton": + if len(args) < 2: + return 2 + return launch(args, game_environment(dict(os.environ), args[2:] or args), "on", keep_compat=True) if action == "run": try: mode, decide, command = parse_run(args) @@ -996,6 +1003,10 @@ def main(argv): return extract(args[0]) if action == "prepare": return 0 if prepare() else 1 + if action == "update": + with locked(): + update_own_fex() + return 0 if action == "status": with locked(): status = describe(fex_install(), runtime_platform(), graphics_platform()) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update index 25f445adee..f25d2a3394 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update @@ -29,10 +29,14 @@ fex_install() { return 1 fi (cd "$tmp/root" && find . ! -type d) > "$tmp/files" - for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do - [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue - (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done - done > "$tmp/stale" + { + for d in usr/local/share/fex-emu/GuestThunks usr/local/share/fex-emu/GuestThunks_32 usr/local/lib/fex-emu/HostThunks usr/local/lib/fex-emu/HostThunks_32; do + [ -d "$tmp/root/$d" ] && [ -d "$dst$d" ] || continue + (cd "$dst" && find "$d" ! -type d) | while IFS= read -r f; do grep -qxF "./$f" "$tmp/files" || echo "$f"; done + done + f=usr/local/share/fex-emu/.droiddeck-patches + if [ -e "$dst$f" ] && ! grep -qxF "./$f" "$tmp/files"; then echo "$f"; fi + } > "$tmp/stale" mkdir "$tmp/old" while IFS= read -r f; do f=${f#./} diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 4eb7ba26f7..c3c10c8638 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -318,12 +318,72 @@ dd_vacdiag() { } """ +DD_ANTICHEAT_SETUP = """ +dd_anticheat_runtime() { + local current=$1 name=$2 bridge=$3 library + if [ -n "$current" ] && [ -n "$(find -L "$current" -iname "$bridge" -print -quit 2>/dev/null)" ]; then + printf '%s' "$current"; return 0 + fi + while IFS= read -r library; do + [ -n "$(find "$library/steamapps/common/$name" -iname "$bridge" -print -quit 2>/dev/null)" ] || continue + printf '%s' "$library/steamapps/common/$name"; return 0 + done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null) + return 1 +} + +dd_x86_64_proton() { + [ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ] +} + +dd_anticheat() { + case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac + case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac + local game=${STEAM_COMPAT_INSTALL_PATH:-} found tool runtime + [ -d "$game" ] || return 0 + found=$(find "$game" -maxdepth 3 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\ + -o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print -quit 2>/dev/null) + [ -n "$found" ] || return 0 + case ${DD_AC_TOOL:-DroidDeck-Proton} in + DroidDeck-Proton*) ;; + *) + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; ${DD_AC_TOOL} was chosen for this game, so it runs as chosen" >&2 + return 0 + ;; + esac + /usr/local/bin/droiddeck-fex update || true + if ! grep -qx fixed-guest-memory-above-host-address-limit /usr/local/share/fex-emu/.droiddeck-patches 2>/dev/null; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; the installed FEX build cannot run anti-cheat, so this launch stays on ARM64" >&2 + return 0 + fi + DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam} + tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do + [ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d" + done | sort -V | tail -n 1) + if [ -z "$tool" ]; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2 + return 0 + fi + case ${found,,} in + *easyanticheat*) runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime" easyanticheat_x64.so) && export PROTON_EAC_RUNTIME="$runtime" ;; + *) runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime" beclient_x64.so) && export PROTON_BATTLEYE_RUNTIME="$runtime" ;; + esac + if [ -z "$runtime" ]; then + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2 + return 0 + fi + dd_game_cpus + declare -F dd_components >/dev/null && dd_components "$tool" + echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2 + exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@" +} +""" + # DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the # newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set. DD_BIONIC_PROOT_FALLBACK = """ if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do - [ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue + [ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d" done | sort -V | tail -n 1 | cut -f 2-) if [ -n "$dd_fallback" ]; then @@ -461,6 +521,7 @@ for name in %s; do [ -n "$depot" ] && break done if [ -n "$depot" ]; then + dd_anticheat "$@" dd_components "$depot" dd_directaudio "$depot" "$@" dd_game_cpus @@ -481,7 +542,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH def launcher_sh(sources=SOURCES): return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( "verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP - + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) + + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1) LAUNCHER_SH = launcher_sh() @@ -516,6 +577,11 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then *) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;; esac fi +if dd_x86_64_proton "$here"; then + dd_game_cpus + exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@" +fi +DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@" dd_components "$here" dd_directaudio "$here" "$@" dd_game_cpus @@ -530,9 +596,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve def extra_wrapper_sh(entry_point): - return (EXTRA_WRAPPER_SH % entry_point).replace( + return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + 'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) @@ -1332,10 +1398,18 @@ def tool_catalog(steam_root, extras=None): continue extras[first_key(os.path.join(tool_dir, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or entry] = entry for name, entry in sorted(extras.items()): - catalog.append(tool_entry(name, display_name(entry), os.path.join(tools, entry), False)) + tool = tool_entry(name, display_name(entry), os.path.join(tools, entry), False) + if x86_64_layout(os.path.join(tools, entry)): + tool["x86_64"] = True + catalog.append(tool) return catalog +def x86_64_layout(path): + return (os.path.isdir(os.path.join(path, "files", "lib", "wine", "x86_64-unix")) and + not os.path.isdir(os.path.join(path, "files", "bin-arm64"))) + + def built_from(name, catalog, runnable=None): depot = VALVE_DEPOTS.get(name) tools = [t["name"] for t in catalog if depot and t["valve"] and t["dir"] == depot and @@ -1474,7 +1548,7 @@ ARCH_WORDS = re.compile(r"(?i)aarch64|arm64|x86_64|x86-64|amd64") def own_builds(tools): return [t for t in tools if isinstance(t, dict) and not t.get("valve") and - isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name")] + isinstance(t.get("dir"), str) and t["dir"].startswith(OWN_PROTON) and t.get("name") and not t.get("x86_64")] def build_key(name): @@ -1512,7 +1586,8 @@ def choose_default(steam_default, state, request, catalog, adopt_steam=True, app wanted = requested_tool(request, catalog) state["applied"] = seq if wanted: - if wanted != state.get("default"): + if wanted != state.get("default") or (state.get("source") not in ("app", "steam") and any( + t["name"] == wanted and t.get("x86_64") for t in catalog)): state.update(default=wanted, seq=now or now_ms(), source="app") else: print("steam-compatibility: the app asked for %s, which is not installed; kept %s" % ( @@ -1709,7 +1784,11 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non read_json(state_path("request.json", directory)), catalog) else: default = state.get("default") if state.get("default") in names else TOOL - if settle and newest and default == TOOL and state.get("source") not in ("app", "steam"): + automatic = state.get("source") not in ("app", "steam") + if settle and automatic and default in {t["name"] for t in catalog if t.get("x86_64")}: + default = newest or TOOL + state.update(default=default, seq=now_ms(), source="update") + elif settle and newest and default == TOOL and automatic: default = newest state.update(default=newest, seq=now_ms(), source="update") state.pop("own_proton", None) diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 3bd38f3bc9..89e62129cf 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -957,8 +957,9 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) { __attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int), int *ret) { - if (n != 1 || vd_find(fds[0].fd) == NULL) return 0; + if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0; struct vdec *v = vd_find(fds[0].fd); + if (v == NULL) return 0; pthread_mutex_lock(&vd_lock); short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0); pthread_mutex_unlock(&vd_lock); diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 7fc21d0cab..446996a06e 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -18,6 +19,9 @@ #include +#ifndef PR_SET_SYSCALL_USER_DISPATCH +#define PR_SET_SYSCALL_USER_DISPATCH 59 +#endif #ifndef MADV_PAGEOUT #define MADV_PAGEOUT 21 #endif @@ -538,13 +542,40 @@ static int zr_start(void) { return 0; } +static __thread volatile unsigned char *zr_dispatch __attribute__((tls_model("initial-exec"))); + +int prctl(int option, ...) { + va_list ap; + va_start(ap, option); + unsigned long arg2 = va_arg(ap, unsigned long); + unsigned long arg3 = va_arg(ap, unsigned long); + unsigned long arg4 = va_arg(ap, unsigned long); + unsigned long arg5 = va_arg(ap, unsigned long); + va_end(ap); + volatile unsigned char *dispatch = zr_dispatch; + unsigned char selector = dispatch != NULL ? *dispatch : 0; + if (selector) *dispatch = 0; + long result = zr_sys(SYS_prctl, option, arg2, arg3, arg4, arg5); + if (selector) *dispatch = selector; + if ((unsigned long)result > -4096UL) { + errno = (int)-result; + return -1; + } + if (option == PR_SET_SYSCALL_USER_DISPATCH) zr_dispatch = arg2 ? (volatile unsigned char *)arg5 : NULL; + return (int)result; +} + static void zr_handler(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (info == NULL || info->si_code != SI_USER) return; + volatile unsigned char *dispatch = zr_dispatch; + unsigned char selector = dispatch != NULL ? *dispatch : 0; + if (selector) *dispatch = 0; int saved = errno; if (__atomic_fetch_add(&zr_requests, 1, __ATOMIC_ACQ_REL) == 0 && !zr_start()) zr_drain(0); errno = saved; + if (selector) *dispatch = selector; } static void zr_child(void) { diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index db55262540..ede8c4354d 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -374,6 +374,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOSYS; return -1; } + if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe; if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp); // Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0), diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 0ca6f97880..9fd5a8077f 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -668,6 +668,19 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_execve + if (number == __NR_execve) { + return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3); + } +#endif + +#ifdef __NR_execveat + if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' && + (((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) { + return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4); + } +#endif + #ifdef __NR_clone3 if (number == __NR_clone3) { errno = ENOSYS; diff --git a/tools/nativeguest/hook/signals.c b/tools/nativeguest/hook/signals.c index 4ed9522da4..3d370bae28 100644 --- a/tools/nativeguest/hook/signals.c +++ b/tools/nativeguest/hook/signals.c @@ -10,6 +10,12 @@ #define SYS_SECCOMP 1 #endif +#if defined(__aarch64__) +#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U +#else +#define DDNATV_HOST_AUDIT_ARCH 0x40000028U +#endif + static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *); // A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's @@ -57,7 +63,13 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va // Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { if (!ctx || !info) return; - if (info->si_code != SYS_SECCOMP) { + int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH; + if (!host_trap && g_app_sigsys_set) { + if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx); + else g_app_sigsys.sa_handler(sig); + return; + } + if (!host_trap) { int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction(); if (real_sig) { struct sigaction sa_dfl; @@ -69,11 +81,6 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) { raise(sig); return; } - if (info->si_errno != 0 && g_app_sigsys_set) { - if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx); - else g_app_sigsys.sa_handler(sig); - return; - } ucontext_t *uctx = (ucontext_t *)ctx; int sys_nr = info->si_syscall; diff --git a/tools/tests/test_anticheat_routing.py b/tools/tests/test_anticheat_routing.py new file mode 100644 index 0000000000..518d194725 --- /dev/null +++ b/tools/tests/test_anticheat_routing.py @@ -0,0 +1,223 @@ +import json +import os +from pathlib import Path +import runpy +import subprocess +import tempfile +import unittest + + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility") +SETUP = COMPAT["DD_ANTICHEAT_SETUP"] + + +class AntiCheatRoutingTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.steam = self.root / "Steam" + self.common = self.steam / "steamapps" / "common" + self.tools = self.steam / "compatibilitytools.d" + self.game = self.common / "Some Game" + self.game.mkdir(parents=True) + self.tools.mkdir(parents=True) + self.record = self.root / "record.json" + self.fex = self.root / "droiddeck-fex" + self.fex.write_text("#!/bin/bash\nif [ \"$1\" = update ]; then echo \"$1\" >> \"$DD_RECORD.update\"; " + "[ -n \"${DD_UPDATED_PATCHES:-}\" ] && printf '%s\\n' \"$DD_UPDATED_PATCHES\" > \"$DD_PATCHES\"; exit 0; fi\n" + "python3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], " + "\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, " + "open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n") + self.fex.chmod(0o755) + self.patches = self.root / "fex-patches" + self.patches.write_text("openat2-enosys-fallback\nfixed-guest-memory-above-host-address-limit\n") + + def tool(self, name, x86_64=True): + tool = self.tools / name + (tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True) + if not x86_64: + (tool / "files" / "bin-arm64").mkdir() + (tool / "proton").write_text("#!/bin/sh\n") + (tool / "proton").chmod(0o755) + return tool + + def runtime(self, name, library): + folder = self.common / name / "v2" / "lib64" + folder.mkdir(parents=True) + (folder / library).write_text("") + return self.common / name + + def file(self, relative): + path = self.game / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("{}") + + def launch(self, verb="waitforexitandrun", extra=None): + script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)).replace( + "/usr/local/share/fex-emu/.droiddeck-patches", str(self.patches)) + ( + "dd_game_cpus() { :; }\n" + "verb=$1; shift\n" + "dd_anticheat \"$@\"\n" + "echo stayed\n") + env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record), "DD_PATCHES": str(self.patches), + "STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)} + env.update(extra or {}) + result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")], + env=env, capture_output=True, text=True, timeout=30) + routed = json.loads(self.record.read_text()) if self.record.exists() else None + return result, routed + + def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + newest = self.tool("DroidDeck-Proton-11.0-10-x86_64") + self.tool("DroidDeck-Proton-11.0-20", x86_64=False) + runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertNotIn("stayed", result.stdout) + self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")]) + self.assertEqual(routed["eac"], str(runtime)) + self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr) + + def test_battleye_sets_its_own_runtime(self): + self.file("BattlEye/BEClient_x64.so") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so") + _, routed = self.launch() + self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None)) + + def test_a_runtime_already_set_with_files_is_kept(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + own = self.root / "own-eac" + (own / "v2").mkdir(parents=True) + (own / "v2" / "easyanticheat_x64.so").write_text("") + _, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)}) + self.assertEqual(routed["eac"], str(own)) + + def test_games_without_anti_cheat_files_stay_on_arm64(self): + self.file("Data/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertEqual(result.stderr, "") + + def test_without_an_x86_64_build_the_launch_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-20", x86_64=False) + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr) + + def test_without_the_runtime_files_the_launch_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + (self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True) + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("its Proton runtime is not installed", result.stderr) + + def test_the_user_can_turn_routing_off(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"}) + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + + def test_a_tool_the_user_chose_is_kept(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for chosen in ("GE-Proton11-15-aarch64", "DroidDeck-Bionic-14.1-r85", "proton_experimental"): + result, routed = self.launch(extra={"DD_AC_TOOL": chosen}) + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("%s was chosen for this game, so it runs as chosen" % chosen, result.stderr) + + def test_droiddeck_proton_builds_still_route(self): + self.file("EasyAntiCheat/Settings.json") + newest = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for own in ("DroidDeck-Proton 11-14.1", "DroidDeck-Proton-11-14.2"): + self.record.unlink(missing_ok=True) + result, routed = self.launch(extra={"DD_AC_TOOL": own}) + self.assertEqual(routed["argv"][1], str(newest / "proton")) + + def test_a_fex_build_without_high_guest_memory_stays_on_arm64(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + for patches in ("openat2-enosys-fallback\n", None): + if patches is None: + self.patches.unlink() + else: + self.patches.write_text(patches) + result, routed = self.launch() + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + self.assertIn("the installed FEX build cannot run anti-cheat", result.stderr) + + def test_an_older_fex_build_is_updated_before_routing(self): + self.file("EasyAntiCheat/Settings.json") + tool = self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + self.patches.unlink() + result, routed = self.launch(extra={"DD_UPDATED_PATCHES": "fixed-guest-memory-above-host-address-limit"}) + self.assertEqual(routed["argv"][1], str(tool / "proton")) + self.assertNotIn("cannot run anti-cheat", result.stderr) + self.assertTrue((self.root / "record.json.update").exists()) + + def test_games_without_anti_cheat_files_do_not_update_fex(self): + self.file("Data/Settings.json") + self.launch() + self.assertFalse((self.root / "record.json.update").exists()) + + def test_choices_are_kept_the_same_with_an_older_fex_build(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + self.patches.unlink() + result, routed = self.launch(extra={"DD_AC_TOOL": "GE-Proton11-15-aarch64"}) + self.assertIsNone(routed) + self.assertIn("GE-Proton11-15-aarch64 was chosen for this game, so it runs as chosen", result.stderr) + result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"}) + self.assertIsNone(routed) + self.assertEqual(result.stderr, "") + + def test_the_fex_build_lists_its_patches(self): + build = (BIN.parents[4] / "fex" / "build-in-arch.sh").read_text() + self.assertIn("> out/usr/local/share/fex-emu/.droiddeck-patches", build) + names = {p.stem.split("-", 1)[1] for p in (BIN.parents[4] / "fex" / "patches").glob("*.patch")} + self.assertIn("fixed-guest-memory-above-host-address-limit", names) + + def test_adopted_tools_pass_their_own_folder_name(self): + wrapper = COMPAT["extra_wrapper_sh"]("proton") + self.assertIn('DD_AC_TOOL=$(basename "$(cd "$here" && pwd -P)") dd_anticheat "$@"', wrapper) + self.assertNotIn("DD_AC_TOOL=", COMPAT["LAUNCHER_SH"]) + + def test_other_verbs_are_left_alone(self): + self.file("EasyAntiCheat/Settings.json") + self.tool("DroidDeck-Proton-11.0-1-x86_64") + self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so") + result, routed = self.launch(verb="getcompatpath") + self.assertIsNone(routed) + self.assertIn("stayed", result.stdout) + + def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self): + launcher = COMPAT["LAUNCHER_SH"] + self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"')) + wrapper = COMPAT["extra_wrapper_sh"]("proton") + self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback=")) + self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"')) + self.assertIn('! dd_x86_64_proton "$d"', wrapper) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 79f7043cbb..2eecb9cfeb 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -1235,6 +1235,29 @@ class LaunchTest(FexTestCase): self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files")) self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350") + def test_an_adopted_proton_keeps_the_runtime_of_its_original_manifest(self): + proton = self.proton("4183110") + folder = proton.parent + os.rename(folder / "toolmanifest.vdf", folder / "toolmanifest.vdf.droiddeck-orig") + self.write(folder / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/droiddeck-proton-wrap %verb%"\n}\n') + self.assertEqual(FEX["required_runtime"](str(proton)), "4183110") + os.unlink(folder / "toolmanifest.vdf.droiddeck-orig") + self.assertEqual(FEX["required_runtime"](str(proton)), "1628350") + + def test_proton_action_keeps_the_prefix_and_runs_under_fex(self): + self.fex_tool() + self.runtime() + proton = self.proton("1628350") + prefix = str(self.tmp / "compatdata" / "730") + env = {"STEAM_COMPAT_DATA_PATH": prefix} + with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated: + self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"]) + command, guest = emulated.call_args[0][1], emulated.call_args[0][2] + self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"]) + self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix) + self.assertEqual(FEX["main"](["proton", str(proton)]), 2) + def test_native_programs_run_directly(self): program = self.write(self.tmp / "native", elf(183), 0o755) with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated: diff --git a/tools/tests/test_droiddeck_proton_default.py b/tools/tests/test_droiddeck_proton_default.py index 2173a223a1..194bf022c9 100644 --- a/tools/tests/test_droiddeck_proton_default.py +++ b/tools/tests/test_droiddeck_proton_default.py @@ -15,6 +15,8 @@ VALVE_11 = {"name": COMPAT["TOOL_11"], "display": "Proton 11.0 ARM64", "dir": CO GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False} GE10 = {"name": "GE-Proton10-3", "display": "GE-Proton10-3", "dir": "GE-Proton10-3", "valve": False} NEWER = {"name": "DroidDeck-Proton-11-12.1", "display": "DroidDeck-Proton 11-12.1", "dir": "DroidDeck-Proton 11-12.1", "valve": False} +X86 = {"name": "DroidDeck-Proton-11-14.2-x86_64", "display": "DroidDeck-Proton 11-14.2 x86-64", "dir": "DroidDeck-Proton 11-14.2 x86-64", + "valve": False, "x86_64": True} def config_text(entries): @@ -204,6 +206,50 @@ class DroidDeckProtonDefaultTest(unittest.TestCase): self.assertEqual(newest, "b") self.assertEqual(gone, {OLD["name"]}) + def test_an_x86_64_build_never_becomes_the_automatic_default(self): + default, mapping, state = self.run_default( + {"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL)], [VALVE, NEW, X86], ["42"]) + self.assertEqual((default, mapping["0"]), (NEW["name"], NEW["name"])) + default, mapping, _ = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, X86]) + self.assertEqual((default, mapping), (TOOL, {"0": TOOL})) + + def test_an_automatic_x86_64_default_moves_back_to_arm64(self): + default, mapping, state = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, NEW, X86]) + self.assertEqual((default, mapping, state["source"]), (NEW["name"], {"0": NEW["name"]}, "update")) + default, mapping, _ = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update"}, [("0", X86["name"])], [VALVE, X86]) + self.assertEqual((default, mapping), (TOOL, {"0": TOOL})) + + def test_an_x86_64_default_the_user_picked_is_kept(self): + for source in ("app", "steam"): + default, mapping, _ = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": source}, [("0", X86["name"])], [VALVE, NEW, X86]) + self.assertEqual((default, mapping), (X86["name"], {"0": X86["name"]})) + + def test_a_request_for_the_automatic_x86_64_default_keeps_it(self): + default, mapping, state = self.run_default( + {"default": X86["name"], "written": X86["name"], "source": "update", "applied": 1}, [("0", X86["name"])], + [VALVE, NEW, X86], request={"seq": 2, "name": X86["name"]}) + self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app")) + default, mapping, state = self.run_default(state, [("0", X86["name"])], [VALVE, NEW, X86], + request={"seq": 2, "name": X86["name"]}) + self.assertEqual((default, mapping, state["source"]), (X86["name"], {"0": X86["name"]}, "app")) + + def test_x86_64_layouts_are_marked_in_the_catalog(self): + with tempfile.TemporaryDirectory() as tmp: + tools = Path(tmp) / "compatibilitytools.d" + for entry, arm in (("DroidDeck-Proton 11-14.2 x86-64", False), ("DroidDeck-Proton 11-14.2", True)): + (tools / entry / "files" / "lib" / "wine" / ("aarch64-unix" if arm else "x86_64-unix")).mkdir(parents=True) + if arm: + (tools / entry / "files" / "bin-arm64").mkdir() + (tools / entry / COMPAT["EXTRA_WRAPPER"]).write_text("") + catalog = {t["dir"]: t for t in COMPAT["tool_catalog"](tmp) if not t["valve"]} + self.assertTrue(catalog["DroidDeck-Proton 11-14.2 x86-64"].get("x86_64")) + self.assertNotIn("x86_64", catalog["DroidDeck-Proton 11-14.2"]) + newest, _ = COMPAT["own_proton_moves"]({}, list(catalog.values())) + self.assertEqual(newest, catalog["DroidDeck-Proton 11-14.2"]["name"]) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_fex_guest_high_memory.py b/tools/tests/test_fex_guest_high_memory.py new file mode 100644 index 0000000000..ff21c4adad --- /dev/null +++ b/tools/tests/test_fex_guest_high_memory.py @@ -0,0 +1,3392 @@ +import platform +import re +import shutil +import signal +import subprocess +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch" +PROBE = REPO / "tools/fex/probes/guest-high-memory.c" + +SOURCE = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp" +HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h" + +KERNEL_NAMES = {"pread_64": "pread64", "pwrite_64": "pwrite64", "prlimit_64": "prlimit64"} +NEWER_SYSCALLS = { + "futex_wake": 454, "futex_wait": 455, "futex_requeue": 456, "statmount": 457, "listmount": 458, + "lsm_get_self_attr": 459, "lsm_set_self_attr": 460, "lsm_list_modules": 461, + "mseal": 462, "setxattrat": 463, "getxattrat": 464, "listxattrat": 465, "removexattrat": 466, +} +OLDEST_HEADERS_LAST_SYSCALL = 453 +HARNESS_SECONDS = 120 + +PRELUDE = r""" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace fextl { +template using vector = std::vector; +template using list = std::list; +template using unordered_map = std::unordered_map; +using std::make_unique; +} +namespace FEXCore { +namespace Utils { constexpr uint64_t FEX_PAGE_SIZE = 4096; } +constexpr uint64_t AlignUp(uint64_t V, uint64_t A) { return (V + A - 1) & ~(A - 1); } +namespace Allocator { inline uint64_t GetHostVABits() { return 39; } } +} +""" + +STUBS = r""" +static int MunmapFailures; +static int TestMunmap(void* Address, size_t Size) { + if (MunmapFailures > 0) { + --MunmapFailures; + errno = ENOMEM; + return -1; + } + return munmap(Address, Size); +} +#define munmap TestMunmap +static int SendCalls; +static int SendFailures; +static size_t SendLimit = ~size_t {}; +static int SentSocket = -1; +static size_t SentLengths[8]; +static struct iovec* GrowAfterSend; +static void* UnmapAfterSend; +static bool PassSend; +static int DupFailures; +static int TestSendmmsg(int Socket, struct mmsghdr* Messages, unsigned int Count, int Flags) { + if (PassSend) { + return sendmmsg(Socket, Messages, Count, Flags); + } + SentSocket = Socket; + if (Count != 1 || SendFailures > 0) { + SendFailures -= SendFailures > 0; + errno = EAGAIN; + return -1; + } + size_t Length = 0; + for (size_t i = 0; i < Messages[0].msg_hdr.msg_iovlen; ++i) { + Length += Messages[0].msg_hdr.msg_iov[i].iov_len; + } + Length = std::min(Length, SendLimit); + SentLengths[SendCalls++ & 7] = Length; + Messages[0].msg_len = Length; + if (GrowAfterSend) { + GrowAfterSend->iov_len = 64; + } + if (UnmapAfterSend) { + munmap(UnmapAfterSend, 4096); + UnmapAfterSend = nullptr; + } + return 1; +} +#define sendmmsg TestSendmmsg +static int TestFcntl(int FD, int Command, int Argument = 0) { + if (Command == F_DUPFD_CLOEXEC && DupFailures > 0) { + --DupFailures; + errno = EMFILE; + return -1; + } + return fcntl(FD, Command, Argument); +} +#define fcntl TestFcntl +static int ProtectCalls; +static int TestMprotect(void* Address, size_t Size, int Prot) { + ++ProtectCalls; + return mprotect(Address, Size, Prot); +} +#define mprotect TestMprotect +static uint64_t AioDestroyed; +static std::function AioDestroyHook; +static int AioReaps; +static uint64_t AioReapArgs[7]; +static std::function AioReapHook; +template static uint64_t SyscallWord(T Value) { + if constexpr (std::is_null_pointer_v) { + return 0; + } else if constexpr (std::is_pointer_v) { + return reinterpret_cast(Value); + } else { + return static_cast(Value); + } +} +template static long TestSyscall(long Number, T... Args) { + const uint64_t Words[] = {0, SyscallWord(Args)...}; + if (Number == SYS_io_getevents || Number == SYS_io_pgetevents) { + ++AioReaps; + std::copy_n(Words, std::min(std::size(Words), 7), AioReapArgs); + AioReapArgs[0] = Number; + if (AioReapHook) { + return AioReapHook(Words); + } + errno = EINTR; + return -1; + } + if (Number == SYS_io_destroy) { + AioDestroyed = Words[1]; + if (AioDestroyHook) { + AioDestroyHook(Words[1]); + } + errno = EINVAL; + return -1; + } + return syscall(Number, Args...); +} +#define syscall TestSyscall +namespace FEXCore { +template class LockType = std::unique_lock, typename MutexType> +inline auto MaskSignalsAndLockMutex(MutexType& Mutex, uint64_t = ~0ULL) { return LockType {Mutex}; } +} +namespace ArchHelpers::Context { +inline uint64_t GetArmReg(void* UContext, uint32_t Reg) { return static_cast(UContext)[Reg]; } +inline void SetArmReg(void* UContext, uint32_t Reg, uint64_t Value) { static_cast(UContext)[Reg] = Value; } +} +namespace FEX::HLE { +struct TestVMATracking { std::shared_mutex Mutex; }; +struct TestSyscallHandler { TestVMATracking VMATracking; }; +inline TestSyscallHandler TestHandler; +inline TestSyscallHandler* _SyscallHandler = &TestHandler; +struct TestThreadObject { + struct { + struct { + bool Held; + uint32_t Deferred; + siginfo_t DeferredInfo[3]; + } Mappings; + } HighMemoryTrap; + struct { + std::vector DeferredSignalFrames; + } SignalInfo; +}; +inline TestThreadObject TestThread {}; +struct ThreadManager { + static TestThreadObject* GetCurrentThreadObject() { return &TestThread; } +}; +inline bool HasSyscallError(uint64_t Result) { return Result >= 0xFFFF'FFFF'FFFF'0001ULL; } +namespace FaultSafeUserMemAccess { +inline size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { + struct iovec Local {Dest, Size}; + struct iovec Remote {const_cast(Src), Size}; + return Size == 0 || process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0) == static_cast(Size) ? 0 : Size; +} +inline void (*BeforeUserWrite)() = nullptr; +inline size_t CopyToUser(void* Dest, const void* Src, size_t Size) { + if (auto* Hook = std::exchange(BeforeUserWrite, nullptr)) { + Hook(); + } + struct iovec Local {const_cast(Src), Size}; + struct iovec Remote {Dest, Size}; + return Size == 0 || process_vm_writev(getpid(), &Local, 1, &Remote, 1, 0) == static_cast(Size) ? 0 : Size; +} +} +namespace x64 { +ENUM +} +} +""" + +MAIN = r""" +using namespace FEX::HLE::GuestHighMemory; +namespace Sys = FEX::HLE::x64; +static void Show(const char* Name, uint64_t Value) { std::printf("%s %llx\n", Name, static_cast(Value)); } +struct TestHold { + bool Held; + uint32_t Deferred; + siginfo_t DeferredInfo[3]; +}; +static std::atomic TrapsSeen; +static std::atomic TrapCode; +static std::atomic TrapValue; +static bool ExclusiveFromAnotherThread() { + std::thread Writer([] { std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; }); + Writer.join(); + return true; +} +static void CountTrap(int, siginfo_t* Info, void*) { + ++TrapsSeen; + TrapCode = Info->si_code; + TrapValue = Info->si_value.sival_int; +} +static uint64_t Call(uint32_t Syscall, uint64_t* Args, ArgumentStorage* Storage) { return TranslateSyscallArguments(Syscall, Args, 6, Storage); } +template +static uint64_t FinishResult(uint64_t Result, Arguments* Storage) { + if constexpr (std::is_void_v) { + FinishSyscallArguments(Result, Storage); + return Result; + } else { + return FinishSyscallArguments(Result, Storage); + } +} +int main() { + alarm(HARNESS_SECONDS); + const uint64_t Page = 4096; + static bool FirstHighStoreHeld; + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { FirstHighStoreHeld = FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held; }; + const uint32_t FirstHighValue = 1; + Show("high_store_unmapped_result", CopyToGuest(0x720000000000ULL, &FirstHighValue, sizeof(FirstHighValue))); + Show("high_store_unmapped_held", FirstHighStoreHeld); + Show("high_store_unmapped_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held); + const uint64_t High = TaskTop - Page; + const uint64_t Low = 0x140000000ULL; + Show("contains_last_page", Contains(High)); + Show("contains_task_top", Contains(TaskTop)); + Show("contains_host_limit", Contains(1ULL << 39)); + Show("contains_below_limit", Contains((1ULL << 39) - Page)); + Show("claims_fixed", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + Show("claims_noreplace", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE)); + Show("claims_low", ClaimsMapping(Low, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + Show("claims_hint", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS)); + Show("claims_task_top", ClaimsMapping(TaskTop, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED)); + + auto* Backing = static_cast(mmap(nullptr, 8 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Base = reinterpret_cast(Backing); + const uint64_t Single = 0x7f0000000000ULL; + const uint64_t Split = 0x7e0000000000ULL; + const uint64_t Joined = 0x7d0000000000ULL; + AddEntry(Single, Page, Base, false, PROT_READ | PROT_WRITE); + AddEntry(Split, Page, Base + 2 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Split + Page, Page, Base + 4 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Joined, Page, Base + 5 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Joined + Page, Page, Base + 6 * Page, false, PROT_READ | PROT_WRITE); + ArgumentStorage Storage; + const int Peer = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); + + uint64_t Read[6] = {3, Single + 16, 32, 0, 0, 0}; + Show("read_result", Call(Sys::SYSCALL_x64_read, Read, &Storage)); + Show("read_buffer", Read[1] - Base); + + uint64_t Truncate[6] = {3, Single + 16, 0, 0, 0, 0}; + Show("ftruncate_result", Call(Sys::SYSCALL_x64_ftruncate, Truncate, &Storage)); + Show("ftruncate_length", Truncate[1] - Single); + + uint64_t Mapping[6] = {Single, Page, 0, 0, 0, 0}; + Show("mmap_result", Call(Sys::SYSCALL_x64_mmap, Mapping, &Storage)); + Show("mmap_address", Mapping[0] - Single); + + uint64_t Unknown[6] = {Single, Single, Single, Single, Single, Single}; + Show("unknown_result", Call(1000, Unknown, &Storage)); + Show("unknown_args", Unknown[0] - Single + Unknown[5] - Single); + + uint64_t Overrun[6] = {3, Single + Page - 8, 64, 0, 0, 0}; + Show("overrun_result", Call(Sys::SYSCALL_x64_read, Overrun, &Storage)); + + uint64_t Apart[6] = {3, Split + Page - 96, 200, 0, 0, 0}; + Show("split_result", Call(Sys::SYSCALL_x64_read, Apart, &Storage)); + + uint64_t Together[6] = {3, Joined + Page - 96, 200, 0, 0, 0}; + Show("joined_result", Call(Sys::SYSCALL_x64_read, Together, &Storage)); + Show("joined_buffer", Together[1] - Base); + + uint64_t Write[6] = {3, Split + Page - 96, 96, 0, 0, 0}; + Show("fits_result", Call(Sys::SYSCALL_x64_write, Write, &Storage)); + + uint64_t PollApart[6] = {Split + Page - 96, 25, 0, 0, 0, 0}; + Show("poll_split_result", Call(Sys::SYSCALL_x64_poll, PollApart, &Storage)); + uint64_t PollFits[6] = {Split + Page - 96, 12, 0, 0, 0, 0}; + Show("poll_fits_result", Call(Sys::SYSCALL_x64_poll, PollFits, &Storage)); + uint64_t PollJoined[6] = {Joined + Page - 96, 25, 0, 0, 0, 0}; + Show("poll_joined_result", Call(Sys::SYSCALL_x64_poll, PollJoined, &Storage)); + uint64_t PollHuge[6] = {Single, 1ULL << 61, 0, 0, 0, 0}; + Show("poll_huge_result", Call(Sys::SYSCALL_x64_poll, PollHuge, &Storage)); + uint64_t EpollApart[6] = {3, Split + Page - 96, 9, 0, 0, 0}; + Show("epoll_split_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollApart, &Storage)); + uint64_t EpollFits[6] = {3, Split + Page - 96, 8, 0, 0, 0}; + Show("epoll_fits_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollFits, &Storage)); + uint64_t SelectApart[6] = {1024, Split + Page - 64, 0, 0, 0, 0}; + Show("select_split_result", Call(Sys::SYSCALL_x64_select, SelectApart, &Storage)); + uint64_t SelectFits[6] = {512, Split + Page - 64, 0, 0, 0, 0}; + Show("select_fits_result", Call(Sys::SYSCALL_x64_select, SelectFits, &Storage)); + uint64_t SelectWide[6] = {(1ULL << 32) + 1, Single, 0, 0, 0, 0}; + Show("select_wide_result", Call(Sys::SYSCALL_x64_select, SelectWide, &Storage)); + Show("fits_buffer", Write[1] - Base); + + char LowBuffer[16]; + struct iovec Guest[2] = {{reinterpret_cast(Single + 64), 32}, {LowBuffer, sizeof(LowBuffer)}}; + uint64_t Vector[6] = {3, reinterpret_cast(Guest), 2, 0, 0, 0}; + Show("readv_result", Call(Sys::SYSCALL_x64_readv, Vector, &Storage)); + const auto* HostVector = reinterpret_cast(Vector[1]); + Show("readv_copied", HostVector != Guest); + Show("readv_high_base", reinterpret_cast(HostVector[0].iov_base) - Base); + Show("readv_low_base", HostVector[1].iov_base == LowBuffer); + Show("readv_guest_untouched", reinterpret_cast(Guest[0].iov_base) - Single); + + struct iovec LowOnly[1] = {{LowBuffer, sizeof(LowBuffer)}}; + uint64_t Plain[6] = {3, reinterpret_cast(LowOnly), 1, 0, 0, 0}; + Show("writev_result", Call(Sys::SYSCALL_x64_writev, Plain, &Storage)); + Show("writev_untouched", Plain[1] == reinterpret_cast(LowOnly)); + + struct iovec Straddle[1] = {{reinterpret_cast(Split + Page - 8), 16}}; + uint64_t Crossing[6] = {3, reinterpret_cast(Straddle), 1, 0, 0, 0}; + Show("writev_split_result", Call(Sys::SYSCALL_x64_writev, Crossing, &Storage)); + + ArgumentStorage Receive; + struct iovec Incoming[1] = {{reinterpret_cast(Single + 128), 64}}; + struct msghdr Header {}; + Header.msg_iov = Incoming; + Header.msg_iovlen = 1; + uint64_t Message[6] = {3, reinterpret_cast(&Header), 0, 0, 0, 0}; + Show("recvmsg_result", Call(Sys::SYSCALL_x64_recvmsg, Message, &Receive)); + const auto* HostHeader = reinterpret_cast(Message[1]); + Show("recvmsg_copied", HostHeader != &Header); + Show("recvmsg_base", reinterpret_cast(HostHeader->msg_iov[0].iov_base) - Base); + Receive.Message.msg_flags = MSG_TRUNC; + FinishSyscallArguments(64, &Receive); + Show("recvmsg_flags", Header.msg_flags); + Show("recvmsg_guest_iov", Header.msg_iov == Incoming); + + Show("to_guest", ToGuest(Base + 6 * Page + 8) - Joined); + Show("to_guest_low", ToGuest(Low) == Low); + + const uint32_t ExclusiveOps[] = {0xc85f7c20, 0x885ffc20, 0x085ffc20, 0x485f7c20, 0xc8027c20, 0xc802fc20, + 0x0802fc20, 0xc87f0820, 0x887f8820, 0xc8230820, 0xc8238820}; + const uint32_t OtherOps[] = {0xc8dffc20, 0xc89ffc20, 0xc8e0fc41, 0x4860fc82, 0x08207c82, 0xf8e00041, + 0xf8e08041, 0xf9400020, 0xf9000420, 0xa9000440, 0xf8bfc020}; + uint64_t Refused = 0; + for (auto Op : ExclusiveOps) { + Refused += IsExclusive(Op); + } + uint64_t Allowed = 0; + for (auto Op : OtherOps) { + Allowed += !IsExclusive(Op); + } + Show("exclusive_refused", Refused); + Show("others_allowed", Allowed); + + std::vector> Applied; + auto Record = [&](void* Host, uint64_t Size, uint32_t) { + Applied.emplace_back(reinterpret_cast(Host), Size); + return 0; + }; + Show("split_apply_result", ApplyToRegionsLocked(Split, 2 * Page, -EINVAL, Record)); + Show("split_apply_count", Applied.size()); + Show("split_apply_first", Applied[0].first - Base); + Show("split_apply_second", Applied[1].first - Base); + Show("split_apply_sizes", Applied[0].second + Applied[1].second); + Applied.clear(); + Show("gap_apply_result", ApplyToRegionsLocked(Single, 2 * Page, -EINVAL, Record)); + Show("gap_apply_count", Applied.size()); + bool Advised = false; + Show("advise_split", Advise(Split, 2 * Page, MADV_DONTNEED, &Advised)); + Show("advise_split_applied", Advised); + Show("advise_gap", Advise(Single, 2 * Page, MADV_DONTNEED, &Advised)); + Show("advise_gap_applied", Advised); + Show("advise_unaligned", Advise(Single + 8, Page, MADV_DONTNEED, &Advised)); + Show("advise_unaligned_applied", Advised); + Show("advise_zero", Advise(Single, 0, MADV_DONTNEED, &Advised)); + Show("advise_wrap", Advise(Single, UINT64_MAX - 16, MADV_DONTNEED, &Advised)); + Show("advise_wrap_applied", Advised); + Show("protect_split", Protect(Split, 2 * Page, PROT_READ | PROT_WRITE)); + Show("protect_zero", Protect(Single, 0, PROT_READ | PROT_WRITE)); + Show("protect_wrap", Protect(Single, UINT64_MAX - 16, PROT_READ | PROT_WRITE)); + + auto* Guarded = static_cast(mmap(nullptr, 3 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Guard = 0x7b0000000000ULL; + RegionView Part {}; + AddEntry(Guard, 3 * Page, reinterpret_cast(Guarded), false, PROT_READ | PROT_WRITE); + Show("guard_protect", Protect(Guard + Page, Page, PROT_READ)); + FindLocked(Guard, &Part); + Show("guard_low_size", Part.Size); + Show("guard_low_prot", Part.Prot); + FindLocked(Guard + Page, &Part); + Show("guard_mid_size", Part.Size); + Show("guard_mid_host", Part.Host - reinterpret_cast(Guarded)); + Show("guard_mid_prot", Part.Prot); + FindLocked(Guard + 2 * Page, &Part); + Show("guard_high_size", Part.Size); + Show("guard_high_prot", Part.Prot); + Show("guard_store_readonly", ExclusiveReachable(0xc8027c20, PROT_READ)); + Show("guard_load_readonly", ExclusiveReachable(0xc85f7c20, PROT_READ)); + Show("guard_store_writable", ExclusiveReachable(0xc8027c20, PROT_READ | PROT_WRITE)); + Show("guard_load_none", ExclusiveReachable(0xc85f7c20, PROT_NONE)); + Show("guard_pair_store_readonly", ExclusiveReachable(0xc8220c20, PROT_READ)); + Show("discards", DiscardsContents(MADV_DONTNEED) + DiscardsContents(MADV_FREE) + DiscardsContents(MADV_REMOVE) + + DiscardsContents(MADV_DONTNEED_LOCKED)); + Show("keeps", DiscardsContents(MADV_WILLNEED) + DiscardsContents(MADV_NORMAL) + DiscardsContents(MADV_HUGEPAGE)); + + auto* Spare = static_cast(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Retire = 0x7c0000000000ULL; + unsigned char Resident = 0; + RegionView View {}; + AddEntry(Retire, 2 * Page, reinterpret_cast(Spare), false, PROT_READ | PROT_WRITE); + MunmapFailures = 1; + Show("retire_unmap", UnmapLocked(Retire, Page)); + Show("retire_pending", RetiredCount); + Show("retire_untracked", !FindLocked(Retire, &View)); + Show("retire_host_held", mincore(Spare, Page, &Resident) == 0); + Show("retire_second", UnmapLocked(Retire + Page, Page)); + Show("retire_released", RetiredCount); + Show("retire_host_gone", mincore(Spare, Page, &Resident) != 0 && errno == ENOMEM); + Show("retire_rest_gone", mincore(Spare + Page, Page, &Resident) != 0 && errno == ENOMEM); + + auto* Kept = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Full = 0x7a0000000000ULL; + AddEntry(Full, Page, reinterpret_cast(Kept), false, PROT_READ | PROT_WRITE); + for (uint32_t i = 0; i < MaxRegions; ++i) { + Retired[i] = {0x10000000ULL + i * 2 * Page, Page}; + } + RetiredCount = MaxRegions; + MunmapFailures = MaxRegions + 1; + Show("retire_full_unmap", UnmapLocked(Full, Page)); + Show("retire_full_tracked", FindLocked(Full, &View)); + Show("retire_full_host_held", mincore(Kept, Page, &Resident) == 0); + RetiredCount = 0; + MunmapFailures = 0; + Show("retire_full_after", UnmapLocked(Full, Page)); + Show("retire_full_gone", !FindLocked(Full, &View)); + + struct { + uint64_t Host; + uint64_t Low; + uint64_t High; + uint32_t Size; + bool Valid; + } Monitor {}; + uint64_t Context[32] {}; + alignas(16) uint64_t Cell[2] = {5, 0}; + const auto CellHost = reinterpret_cast(Cell); + EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context); + Show("ldxr_value", Context[0]); + Context[0] = 9; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("stxr_status", Context[2]); + Show("stxr_memory", Cell[0]); + EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context); + Cell[0] = 11; + Context[0] = 12; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("contended_status", Context[2]); + Show("contended_memory", Cell[0]); + Context[0] = 13; + EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context); + Show("unarmed_status", Context[2]); + Show("unarmed_memory", Cell[0]); + Cell[0] = 1; + Cell[1] = 2; + EmulateExclusive(Monitor, 0xc87f0c20, CellHost, Context); + Show("ldxp_low", Context[0]); + Show("ldxp_high", Context[3]); + Context[0] = 7; + Context[3] = 8; + EmulateExclusive(Monitor, 0xc8220c20, CellHost, Context); + Show("stxp_status", Context[2]); + Show("stxp_memory", Cell[0] * 16 + Cell[1]); + Cell[0] = 0x1122334455667788ULL; + EmulateExclusive(Monitor, 0x085f7c20, CellHost, Context); + Show("ldxrb_value", Context[0]); + Context[0] = 0x1ab; + EmulateExclusive(Monitor, 0x0802fc20, CellHost, Context); + Show("stlxrb_status", Context[2]); + Show("stlxrb_memory", Cell[0]); + Show("misaligned", EmulateExclusive(Monitor, 0xc85f7c20, CellHost + 4, Context)); + + Show("writeonly_load", ExclusiveReachable(0xc85f7c20, PROT_WRITE)); + Show("writeonly_store", ExclusiveReachable(0xc8027c20, PROT_WRITE)); + Show("writeonly_pair_store", ExclusiveReachable(0xc8220c20, PROT_WRITE)); + Show("exec_only_load", ExclusiveReachable(0xc85f7c20, PROT_EXEC)); + + const uint32_t GuardEntries = Count.load(); + Show("guard_restore", Protect(Guard + Page, Page, PROT_READ | PROT_WRITE)); + FindLocked(Guard + Page, &Part); + Show("guard_restored_guest", Part.Guest - Guard); + Show("guard_restored_size", Part.Size); + Show("guard_restored_merged", GuardEntries - Count.load()); + Show("split_hosts_kept_apart", FindLocked(Split + Page, &Part) && Part.Guest == Split + Page && Part.Size == Page); + + const uint64_t Toggles = 1100; + auto* Striped = static_cast(mmap(nullptr, Toggles * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Stripe = 0x790000000000ULL; + AddEntry(Stripe, Toggles * Page, reinterpret_cast(Striped), false, PROT_READ | PROT_WRITE); + const uint32_t StripeEntries = Count.load(); + uint64_t ToggleFailures = 0; + for (uint64_t i = 0; i < Toggles; ++i) { + ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ) != 0; + ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ | PROT_WRITE) != 0; + } + Show("toggle_failures", ToggleFailures); + Show("toggle_entries", Count.load() - StripeEntries); + FindLocked(Stripe, &Part); + Show("toggle_pages", Part.Size / Page); + + uint64_t SemApart[6] = {1, Split + Page - 12, 3, 0, 0, 0}; + Show("semop_split_result", Call(Sys::SYSCALL_x64_semop, SemApart, &Storage)); + uint64_t SemFits[6] = {1, Split + Page - 12, 2, 0, 0, 0}; + Show("semop_fits_result", Call(Sys::SYSCALL_x64_semop, SemFits, &Storage)); + uint64_t GroupsApart[6] = {4, Split + Page - 12, 0, 0, 0, 0}; + Show("getgroups_split_result", Call(Sys::SYSCALL_x64_getgroups, GroupsApart, &Storage)); + uint64_t EventsApart[6] = {1, 1, 2, Split + Page - 32, 0, 0}; + Show("io_getevents_split_result", Call(Sys::SYSCALL_x64_io_getevents, EventsApart, &Storage)); + uint64_t EventsFit[6] = {1, 1, 1, Split + Page - 32, 0, 0}; + Show("io_getevents_fits_result", Call(Sys::SYSCALL_x64_io_getevents, EventsFit, &Storage)); + uint64_t PagesApart[6] = {0, 2, Split + Page - 8, 0, 0, 0}; + Show("move_pages_split_result", Call(Sys::SYSCALL_x64_move_pages, PagesApart, &Storage)); + + char BatchLow[16]; + struct iovec SendVectors[2] = {{reinterpret_cast(Single + 256), 32}, {BatchLow, sizeof(BatchLow)}}; + struct mmsghdr Outgoing[2] {}; + Outgoing[0].msg_hdr.msg_iov = &SendVectors[0]; + Outgoing[0].msg_hdr.msg_iovlen = 1; + Outgoing[1].msg_hdr.msg_iov = &SendVectors[1]; + Outgoing[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage SendBatch; + uint64_t Send[6] = {static_cast(Peer), reinterpret_cast(Outgoing), 2, 0, 0, 0}; + Show("sendmmsg_result", Call(Sys::SYSCALL_x64_sendmmsg, Send, &SendBatch)); + auto* HostSend = reinterpret_cast(Send[1]); + Show("sendmmsg_copied", HostSend != Outgoing); + Show("sendmmsg_high_base", reinterpret_cast(HostSend[0].msg_hdr.msg_iov[0].iov_base) - Base); + Show("sendmmsg_low_base", HostSend[1].msg_hdr.msg_iov[0].iov_base == BatchLow); + Show("sendmmsg_guest_untouched", reinterpret_cast(Outgoing[0].msg_hdr.msg_iov[0].iov_base) - Single); + Show("sendmmsg_submitted", Send[2]); + SendCalls = 0; + HostSend[0].msg_len = 32; + Show("sendmmsg_finish", FinishResult(1, &SendBatch)); + Show("sendmmsg_later_sends", SendCalls); + Show("sendmmsg_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len); + Outgoing[0].msg_len = 0; + Outgoing[1].msg_len = 0; + ArgumentStorage DeclinedBatch; + uint64_t Declined[6] = {static_cast(Peer), reinterpret_cast(Outgoing), 2, 0, 0, 0}; + Call(Sys::SYSCALL_x64_sendmmsg, Declined, &DeclinedBatch); + reinterpret_cast(Declined[1])[0].msg_len = 32; + SendFailures = 1; + Show("sendmmsg_refused_finish", FinishResult(1, &DeclinedBatch)); + Show("sendmmsg_refused_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len); + + struct iovec ReceiveVectors[2] = {{reinterpret_cast(Single + 512), 64}, {BatchLow, sizeof(BatchLow)}}; + struct mmsghdr Arriving[2] {}; + Arriving[0].msg_hdr.msg_iov = &ReceiveVectors[0]; + Arriving[0].msg_hdr.msg_iovlen = 1; + Arriving[1].msg_hdr.msg_iov = &ReceiveVectors[1]; + Arriving[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage ReceiveBatch; + uint64_t Batch[6] = {3, reinterpret_cast(Arriving), 2, 0, 0, 0}; + Show("recvmmsg_result", Call(Sys::SYSCALL_x64_recvmmsg, Batch, &ReceiveBatch)); + auto* HostReceive = reinterpret_cast(Batch[1]); + Show("recvmmsg_copied", HostReceive != Arriving); + Show("recvmmsg_base", reinterpret_cast(HostReceive[0].msg_hdr.msg_iov[0].iov_base) - Base); + HostReceive[0].msg_len = 40; + HostReceive[0].msg_hdr.msg_flags = MSG_TRUNC; + HostReceive[1].msg_len = 5; + FinishSyscallArguments(1, &ReceiveBatch); + Show("recvmmsg_first_length", Arriving[0].msg_len); + Show("recvmmsg_first_flags", Arriving[0].msg_hdr.msg_flags); + Show("recvmmsg_second_length", Arriving[1].msg_len); + Show("recvmmsg_guest_iov", Arriving[0].msg_hdr.msg_iov == &ReceiveVectors[0]); + + std::vector Many(1100); + Many[0].msg_hdr.msg_iov = &ReceiveVectors[0]; + Many[0].msg_hdr.msg_iovlen = 1; + ArgumentStorage ManyBatch; + uint64_t Wide[6] = {3, reinterpret_cast(Many.data()), Many.size(), 0, 0, 0}; + Show("recvmmsg_wide_result", Call(Sys::SYSCALL_x64_recvmmsg, Wide, &ManyBatch)); + Show("recvmmsg_wide_count", Wide[2]); + uint64_t BatchApart[6] = {3, Split + Page - 64, 2, 0, 0, 0}; + Show("sendmmsg_split_result", Call(Sys::SYSCALL_x64_sendmmsg, BatchApart, &ManyBatch)); + + ArgumentStorage Sizes; + uint64_t StatSplit[6] = {3, Split + Page - 64, 0, 0, 0, 0}; + Show("fstat_split_result", Call(Sys::SYSCALL_x64_fstat, StatSplit, &Sizes)); + uint64_t StatEdge[6] = {3, Single + Page - 144, 0, 0, 0, 0}; + Show("fstat_edge_result", Call(Sys::SYSCALL_x64_fstat, StatEdge, &Sizes)); + uint64_t NameEdge[6] = {Single + Page - 390, 0, 0, 0, 0, 0}; + Show("uname_edge_result", Call(Sys::SYSCALL_x64_uname, NameEdge, &Sizes)); + uint64_t NameOver[6] = {Single + Page - 389, 0, 0, 0, 0, 0}; + Show("uname_over_result", Call(Sys::SYSCALL_x64_uname, NameOver, &Sizes)); + uint64_t Action[6] = {10, Single + Page - 32, 0, 8, 0, 0}; + Show("sigaction_edge_result", Call(Sys::SYSCALL_x64_rt_sigaction, Action, &Sizes)); + uint64_t ActionOver[6] = {10, Single + Page - 24, 0, 8, 0, 0}; + Show("sigaction_over_result", Call(Sys::SYSCALL_x64_rt_sigaction, ActionOver, &Sizes)); + uint64_t MaskApart[6] = {0, Split + Page - 4, 0, 8, 0, 0}; + Show("sigprocmask_split_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskApart, &Sizes)); + uint64_t MaskFits[6] = {0, Split + Page - 8, 0, 8, 0, 0}; + Show("sigprocmask_fits_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskFits, &Sizes)); + uint64_t Sleep[6] = {Single + Page - 16, 0, 0, 0, 0, 0}; + Show("nanosleep_edge_result", Call(Sys::SYSCALL_x64_nanosleep, Sleep, &Sizes)); + uint64_t SleepOver[6] = {Single + Page - 8, 0, 0, 0, 0, 0}; + Show("nanosleep_over_result", Call(Sys::SYSCALL_x64_nanosleep, SleepOver, &Sizes)); + uint64_t Residency[6] = {Low, 3 * Page, Split + Page - 2, 0, 0, 0}; + Show("mincore_split_result", Call(Sys::SYSCALL_x64_mincore, Residency, &Sizes)); + uint64_t ResidencyFits[6] = {Low, 2 * Page, Split + Page - 2, 0, 0, 0}; + Show("mincore_fits_result", Call(Sys::SYSCALL_x64_mincore, ResidencyFits, &Sizes)); + uint64_t Lock[6] = {3, F_GETLK, Split + Page - 16, 0, 0, 0}; + Show("fcntl_lock_split_result", Call(Sys::SYSCALL_x64_fcntl, Lock, &Sizes)); + uint64_t LockFits[6] = {3, F_GETLK, Single + Page - 32, 0, 0, 0}; + Show("fcntl_lock_fits_result", Call(Sys::SYSCALL_x64_fcntl, LockFits, &Sizes)); + Show("fcntl_lock_fits_buffer", LockFits[2] - Base); + + std::memcpy(Backing + 3 * Page - 2, "ab", 2); + std::memcpy(Backing + 4 * Page, "cd", 3); + uint64_t PathApart[6] = {Split + Page - 2, 0, 0, 0, 0, 0}; + Show("open_split_result", Call(Sys::SYSCALL_x64_open, PathApart, &Sizes)); + std::memcpy(Backing + 6 * Page - 2, "ab", 2); + std::memcpy(Backing + 6 * Page, "cd", 3); + uint64_t PathJoined[6] = {Joined + Page - 2, 0, 0, 0, 0, 0}; + Show("open_joined_result", Call(Sys::SYSCALL_x64_open, PathJoined, &Sizes)); + Show("open_joined_path", PathJoined[0] - Base); + std::memcpy(Backing + 3000, "dir/file", 9); + uint64_t PathInside[6] = {static_cast(AT_FDCWD), Single + 3000, 0, 0, 0, 0}; + Show("openat_inside_result", Call(Sys::SYSCALL_x64_openat, PathInside, &Sizes)); + Show("openat_inside_path", PathInside[1] - Base); + std::memset(Backing + Page - 8, 'x', 8); + uint64_t PathOpen[6] = {Single + Page - 8, 0, 0, 0, 0, 0}; + Show("open_unterminated_result", Call(Sys::SYSCALL_x64_open, PathOpen, &Sizes)); + uint64_t RenameApart[6] = {Single + 3000, Split + Page - 2, 0, 0, 0, 0}; + Show("rename_split_result", Call(Sys::SYSCALL_x64_rename, RenameApart, &Sizes)); + + socklen_t AddressLength = 16; + uint64_t Accept[6] = {3, Split + Page - 16, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_fits_result", Call(Sys::SYSCALL_x64_accept, Accept, &Sizes)); + AddressLength = 32; + uint64_t AcceptOver[6] = {3, Split + Page - 16, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_split_result", Call(Sys::SYSCALL_x64_accept, AcceptOver, &Sizes)); + AddressLength = 4096; + uint64_t AcceptCapped[6] = {3, Single + Page - 128, reinterpret_cast(&AddressLength), 0, 0, 0}; + Show("accept_capped_result", Call(Sys::SYSCALL_x64_accept, AcceptCapped, &Sizes)); + const uint32_t HighLength = 32; + std::memcpy(Backing + 40, &HighLength, sizeof(HighLength)); + uint64_t AcceptHigh[6] = {3, Split + Page - 16, Single + 40, 0, 0, 0}; + Show("accept_high_length_result", Call(Sys::SYSCALL_x64_accept, AcceptHigh, &Sizes)); + uint32_t OptionLength = 8; + uint64_t Option[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast(&OptionLength), 0}; + Show("getsockopt_split_result", Call(Sys::SYSCALL_x64_getsockopt, Option, &Sizes)); + OptionLength = 4; + uint64_t OptionFits[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast(&OptionLength), 0}; + Show("getsockopt_fits_result", Call(Sys::SYSCALL_x64_getsockopt, OptionFits, &Sizes)); + + uint64_t QueueFits[6] = {1, Split + Page - 16, 8, 0, 0, 0}; + Show("msgsnd_fits_result", Call(Sys::SYSCALL_x64_msgsnd, QueueFits, &Sizes)); + uint64_t QueueOver[6] = {1, Split + Page - 16, 9, 0, 0, 0}; + Show("msgsnd_split_result", Call(Sys::SYSCALL_x64_msgsnd, QueueOver, &Sizes)); + uint64_t QueueReceive[6] = {1, Split + Page - 16, 9, 0, 0, 0}; + Show("msgrcv_split_result", Call(Sys::SYSCALL_x64_msgrcv, QueueReceive, &Sizes)); + uint64_t QueueHuge[6] = {1, Single, 1ULL << 40, 0, 0, 0}; + Show("msgsnd_huge_result", Call(Sys::SYSCALL_x64_msgsnd, QueueHuge, &Sizes)); + + std::memcpy(Backing + 100, "x", 2); + uint64_t ValidFailures = 0; + uint64_t ValidTranslated = 0; + uint64_t StatValid[6] = {Single + 100, Single + 1024, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_stat, StatValid, &Sizes) != 0; + ValidTranslated += StatValid[0] == Base + 100 && StatValid[1] == Base + 1024; + uint64_t StatxValid[6] = {static_cast(AT_FDCWD), Single + 100, 0, 0x7ff, Single + 1536, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_statx, StatxValid, &Sizes) != 0; + ValidTranslated += StatxValid[1] == Base + 100 && StatxValid[4] == Base + 1536; + uint64_t ClockValid[6] = {1, Single + 2048, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_clock_gettime, ClockValid, &Sizes) != 0; + ValidTranslated += ClockValid[1] == Base + 2048; + uint64_t WaitValid[6] = {static_cast(-1), Single + 64, 0, Single + 512, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_wait4, WaitValid, &Sizes) != 0; + ValidTranslated += WaitValid[1] == Base + 64 && WaitValid[3] == Base + 512; + uint64_t PipeValid[6] = {Single + 8, 0, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_pipe2, PipeValid, &Sizes) != 0; + ValidTranslated += PipeValid[0] == Base + 8; + uint64_t LimitValid[6] = {0, 7, Single + 2560, Single + 2600, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_prlimit_64, LimitValid, &Sizes) != 0; + ValidTranslated += LimitValid[2] == Base + 2560 && LimitValid[3] == Base + 2600; + uint64_t TimerValid[6] = {1, 0, Single + 2304, Single + 2336, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_timer_settime, TimerValid, &Sizes) != 0; + ValidTranslated += TimerValid[2] == Base + 2304 && TimerValid[3] == Base + 2336; + AddressLength = 16; + uint64_t AcceptValid[6] = {3, Single + 256, reinterpret_cast(&AddressLength), 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_accept, AcceptValid, &Sizes) != 0; + ValidTranslated += AcceptValid[1] == Base + 256; + uint64_t NameValid[6] = {Single, 0, 0, 0, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_uname, NameValid, &Sizes) != 0; + ValidTranslated += NameValid[0] == Base; + uint64_t SignalValid[6] = {10, Single + 2800, Single + 2900, 8, 0, 0}; + ValidFailures += Call(Sys::SYSCALL_x64_rt_sigaction, SignalValid, &Sizes) != 0; + ValidTranslated += SignalValid[1] == Base + 2800 && SignalValid[2] == Base + 2900; + Show("single_valid_failures", ValidFailures); + Show("single_valid_translated", ValidTranslated); + + struct TestIocb { + uint64_t Data; + uint32_t Key; + int32_t ReadWriteFlags; + uint16_t Opcode; + int16_t Priority; + uint32_t File; + uint64_t Buffer; + uint64_t Bytes; + int64_t Offset; + uint64_t Reserved; + uint32_t Flags; + uint32_t ResultFile; + }; + TestIocb ReadBlock {}; + ReadBlock.Data = 0x77; + ReadBlock.Key = 5; + ReadBlock.Buffer = Single + 768; + ReadBlock.Bytes = 64; + char VectorLow[16]; + struct iovec Scatter[2] = {{reinterpret_cast(Single + 800), 16}, {VectorLow, sizeof(VectorLow)}}; + TestIocb Vectored {}; + Vectored.Opcode = 7; + Vectored.Buffer = reinterpret_cast(Scatter); + Vectored.Bytes = 2; + TestIocb ReadExpected = ReadBlock; + const TestIocb VectoredExpected = Vectored; + auto GuestBlocksUntouched = [&] { + return std::memcmp(&ReadBlock, &ReadExpected, sizeof(TestIocb)) == 0 && std::memcmp(&Vectored, &VectoredExpected, sizeof(TestIocb)) == 0; + }; + struct TestEvent { + uint64_t Data; + uint64_t Object; + int64_t Result; + int64_t Result2; + }; + auto Deliver = [](const uint64_t* Args, const void* Events, size_t Size) { + static_cast(FEX::HLE::FaultSafeUserMemAccess::CopyToUser(reinterpret_cast(Args[3]), Events, Size)); + }; + uint64_t Submitted[2] = {reinterpret_cast(&ReadBlock), reinterpret_cast(&Vectored)}; + ArgumentStorage Submit; + uint64_t SubmitArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + const auto CopiesBefore = IoCopyCount.load(); + ProtectCalls = 0; + Show("io_submit_result", Call(Sys::SYSCALL_x64_io_submit, SubmitArgs, &Submit)); + Show("io_submit_count", SubmitArgs[1]); + Show("io_submit_list_copied", SubmitArgs[2] != reinterpret_cast(Submitted)); + const auto* Sent = reinterpret_cast(SubmitArgs[2]); + const auto* SentRead = reinterpret_cast(Sent[0]); + const auto* SentVector = reinterpret_cast(Sent[1]); + Show("io_submit_private_blocks", SentRead != &ReadBlock && SentVector != &Vectored); + Show("io_submit_buffer", SentRead->Buffer - Base); + Show("io_submit_fields_kept", SentRead->Data == 0x77 && SentRead->Bytes == 64 && SentRead->Key == 5); + const auto* HostScatter = reinterpret_cast(SentVector->Buffer); + Show("io_submit_vector_copied", HostScatter != Scatter); + Show("io_submit_vector_base", reinterpret_cast(HostScatter[0].iov_base) - Base); + Show("io_submit_vector_low", HostScatter[1].iov_base == VectorLow); + Show("io_submit_guest_key", ReadBlock.Key); + Show("io_submit_guest_untouched", GuestBlocksUntouched()); + Show("io_submit_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(2, &Submit); + Show("io_submit_accepted_key", ReadBlock.Key); + ReadExpected.Key = 0; + Show("io_submit_copies_kept", IoCopyCount.load() - CopiesBefore); + Show("io_submit_finished_untouched", GuestBlocksUntouched()); + + TestEvent CancelEvent {}; + ArgumentStorage Cancel; + uint64_t CancelArgs[6] = {1, reinterpret_cast(&ReadBlock), reinterpret_cast(&CancelEvent), 0, 0, 0}; + Show("io_cancel_result", Call(Sys::SYSCALL_x64_io_cancel, CancelArgs, &Cancel)); + Show("io_cancel_private", CancelArgs[1] == Sent[0]); + ArgumentStorage CancelElsewhere; + uint64_t ElsewhereArgs[6] = {2, reinterpret_cast(&ReadBlock), reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, ElsewhereArgs, &CancelElsewhere); + Show("io_cancel_other_context", ElsewhereArgs[1] == reinterpret_cast(&ReadBlock)); + + TestEvent Reaped[3] = {{0x77, Sent[0], 64, 0}, {0, Sent[1], 16, 0}, {8, Base + 1536, 16, 0}}; + ArgumentStorage ReapCopies; + uint64_t ReapCopiesArgs[6] = {1, 1, 3, reinterpret_cast(Reaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReapCopiesArgs, &ReapCopies); + Show("io_getevents_host_buffer", ReapCopiesArgs[3] == reinterpret_cast(ReapCopies.EventBuffer.data())); + Deliver(ReapCopiesArgs, Reaped, sizeof(Reaped)); + FinishSyscallArguments(3, &ReapCopies); + Show("io_getevents_copy_object", Reaped[0].Object == reinterpret_cast(&ReadBlock)); + Show("io_getevents_vector_object", Reaped[1].Object == reinterpret_cast(&Vectored)); + Show("io_getevents_alias_object", Reaped[2].Object - Single); + Show("io_getevents_copies_freed", IoCopyCount.load() - CopiesBefore); + Show("io_getevents_untouched", GuestBlocksUntouched()); + Show("io_submit_protect_calls", ProtectCalls); + + auto* HighBlock = reinterpret_cast(Backing + 1536); + *HighBlock = {}; + HighBlock->Opcode = 1; + HighBlock->Buffer = reinterpret_cast(LowBuffer); + HighBlock->Bytes = sizeof(LowBuffer); + uint64_t HighList[1] = {Single + 1536}; + ArgumentStorage HighSubmit; + uint64_t HighArgs[6] = {1, 1, reinterpret_cast(HighList), 0, 0, 0}; + Show("io_submit_high_result", Call(Sys::SYSCALL_x64_io_submit, HighArgs, &HighSubmit)); + Show("io_submit_high_copied", HighArgs[2] != reinterpret_cast(HighList)); + Show("io_submit_high_block", reinterpret_cast(HighArgs[2])[0] - Base); + Show("io_submit_high_guest_list", HighList[0] - Single); + Show("io_submit_high_uncopied", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(1, &HighSubmit); + + TestIocb BadBlock {}; + BadBlock.Buffer = Split + Page - 8; + BadBlock.Bytes = 16; + uint64_t Mixed[2] = {reinterpret_cast(&ReadBlock), reinterpret_cast(&BadBlock)}; + ArgumentStorage Partial; + uint64_t PartialArgs[6] = {1, 2, reinterpret_cast(Mixed), 0, 0, 0}; + Show("io_submit_partial_result", Call(Sys::SYSCALL_x64_io_submit, PartialArgs, &Partial)); + Show("io_submit_partial_count", PartialArgs[1]); + Show("io_submit_partial_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(static_cast(-EFAULT), &Partial); + Show("io_submit_partial_released", IoCopyCount.load() - CopiesBefore); + Show("io_submit_partial_untouched", GuestBlocksUntouched()); + ArgumentStorage Truncated; + uint64_t TruncatedArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, TruncatedArgs, &Truncated); + const uint64_t TruncatedFirst = reinterpret_cast(TruncatedArgs[2])[0]; + FinishSyscallArguments(1, &Truncated); + Show("io_submit_short_kept", IoCopyCount.load() - CopiesBefore); + Show("io_submit_short_first_live", FindIoCopyLocked(TruncatedFirst) != nullptr); + ArgumentStorage OtherContext; + uint64_t OtherContextArgs[6] = {3, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, OtherContextArgs, &OtherContext); + FinishSyscallArguments(1, &OtherContext); + ArgumentStorage Destroy; + uint64_t DestroyArgs[6] = {1, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyArgs, &Destroy); + FinishSyscallArguments(0, &Destroy); + Show("io_destroy_released", IoCopyCount.load() - CopiesBefore); + ArgumentStorage DestroyFailed; + uint64_t DestroyFailedArgs[6] = {3, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyFailedArgs, &DestroyFailed); + FinishSyscallArguments(static_cast(-EINVAL), &DestroyFailed); + Show("io_destroy_failed_kept", IoCopyCount.load() - CopiesBefore); + ArgumentStorage DestroyOther; + uint64_t DestroyOtherArgs[6] = {3, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DestroyOtherArgs, &DestroyOther); + FinishSyscallArguments(0, &DestroyOther); + Show("io_destroy_other_released", IoCopyCount.load() - CopiesBefore); + uint64_t OnlyCrossing[1] = {reinterpret_cast(&BadBlock)}; + ArgumentStorage FirstBad; + uint64_t FirstBadArgs[6] = {1, 1, reinterpret_cast(OnlyCrossing), 0, 0, 0}; + Show("io_submit_first_bad_result", Call(Sys::SYSCALL_x64_io_submit, FirstBadArgs, &FirstBad)); + FinishSyscallArguments(static_cast(-EFAULT), &FirstBad); + Show("io_submit_first_bad_copies", IoCopyCount.load() - CopiesBefore); + TestIocb KeyFirst = ReadBlock; + KeyFirst.Key = 5; + TestIocb KeySecond = ReadBlock; + KeySecond.Key = 6; + uint64_t KeyList[2] = {reinterpret_cast(&KeyFirst), reinterpret_cast(&KeySecond)}; + ArgumentStorage KeySubmit; + uint64_t KeySubmitArgs[6] = {4, 2, reinterpret_cast(KeyList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, KeySubmitArgs, &KeySubmit); + const uint64_t KeyFirstSent = reinterpret_cast(KeySubmitArgs[2])[0]; + Show("io_submit_keys_prepared", KeyFirst.Key == 5 && KeySecond.Key == 6); + TestEvent KeyCancelEvent {}; + ArgumentStorage EarlyCancel; + uint64_t EarlyCancelArgs[6] = {4, reinterpret_cast(&KeyFirst), reinterpret_cast(&KeyCancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, EarlyCancelArgs, &EarlyCancel); + Show("io_cancel_keyed_native", EarlyCancelArgs[1] == reinterpret_cast(&KeyFirst)); + FinishSyscallArguments(1, &KeySubmit); + Show("io_submit_key_accepted", KeyFirst.Key); + Show("io_submit_key_after_rejected", KeySecond.Key); + Show("io_submit_key_rejected_released", IoCopyCount.load() - CopiesBefore); + ArgumentStorage LateCancel; + uint64_t LateCancelArgs[6] = {4, reinterpret_cast(&KeyFirst), reinterpret_cast(&KeyCancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, LateCancelArgs, &LateCancel); + Show("io_cancel_accepted_private", LateCancelArgs[1] == KeyFirstSent); + TestIocb KeyA = ReadBlock; + KeyA.Key = 7; + TestIocb KeyB = ReadBlock; + KeyB.Key = 8; + TestIocb KeyC = ReadBlock; + KeyC.Key = 9; + uint64_t KeyTriple[3] = {reinterpret_cast(&KeyA), reinterpret_cast(&KeyB), reinterpret_cast(&KeyC)}; + ArgumentStorage RejectSubmit; + uint64_t RejectSubmitArgs[6] = {6, 3, reinterpret_cast(KeyTriple), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, RejectSubmitArgs, &RejectSubmit); + const auto* RejectSent = reinterpret_cast(RejectSubmitArgs[2]); + reinterpret_cast(RejectSent[0])->Key = 0; + reinterpret_cast(RejectSent[1])->Key = 0; + FinishSyscallArguments(1, &RejectSubmit); + Show("io_submit_rejected_key_cleared", KeyA.Key == 0 && KeyB.Key == 0); + Show("io_submit_unreached_key", KeyC.Key); + TestIocb KeyD = ReadBlock; + KeyD.Key = 3; + uint64_t KeySingle[1] = {reinterpret_cast(&KeyD)}; + ArgumentStorage FirstRejected; + uint64_t FirstRejectedArgs[6] = {6, 1, reinterpret_cast(KeySingle), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, FirstRejectedArgs, &FirstRejected); + reinterpret_cast(reinterpret_cast(FirstRejectedArgs[2])[0])->Key = 0; + FinishSyscallArguments(static_cast(-EBADF), &FirstRejected); + Show("io_submit_first_rejected_key", KeyD.Key); + ArgumentStorage RejectDestroy; + uint64_t RejectDestroyArgs[6] = {6, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, RejectDestroyArgs, &RejectDestroy); + FinishSyscallArguments(0, &RejectDestroy); + Show("io_submit_rejected_released", IoCopyCount.load() - CopiesBefore); + auto* SealedEvents = static_cast(mmap(nullptr, Page, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + int64_t NoWait[2] = {0, 0}; + const uint64_t Immediate = reinterpret_cast(NoWait); + ArgumentStorage UnwritableReap; + uint64_t UnwritableReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, UnwritableReapArgs, &UnwritableReap); + Show("io_getevents_unwritable_staged", UnwritableReapArgs[3] == reinterpret_cast(UnwritableReap.EventBuffer.data()) && + UnwritableReapArgs[2] == 1 && UnwritableReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t)); + Show("io_getevents_unwritable_result", FinishSyscallArguments(static_cast(-EFAULT), &UnwritableReap)); + Show("io_getevents_unwritable_kept", IoCopyCount.load() - CopiesBefore); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage SealedReap; + uint64_t SealedReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SealedReapArgs, &SealedReap); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent SealedEvent {0x77, KeyFirstSent, 64, 0}; + Deliver(SealedReapArgs, &SealedEvent, sizeof(SealedEvent)); + Show("io_getevents_sealed_result", FinishSyscallArguments(1, &SealedReap)); + Show("io_getevents_sealed_released", IoCopyCount.load() - CopiesBefore); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage StashedReap; + uint64_t StashedReapArgs[6] = {4, 1, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StashedReapArgs, &StashedReap); + Show("io_getevents_stash_nonblocking", StashedReapArgs[1] == 0 && StashedReapArgs[2] == 1 && + StashedReapArgs[3] == reinterpret_cast(StashedReap.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t))); + Show("io_getevents_stash_result", FinishSyscallArguments(0, &StashedReap)); + Show("io_getevents_stash_event", SealedEvents[0].Object == reinterpret_cast(&KeyFirst) && SealedEvents[0].Data == 0x77); + ArgumentStorage DrainedReap; + uint64_t DrainedReapArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DrainedReapArgs, &DrainedReap); + Show("io_getevents_stash_once", DrainedReapArgs[1] == 1 && DrainedReapArgs[2] == 1 && FinishSyscallArguments(0, &DrainedReap) == 0); + auto FailReap = [&](uint64_t Context, const TestEvent& Event) { + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Failed; + uint64_t FailedArgs[6] = {Context, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FailedArgs, &Failed); + mprotect(SealedEvents, Page, PROT_READ); + Deliver(FailedArgs, &Event, sizeof(Event)); + const auto Result = FinishSyscallArguments(1, &Failed); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + return Result; + }; + Show("io_getevents_stash_ready_failed", FailReap(4, {0x57, reinterpret_cast(&KeyD), 1, 0})); + ArgumentStorage ReadyReap; + uint64_t ReadyReapArgs[6] = {4, 1, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReadyReapArgs, &ReadyReap); + const TestEvent Ready {0x58, reinterpret_cast(&KeyC), 1, 0}; + Deliver(ReadyReapArgs, &Ready, sizeof(Ready)); + Show("io_getevents_stash_ready_result", FinishSyscallArguments(1, &ReadyReap)); + Show("io_getevents_stash_ready_order", SealedEvents[0].Data == 0x57 && SealedEvents[1].Data == 0x58 && + SealedEvents[1].Object == reinterpret_cast(&KeyC)); + Show("io_getevents_stash_plain_failed", FailReap(4, {0x55, reinterpret_cast(&KeyD), 1, 0})); + ArgumentStorage TopUp; + uint64_t TopUpArgs[6] = {4, 2, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, TopUpArgs, &TopUp); + Show("io_getevents_stash_topup_args", TopUpArgs[1] == 1 && TopUpArgs[2] == 2 && + TopUpArgs[3] == reinterpret_cast(TopUp.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t))); + const TestEvent Fresh {0x66, reinterpret_cast(&KeyA), 2, 0}; + Deliver(TopUpArgs, &Fresh, sizeof(Fresh)); + Show("io_getevents_stash_topup_result", FinishSyscallArguments(1, &TopUp)); + Show("io_getevents_stash_topup_order", SealedEvents[0].Data == 0x55 && SealedEvents[0].Object == reinterpret_cast(&KeyD) && + SealedEvents[1].Data == 0x66 && SealedEvents[1].Object == reinterpret_cast(&KeyA)); + FailReap(4, {0x44, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage FaultedRetry; + uint64_t FaultedRetryArgs[6] = {4, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FaultedRetryArgs, &FaultedRetry); + Show("io_getevents_stash_fault_result", FinishSyscallArguments(static_cast(-EFAULT), &FaultedRetry)); + ArgumentStorage Interrupted; + uint64_t InterruptedArgs[6] = {4, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InterruptedArgs, &Interrupted); + Show("io_getevents_stash_kept_after_fault", InterruptedArgs[1] == 1 && InterruptedArgs[2] == 1); + Show("io_getevents_stash_interrupted", FinishSyscallArguments(static_cast(-EINTR), &Interrupted)); + Show("io_getevents_stash_interrupted_event", SealedEvents[0].Data == 0x44 && SealedEvents[0].Object == reinterpret_cast(&KeyB)); + FailReap(4, {0x45, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage RejectedMask; + uint64_t RejectedMaskArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_pgetevents, RejectedMaskArgs, &RejectedMask); + Show("io_getevents_stash_einval_result", FinishSyscallArguments(static_cast(-EINVAL), &RejectedMask)); + ArgumentStorage AfterRejected; + uint64_t AfterRejectedArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, AfterRejectedArgs, &AfterRejected); + Show("io_getevents_stash_einval_kept", FinishSyscallArguments(0, &AfterRejected) == 1 && SealedEvents[0].Data == 0x45); + FailReap(12, {0x46, reinterpret_cast(&KeyB), 1, 0}); + ArgumentStorage InFlight; + uint64_t InFlightArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InFlightArgs, &InFlight); + ArgumentStorage InFlightDestroy; + uint64_t InFlightDestroyArgs[6] = {12, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, InFlightDestroyArgs, &InFlightDestroy); + FinishSyscallArguments(0, &InFlightDestroy); + ArgumentStorage Recreated; + uint64_t RecreatedArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, RecreatedArgs, &Recreated); + FinishSyscallArguments(static_cast(-EINVAL), &InFlight); + Show("io_getevents_stash_recreated_result", FinishSyscallArguments(0, &Recreated)); + ArgumentStorage AfterDestroy; + uint64_t AfterDestroyArgs[6] = {12, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, AfterDestroyArgs, &AfterDestroy); + Show("io_getevents_stash_destroyed_in_flight", AfterDestroyArgs[1] == 1 && AfterDestroyArgs[2] == 1 && FinishSyscallArguments(0, &AfterDestroy) == 0); + std::vector FullStash(65536); + ArgumentStorage Filling; + uint64_t FillingArgs[6] = {31, 1, FullStash.size(), reinterpret_cast(FullStash.data()), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, FillingArgs, &Filling); + ArgumentStorage Contended; + uint64_t ContendedArgs[6] = {31, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ContendedArgs, &Contended); + Show("io_getevents_stash_blocking_kept", FillingArgs[2] == FullStash.size() && ContendedArgs[1] == 1 && ContendedArgs[2] == 1); + FinishSyscallArguments(0, &Contended); + FinishSyscallArguments(0, &Filling); + ArgumentStorage Uncrowded; + uint64_t UncrowdedArgs[6] = {31, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, UncrowdedArgs, &Uncrowded); + Show("io_getevents_stash_reserve_released", UncrowdedArgs[1] == 1 && UncrowdedArgs[2] == 1); + FinishSyscallArguments(0, &Uncrowded); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Owned; + uint64_t OwnedArgs[6] = {32, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OwnedArgs, &Owned); + const auto* OwnedBuffer = Owned.EventBuffer.data(); + const bool OwnedReady = Owned.Recovery.size() == 1; + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent OwnedEvent {0x47, reinterpret_cast(&KeyB), 1, 0}; + Deliver(OwnedArgs, &OwnedEvent, sizeof(OwnedEvent)); + const auto OwnedResult = FinishSyscallArguments(1, &Owned); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const auto& OwnedState = AioContextsLocked()[32]; + Show("io_getevents_recovery_preallocated", OwnedReady && OwnedResult == static_cast(-EFAULT) && Owned.Recovery.empty() && + OwnedState.Batches.size() == 1 && OwnedState.Batches.front().data() == OwnedBuffer); + ArgumentStorage OwnedRetry; + uint64_t OwnedRetryArgs[6] = {32, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OwnedRetryArgs, &OwnedRetry); + Show("io_getevents_recovery_delivered", FinishSyscallArguments(0, &OwnedRetry) == 1 && SealedEvents[0].Data == 0x47); + uint32_t ReplacementRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Replaced = reinterpret_cast(ReplacementRing); + FailReap(Replaced, {0x48, reinterpret_cast(&KeyB), 1, 0}); + const auto ReplacedCopies = IoCopyCount.load(); + ArgumentStorage OldSubmit; + uint64_t OldSubmitArgs[6] = {Replaced, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, OldSubmitArgs, &OldSubmit); + const auto OldCopy = reinterpret_cast(OldSubmitArgs[2])[0]; + FinishSyscallArguments(1, &OldSubmit); + ArgumentStorage OldDestroy; + uint64_t OldDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, OldDestroyArgs, &OldDestroy); + uint64_t ReplacementContext = Replaced; + ArgumentStorage Replacement; + uint64_t ReplacementArgs[6] = {128, reinterpret_cast(&ReplacementContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, ReplacementArgs, &Replacement); + FinishSyscallArguments(0, &Replacement); + ArgumentStorage NewSubmit; + uint64_t NewSubmitArgs[6] = {Replaced, 1, reinterpret_cast(Submitted), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, NewSubmitArgs, &NewSubmit); + const auto NewCopy = reinterpret_cast(NewSubmitArgs[2])[0]; + FinishSyscallArguments(1, &NewSubmit); + ArgumentStorage StaleReap; + uint64_t StaleReapArgs[6] = {Replaced, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StaleReapArgs, &StaleReap); + const bool StaleSkipped = StaleReapArgs[1] == 1 && StaleReapArgs[2] == 1; + FinishSyscallArguments(0, &StaleReap); + FailReap(Replaced, {0x49, reinterpret_cast(&KeyB), 1, 0}); + FinishSyscallArguments(0, &OldDestroy); + Show("io_destroy_replacement_copies_kept", StaleSkipped && IoCopyCount.load() - ReplacedCopies == 1 && OldCopy != NewCopy && + !FindIoCopyLocked(OldCopy) && FindIoCopyLocked(NewCopy)); + ArgumentStorage ReplacementRetry; + uint64_t ReplacementRetryArgs[6] = {Replaced, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ReplacementRetryArgs, &ReplacementRetry); + Show("io_destroy_replacement_stash_kept", FinishSyscallArguments(0, &ReplacementRetry) == 1 && SealedEvents[0].Data == 0x49); + ArgumentStorage NewDestroy; + uint64_t NewDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, NewDestroyArgs, &NewDestroy); + FinishSyscallArguments(0, &NewDestroy); + Show("io_destroy_replacement_released", IoCopyCount.load() - ReplacedCopies + (FindIoCopyLocked(NewCopy) != nullptr)); + uint32_t WakeRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Woken = reinterpret_cast(WakeRing); + uint64_t WakeContext = Woken; + ArgumentStorage WakeSetup; + uint64_t WakeSetupArgs[6] = {128, reinterpret_cast(&WakeContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, WakeSetupArgs, &WakeSetup); + const bool SetupPrivate = WakeSetupArgs[1] == reinterpret_cast(&WakeSetup.SetupId); + FinishSyscallArguments(0, &WakeSetup); + const auto WakeGeneration = AioContextsLocked()[Woken].Generation; + ArgumentStorage WakeRejected; + uint64_t WakeRejectedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WakeRejectedArgs, &WakeRejected); + FinishSyscallArguments(static_cast(-EINVAL), &WakeRejected); + Show("io_setup_generation_kept", SetupPrivate && WakeGeneration != 0 && AioContextsLocked().count(Woken) == 1 && + AioContextsLocked()[Woken].Generation == WakeGeneration && AioContextsLocked()[Woken].Live); + const uint64_t EventWords = sizeof(TestEvent) / sizeof(uint64_t); + const int ReapsBefore = AioReaps; + ArgumentStorage Blocked; + uint64_t BlockedArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, BlockedArgs, &Blocked); + Show("io_getevents_blocking_sliced", Blocked.Blocking && BlockedArgs[1] == 2 && BlockedArgs[2] == 2 && + BlockedArgs[4] == reinterpret_cast(Blocked.Wait) && Blocked.Wait[0] == 0 && Blocked.Wait[1] == 20000000 && Blocked.Deadline < 0); + ArgumentStorage StashPair; + uint64_t StashPairArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, StashPairArgs, &StashPair); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent StashPairEvents[2] = {{0x4a, reinterpret_cast(&KeyB), 1, 0}, {0x4b, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(StashPairArgs, StashPairEvents, sizeof(StashPairEvents)); + const auto StashPairResult = FinishSyscallArguments(2, &StashPair); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_slice_collects_stash", StashPairResult == static_cast(-EFAULT) && FinishSyscallArguments(0, &Blocked) == 2 && + AioReaps == ReapsBefore && SealedEvents[0].Data == 0x4a && SealedEvents[1].Data == 0x4b && + SealedEvents[1].Object == reinterpret_cast(&KeyC)); + ArgumentStorage Waiting; + uint64_t WaitingArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WaitingArgs, &Waiting); + bool SiblingStashed = false; + AioReapHook = [&](const uint64_t* Words) -> long { + SiblingStashed = Words[1] == Woken && Words[2] == 1 && Words[3] == 1 && Words[4] == reinterpret_cast(Waiting.EventBuffer.data()) && + Words[5] == reinterpret_cast(Waiting.Wait) && Waiting.Wait[1] == 20000000 && + FailReap(Woken, {0x4c, reinterpret_cast(&KeyB), 1, 0}) == static_cast(-EFAULT); + return 0; + }; + const auto WaitingResult = FinishSyscallArguments(0, &Waiting); + AioReapHook = nullptr; + Show("io_getevents_slice_without_notification", SiblingStashed && WaitingResult == 1 && AioReaps == ReapsBefore + 1 && + AioReapArgs[0] == SYS_io_getevents && SealedEvents[0].Data == 0x4c); + ArgumentStorage Gathering; + uint64_t GatheringArgs[6] = {Woken, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, GatheringArgs, &Gathering); + const TestEvent Trickle[3] = {{0x51, reinterpret_cast(&KeyA), 1, 0}, {0x52, reinterpret_cast(&KeyB), 1, 0}, + {0x53, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(GatheringArgs, &Trickle[0], sizeof(TestEvent)); + int Waits = 0; + bool Remaining = true; + AioReapHook = [&](const uint64_t* Words) -> long { + ++Waits; + if (Waits == 1) { + Remaining = Remaining && Words[2] == 2 && Words[3] == 2 && Words[4] == reinterpret_cast(Gathering.EventBuffer.data() + EventWords); + return 0; + } + const uint64_t Have = Waits == 2 ? 1 : 2; + Remaining = Remaining && Words[2] == 3 - Have && Words[3] == 3 - Have && + Words[4] == reinterpret_cast(Gathering.EventBuffer.data() + Have * EventWords); + std::memcpy(reinterpret_cast(Words[4]), &Trickle[Have], sizeof(TestEvent)); + return 1; + }; + const auto GatheringResult = FinishSyscallArguments(1, &Gathering); + AioReapHook = nullptr; + Show("io_getevents_slices_accumulate", GatheringResult == 3 && Waits == 3 && Remaining && SealedEvents[0].Data == 0x51 && + SealedEvents[1].Data == 0x52 && SealedEvents[2].Data == 0x53 && SealedEvents[2].Object == reinterpret_cast(&KeyC)); + ArgumentStorage Interrupt; + uint64_t InterruptArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, InterruptArgs, &Interrupt); + const int ReapsInterrupt = AioReaps; + Show("io_getevents_slice_host_eintr", FinishSyscallArguments(0, &Interrupt) == static_cast(-EINTR) && AioReaps == ReapsInterrupt + 1); + FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.push_back(SIGUSR1); + ArgumentStorage Signalled; + uint64_t SignalledArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SignalledArgs, &Signalled); + const int ReapsSignalled = AioReaps; + const auto SignalledResult = FinishSyscallArguments(0, &Signalled); + ArgumentStorage SignalledSome; + uint64_t SignalledSomeArgs[6] = {Woken, 2, 2, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SignalledSomeArgs, &SignalledSome); + Deliver(SignalledSomeArgs, &Trickle[1], sizeof(TestEvent)); + const auto SignalledSomeResult = FinishSyscallArguments(1, &SignalledSome); + FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.clear(); + Show("io_getevents_slice_deferred_signal", SignalledResult == static_cast(-EINTR) && SignalledSomeResult == 1 && + AioReaps == ReapsSignalled && SealedEvents[0].Data == 0x52); + ArgumentStorage Polled; + uint64_t PolledArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PolledArgs, &Polled); + const int ReapsPolled = AioReaps; + Show("io_getevents_zero_timeout", PolledArgs[4] == reinterpret_cast(Polled.Wait) && Polled.Wait[0] == 0 && Polled.Wait[1] == 0 && + FinishSyscallArguments(0, &Polled) == 0 && AioReaps == ReapsPolled); + int64_t ShortWait[2] = {0, 1000000}; + ArgumentStorage Timed; + uint64_t TimedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(ShortWait), 0}; + const auto TimedStart = std::chrono::steady_clock::now(); + Call(Sys::SYSCALL_x64_io_getevents, TimedArgs, &Timed); + const bool TimedFirst = Timed.Wait[0] == 0 && Timed.Wait[1] > 0 && Timed.Wait[1] <= 1000000; + bool TimedBounded = true; + AioReapHook = [&](const uint64_t* Words) -> long { + const auto* Wait = reinterpret_cast(Words[5]); + TimedBounded = TimedBounded && Wait[0] == 0 && Wait[1] > 0 && Wait[1] <= 1000000; + return 0; + }; + const auto TimedResult = FinishSyscallArguments(0, &Timed); + const auto TimedTook = std::chrono::steady_clock::now() - TimedStart; + AioReapHook = nullptr; + Show("io_getevents_timeout_returns_empty", TimedFirst && TimedBounded && TimedResult == 0 && TimedTook >= std::chrono::milliseconds(1) && + ShortWait[0] == 0 && ShortWait[1] == 1000000); + int64_t LongWait[2] = {5, 0}; + uint64_t MaskWords[2] = {0, 8}; + ArgumentStorage Masked; + uint64_t MaskedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(LongWait), reinterpret_cast(MaskWords)}; + Call(Sys::SYSCALL_x64_io_pgetevents, MaskedArgs, &Masked); + const bool MaskedSliced = Masked.Wait[0] == 0 && Masked.Wait[1] == 20000000 && Masked.Deadline > 0; + AioReapHook = [&](const uint64_t* Words) -> long { + std::memcpy(reinterpret_cast(Words[4]), &Trickle[2], sizeof(TestEvent)); + return 1; + }; + const auto MaskedResult = FinishSyscallArguments(0, &Masked); + AioReapHook = nullptr; + Show("io_pgetevents_slices_keep_mask", MaskedSliced && MaskedResult == 1 && AioReapArgs[0] == SYS_io_pgetevents && + AioReapArgs[6] == reinterpret_cast(MaskWords) && SealedEvents[0].Data == 0x53); + int64_t BadWait[2] = {0, 2000000000}; + ArgumentStorage Unsliced; + uint64_t UnslicedArgs[6] = {Woken, 1, 1, reinterpret_cast(SealedEvents), reinterpret_cast(BadWait), 0}; + Call(Sys::SYSCALL_x64_io_getevents, UnslicedArgs, &Unsliced); + const int ReapsUnsliced = AioReaps; + Show("io_getevents_odd_timeout_native", !Unsliced.Blocking && UnslicedArgs[1] == 1 && UnslicedArgs[4] == reinterpret_cast(BadWait) && + FinishSyscallArguments(0, &Unsliced) == 0 && AioReaps == ReapsUnsliced); + uint64_t* Published = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + uint32_t LostRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + *Published = reinterpret_cast(LostRing); + ArgumentStorage Unpublished; + uint64_t UnpublishedArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, UnpublishedArgs, &Unpublished); + mprotect(Published, Page, PROT_READ); + Show("io_setup_unpublished_result", FinishSyscallArguments(0, &Unpublished)); + Show("io_setup_unpublished_destroyed", AioDestroyed == reinterpret_cast(LostRing) && + AioContextsLocked().count(reinterpret_cast(LostRing)) == 0); + mprotect(Published, Page, PROT_READ | PROT_WRITE); + uint32_t ReusedRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + const uint64_t Reused = reinterpret_cast(ReusedRing); + *Published = Reused; + uint64_t ReusedGeneration = 0; + AioDestroyHook = [&](uint64_t Ring) { ReusedGeneration = BeginContext(Ring); }; + ArgumentStorage ReusedSetup; + uint64_t ReusedSetupArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, ReusedSetupArgs, &ReusedSetup); + mprotect(Published, Page, PROT_READ); + const auto ReusedResult = FinishSyscallArguments(0, &ReusedSetup); + AioDestroyHook = nullptr; + Show("io_setup_rollback_keeps_reused_context", ReusedResult == static_cast(-EFAULT) && ReusedGeneration != 0 && + AioContextsLocked().count(Reused) == 1 && AioContextsLocked()[Reused].Generation == ReusedGeneration); + ReleaseContext(Reused, ReusedGeneration); + mprotect(Published, Page, PROT_NONE); + ArgumentStorage UnreadableSetup; + uint64_t UnreadableArgs[6] = {128, reinterpret_cast(Published), 0, 0, 0, 0}; + Show("io_setup_unreadable_output_faults", Call(Sys::SYSCALL_x64_io_setup, UnreadableArgs, &UnreadableSetup) == static_cast(-EFAULT) && + UnreadableArgs[1] == reinterpret_cast(Published) && UnreadableSetup.SetupContext == 0 && + FinishSyscallArguments(static_cast(-EFAULT), &UnreadableSetup) == static_cast(-EFAULT)); + munmap(Published, Page); + ArgumentStorage BogusReap; + uint64_t BogusReapArgs[6] = {0x5bad, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, BogusReapArgs, &BogusReap); + FinishSyscallArguments(static_cast(-EINVAL), &BogusReap); + Show("io_getevents_invalid_context_forgotten", AioContextsLocked().count(0x5bad)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage Pending; + uint64_t PendingArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PendingArgs, &Pending); + ArgumentStorage Rejected; + uint64_t RejectedArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_pgetevents, RejectedArgs, &Rejected); + FinishSyscallArguments(static_cast(-EINVAL), &Rejected); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent PendingEvent {0x4a, reinterpret_cast(&KeyB), 1, 0}; + Deliver(PendingArgs, &PendingEvent, sizeof(PendingEvent)); + FinishSyscallArguments(1, &Pending); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage PendingRetry; + uint64_t PendingRetryArgs[6] = {33, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, PendingRetryArgs, &PendingRetry); + Show("io_getevents_rejected_sibling_kept", FinishSyscallArguments(0, &PendingRetry) == 1 && SealedEvents[0].Data == 0x4a); + FailReap(10, {0x33, reinterpret_cast(&KeyC), 1, 0}); + ArgumentStorage StashDestroy; + uint64_t StashDestroyArgs[6] = {10, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, StashDestroyArgs, &StashDestroy); + FinishSyscallArguments(0, &StashDestroy); + ArgumentStorage DestroyedReap; + uint64_t DestroyedReapArgs[6] = {10, 1, 1, reinterpret_cast(SealedEvents), Immediate, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DestroyedReapArgs, &DestroyedReap); + Show("io_getevents_stash_destroyed", DestroyedReapArgs[2] == 1 && FinishSyscallArguments(0, &DestroyedReap) == 0); + ArgumentStorage TripleFailed; + uint64_t TripleFailedArgs[6] = {4, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, TripleFailedArgs, &TripleFailed); + mprotect(SealedEvents, Page, PROT_READ); + const TestEvent Triple[3] = {{0x31, reinterpret_cast(&KeyA), 1, 0}, {0x32, reinterpret_cast(&KeyB), 1, 0}, + {0x33, reinterpret_cast(&KeyC), 1, 0}}; + Deliver(TripleFailedArgs, Triple, sizeof(Triple)); + Show("io_getevents_stash_triple_failed", FinishSyscallArguments(3, &TripleFailed)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage SealedRetry; + uint64_t SealedRetryArgs[6] = {4, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, SealedRetryArgs, &SealedRetry); + mprotect(SealedEvents, Page, PROT_READ); + Show("io_getevents_stash_retry_failed", FinishSyscallArguments(0, &SealedRetry)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage OrderedReap; + uint64_t OrderedReapArgs[6] = {4, 3, 3, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, OrderedReapArgs, &OrderedReap); + Show("io_getevents_stash_ordered_result", FinishSyscallArguments(0, &OrderedReap)); + Show("io_getevents_stash_ordered", SealedEvents[0].Data == 0x31 && SealedEvents[1].Data == 0x32 && SealedEvents[2].Data == 0x33 && + SealedEvents[2].Object == reinterpret_cast(&KeyC)); + static TestEvent ManyEvents[100]; + for (uint64_t i = 0; i < 100; ++i) { + ManyEvents[i] = {0x1000 + i, reinterpret_cast(&KeyA), 1, 0}; + } + ArgumentStorage ManyFailed; + uint64_t ManyFailedArgs[6] = {4, 100, 100, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ManyFailedArgs, &ManyFailed); + mprotect(SealedEvents, Page, PROT_READ); + Deliver(ManyFailedArgs, ManyEvents, sizeof(ManyEvents)); + Show("io_getevents_stash_many_failed", FinishSyscallArguments(100, &ManyFailed)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + ArgumentStorage ManyRetry; + uint64_t ManyRetryArgs[6] = {4, 100, 100, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ManyRetryArgs, &ManyRetry); + bool ManyOrdered = FinishSyscallArguments(0, &ManyRetry) == 100; + for (uint64_t i = 0; i < 100; ++i) { + ManyOrdered = ManyOrdered && SealedEvents[i].Data == 0x1000 + i; + } + Show("io_getevents_stash_many_kept", ManyOrdered); + for (uint64_t Context = 100; Context < 120; ++Context) { + FailReap(Context, {Context, reinterpret_cast(&KeyA), 1, 0}); + } + bool EveryContext = true; + for (uint64_t Context = 100; Context < 120; ++Context) { + ArgumentStorage ContextRetry; + uint64_t ContextRetryArgs[6] = {Context, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, ContextRetryArgs, &ContextRetry); + EveryContext = EveryContext && FinishSyscallArguments(0, &ContextRetry) == 1 && SealedEvents[0].Data == Context; + } + Show("io_getevents_stash_every_context", EveryContext); + TestIocb DirectBlock = ReadBlock; + uint64_t DirectList[1] = {reinterpret_cast(&DirectBlock)}; + auto SubmitDirect = [&] { + ArgumentStorage DirectSubmit; + uint64_t DirectSubmitArgs[6] = {11, 1, reinterpret_cast(DirectList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, DirectSubmitArgs, &DirectSubmit); + const auto Sent = reinterpret_cast(DirectSubmitArgs[2])[0]; + FinishSyscallArguments(1, &DirectSubmit); + return Sent; + }; + const auto DirectBefore = IoCopyCount.load(); + const auto DirectSent = SubmitDirect(); + mprotect(SealedEvents, Page, PROT_READ); + ArgumentStorage DirectReap; + uint64_t DirectReapArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, DirectReapArgs, &DirectReap); + Show("io_getevents_unwritable_first_staged", DirectReapArgs[3] == reinterpret_cast(DirectReap.EventBuffer.data()) && DirectReapArgs[2] == 1); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const TestEvent DirectEvent {0x21, DirectSent, 64, 0}; + Deliver(DirectReapArgs, &DirectEvent, sizeof(DirectEvent)); + Show("io_getevents_late_writable_result", FinishSyscallArguments(1, &DirectReap)); + Show("io_getevents_late_writable_object", SealedEvents[0].Object == reinterpret_cast(&DirectBlock)); + Show("io_getevents_late_writable_released", IoCopyCount.load() - DirectBefore); + const auto HiddenSent = SubmitDirect(); + SealedEvents[0] = {}; + mprotect(SealedEvents, Page, PROT_READ); + ArgumentStorage HiddenReap; + uint64_t HiddenReapArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HiddenReapArgs, &HiddenReap); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + const TestEvent HiddenEvent {0x22, HiddenSent, 64, 0}; + Deliver(HiddenReapArgs, &HiddenEvent, sizeof(HiddenEvent)); + mprotect(SealedEvents, Page, PROT_NONE); + Show("io_getevents_hidden_result", FinishSyscallArguments(1, &HiddenReap)); + mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_hidden_no_private", SealedEvents[0].Object == 0); + Show("io_getevents_hidden_released", IoCopyCount.load() - DirectBefore); + ArgumentStorage HiddenRetry; + uint64_t HiddenRetryArgs[6] = {11, 1, 1, reinterpret_cast(SealedEvents), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HiddenRetryArgs, &HiddenRetry); + Show("io_getevents_hidden_retry", FinishSyscallArguments(0, &HiddenRetry) == 1 && SealedEvents[0].Data == 0x22 && + SealedEvents[0].Object == reinterpret_cast(&DirectBlock)); + ArgumentStorage DirectDestroy; + uint64_t DirectDestroyArgs[6] = {11, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, DirectDestroyArgs, &DirectDestroy); + FinishSyscallArguments(0, &DirectDestroy); + munmap(SealedEvents, Page); + munmap(SealedEvents, Page); + ArgumentStorage WrappedReap; + uint64_t WrappedReapArgs[6] = {4, 1, 1024, 0xFFFF'FFFF'FFFF'F000ULL, 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, WrappedReapArgs, &WrappedReap); + Show("io_getevents_wrapped_staged", WrappedReapArgs[3] == reinterpret_cast(WrappedReap.EventBuffer.data()) && WrappedReapArgs[2] == 1 && + WrappedReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t)); + Show("io_getevents_wrapped_result", FinishSyscallArguments(static_cast(-EFAULT), &WrappedReap)); + auto* EdgeEvents = static_cast(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + mprotect(EdgeEvents + Page, Page, PROT_READ); + ArgumentStorage EdgeReap; + uint64_t EdgeReapArgs[6] = {4, 3, 4, reinterpret_cast(EdgeEvents + Page - 2 * sizeof(TestEvent)), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, EdgeReapArgs, &EdgeReap); + Show("io_getevents_writable_prefix", EdgeReapArgs[2]); + Show("io_getevents_writable_min", EdgeReapArgs[1]); + Show("io_getevents_writable_buffer", EdgeReap.EventBuffer.size() * sizeof(uint64_t) / sizeof(TestEvent)); + munmap(EdgeEvents, 2 * Page); + uint32_t Ring[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t RingContext = reinterpret_cast(Ring); + ArgumentStorage Setup; + uint64_t SetupArgs[6] = {128, reinterpret_cast(&RingContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, SetupArgs, &Setup); + FinishSyscallArguments(0, &Setup); + Show("io_setup_magic", Ring[4]); + Show("io_setup_header_kept", Ring[0] == 0 && Ring[1] == 128 && Ring[2] == 0 && Ring[3] == 0 && Ring[5] == 1 && Ring[6] == 0 && Ring[7] == 32); + uint32_t KeptRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t KeptContext = reinterpret_cast(KeptRing); + ArgumentStorage FailedSetup; + uint64_t FailedSetupArgs[6] = {128, reinterpret_cast(&KeptContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, FailedSetupArgs, &FailedSetup); + FinishSyscallArguments(static_cast(-EINVAL), &FailedSetup); + Show("io_setup_failed_magic", KeptRing[4]); + + TestEvent Completions[2] = {{7, Base + 1536, 16, 0}, {8, Base + 1536, 16, 0}}; + ArgumentStorage Reap; + uint64_t ReapArgs[6] = {1, 1, 2, reinterpret_cast(Completions), 0, 0}; + Show("io_getevents_result", Call(Sys::SYSCALL_x64_io_getevents, ReapArgs, &Reap)); + Deliver(ReapArgs, Completions, sizeof(Completions)); + FinishSyscallArguments(1, &Reap); + Show("io_getevents_object", Completions[0].Object - Single); + Show("io_getevents_unreported", Completions[1].Object - Base); + + uint64_t Pages[2] = {Single + 16, Low}; + int PageStatus[2] = {}; + ArgumentStorage Move; + uint64_t MoveArgs[6] = {0, 2, reinterpret_cast(Pages), 0, reinterpret_cast(PageStatus), 0}; + Show("move_pages_result", Call(Sys::SYSCALL_x64_move_pages, MoveArgs, &Move)); + Show("move_pages_copied", MoveArgs[2] != reinterpret_cast(Pages)); + Show("move_pages_first", reinterpret_cast(MoveArgs[2])[0] - Base); + Show("move_pages_second", reinterpret_cast(MoveArgs[2])[1] == Low); + Show("move_pages_guest_list", Pages[0] - Single); + ArgumentStorage Remote; + uint64_t RemoteArgs[6] = {1, 2, reinterpret_cast(Pages), 0, reinterpret_cast(PageStatus), 0}; + Show("move_pages_remote_result", Call(Sys::SYSCALL_x64_move_pages, RemoteArgs, &Remote)); + Show("move_pages_remote_kept", RemoteArgs[2] == reinterpret_cast(Pages)); + + uint32_t LowWord = 0; + uint64_t Waiters[2][3] = {{0, Single + 64, 2}, {0, reinterpret_cast(&LowWord), 2}}; + ArgumentStorage Wait; + uint64_t WaitArgs[6] = {reinterpret_cast(Waiters), 2, 0, 0, 1, 0}; + Show("futex_waitv_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitArgs, &Wait)); + Show("futex_waitv_copied", WaitArgs[0] != reinterpret_cast(Waiters)); + Show("futex_waitv_first", reinterpret_cast(WaitArgs[0])[1] - Base); + Show("futex_waitv_second", reinterpret_cast(WaitArgs[0])[4] == reinterpret_cast(&LowWord)); + Show("futex_waitv_guest", Waiters[0][1] - Single); + uint64_t Straddling[1][3] = {{0, Split + Page - 2, 2}}; + ArgumentStorage WaitBad; + uint64_t WaitBadArgs[6] = {reinterpret_cast(Straddling), 1, 0, 0, 1, 0}; + Show("futex_waitv_split_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitBadArgs, &WaitBad)); + uint64_t Requeue[2][3] = {{0, Single + 64, 2}, {0, Single + 128, 2}}; + ArgumentStorage RequeueStorage; + uint64_t RequeueArgs[6] = {reinterpret_cast(Requeue), 0, 1, 1, 0, 0}; + Show("futex_requeue_result", Call(Sys::SYSCALL_x64_futex_requeue, RequeueArgs, &RequeueStorage)); + Show("futex_requeue_second", reinterpret_cast(RequeueArgs[0])[4] - Base); + + const uint64_t Mapped = 0x780000000000ULL; + const int Anonymous = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED; + Show("map_result", Map(Mapped, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped); + const uint32_t MappedEntries = Count.load(); + Show("map_unmap", Unmap(Mapped + Page, Page)); + Show("map_again", Map(Mapped + Page, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped); + FindLocked(Mapped, &Part); + Show("map_merged_size", Part.Size); + Show("map_merged_entries", Count.load() - MappedEntries); + Show("map_unmap_again", Unmap(Mapped + Page, Page)); + Show("map_readonly", Map(Mapped + Page, Page, PROT_READ, Anonymous, -1, 0) - Mapped); + FindLocked(Mapped, &Part); + Show("map_readonly_size", Part.Size); + Show("map_readonly_entries", Count.load() - MappedEntries); + + auto* Order = static_cast(mmap(nullptr, 5 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t OrderHost = reinterpret_cast(Order); + const uint64_t Ordered = 0x770000000000ULL; + const uint32_t OrderEntries = Count.load(); + AddEntry(Ordered + Page, Page, OrderHost + Page, false, PROT_READ); + AddEntry(Ordered + 3 * Page, Page, OrderHost + 4 * Page, false, PROT_READ); + AddEntry(Ordered, Page, OrderHost, false, PROT_READ); + AddEntry(Ordered + 2 * Page, Page, OrderHost + 3 * Page, false, PROT_READ); + Show("slot_order_restore", Protect(Ordered, 4 * Page, PROT_READ | PROT_WRITE)); + Show("slot_order_entries", Count.load() - OrderEntries); + FindLocked(Ordered + 2 * Page, &Part); + Show("slot_order_second_size", Part.Size); + + ArgumentStorage Widths; + uint64_t GroupsWide[6] = {(1ULL << 32) + 1, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_wide_result", Call(Sys::SYSCALL_x64_getgroups, GroupsWide, &Widths)); + Show("getgroups_wide_list", GroupsWide[1] - Base); + uint64_t GroupsNegative[6] = {0xffffffffULL, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_negative_result", Call(Sys::SYSCALL_x64_getgroups, GroupsNegative, &Widths)); + uint64_t GroupsLarge[6] = {(1ULL << 32) + 2, Single + Page - 4, 0, 0, 0, 0}; + Show("getgroups_large_result", Call(Sys::SYSCALL_x64_getgroups, GroupsLarge, &Widths)); + uint64_t PollWide[6] = {Single + Page - 8, (1ULL << 32) + 1, 0, 0, 0, 0}; + Show("poll_wide_result", Call(Sys::SYSCALL_x64_poll, PollWide, &Widths)); + uint64_t EpollNegative[6] = {3, Single + Page - 12, 0xffffffffULL, 0, 0, 0}; + Show("epoll_negative_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollNegative, &Widths)); + ArgumentStorage NegativeReap; + uint64_t EventsNegative[6] = {1, 1, static_cast(-1), Single, 0, 0}; + Show("io_getevents_negative_result", Call(Sys::SYSCALL_x64_io_getevents, EventsNegative, &NegativeReap)); + + struct iovec PrefixVectors[2] = {{reinterpret_cast(Single + 256), 32}, {reinterpret_cast(Split + Page - 8), 16}}; + struct mmsghdr Prefix[2] {}; + Prefix[0].msg_hdr.msg_iov = &PrefixVectors[0]; + Prefix[0].msg_hdr.msg_iovlen = 1; + Prefix[1].msg_hdr.msg_iov = &PrefixVectors[1]; + Prefix[1].msg_hdr.msg_iovlen = 1; + ArgumentStorage PrefixBatch; + uint64_t PrefixArgs[6] = {3, reinterpret_cast(Prefix), 2, 0, 0, 0}; + Show("sendmmsg_prefix_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixArgs, &PrefixBatch)); + Show("sendmmsg_prefix_count", PrefixArgs[2]); + ArgumentStorage PrefixBad; + uint64_t PrefixBadArgs[6] = {3, reinterpret_cast(&Prefix[1]), 1, 0, 0, 0}; + Show("sendmmsg_first_bad_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixBadArgs, &PrefixBad)); + auto* ApartFirst = reinterpret_cast(Backing + 3 * Page - sizeof(struct mmsghdr)); + auto* ApartSecond = reinterpret_cast(Backing + 4 * Page); + char ApartLow[32]; + struct iovec ApartVectors[2] = {{ApartLow, 11}, {ApartLow, 22}}; + *ApartFirst = {}; + ApartFirst->msg_hdr.msg_iov = &ApartVectors[0]; + ApartFirst->msg_hdr.msg_iovlen = 1; + *ApartSecond = {}; + ApartSecond->msg_hdr.msg_iov = &ApartVectors[1]; + ApartSecond->msg_hdr.msg_iovlen = 1; + ArgumentStorage ApartBatch; + uint64_t HeadersApart[6] = {static_cast(Peer), Split + Page - sizeof(struct mmsghdr), 2, 0, 0, 0}; + Show("sendmmsg_headers_apart_result", Call(Sys::SYSCALL_x64_sendmmsg, HeadersApart, &ApartBatch)); + Show("sendmmsg_headers_apart_count", HeadersApart[2]); + auto* ApartHost = reinterpret_cast(HeadersApart[1]); + Show("sendmmsg_headers_apart_first", ApartHost[0].msg_hdr.msg_iov[0].iov_len); + Show("sendmmsg_headers_apart_second", ApartHost[1].msg_hdr.msg_iov[0].iov_len); + SendCalls = 0; + ApartHost[0].msg_len = 11; + Show("sendmmsg_headers_apart_finish", FinishResult(1, &ApartBatch)); + Show("sendmmsg_headers_apart_sent", SentLengths[0]); + Show("sendmmsg_headers_apart_lengths", ApartFirst->msg_len * 0x100 + ApartSecond->msg_len); + + struct iovec MovingVector = {reinterpret_cast(Single + 256), 32}; + const uint64_t Moving = 0x760000000000ULL; + Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t OldHost {}; + TranslateRange(Moving, Page, &OldHost); + auto* MovingHeaders = reinterpret_cast(OldHost); + MovingHeaders[0] = {}; + MovingHeaders[0].msg_hdr.msg_iov = &MovingVector; + MovingHeaders[0].msg_hdr.msg_iovlen = 1; + ArgumentStorage MovingBatch; + uint64_t MovingArgs[6] = {3, Moving, 1, 0, 0, 0}; + Show("moved_result", Call(Sys::SYSCALL_x64_sendmmsg, MovingArgs, &MovingBatch)); + reinterpret_cast(MovingArgs[1])[0].msg_len = 32; + Unmap(Moving, Page); + auto* Unrelated = static_cast(mmap(reinterpret_cast(OldHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0)); + Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NewHost {}; + TranslateRange(Moving, Page, &NewHost); + Show("moved_finish", FinishResult(1, &MovingBatch)); + Show("moved_unrelated_placed", reinterpret_cast(Unrelated) == OldHost && NewHost != OldHost); + Show("moved_unrelated_length", Unrelated[0].msg_len); + Show("moved_new_length", reinterpret_cast(NewHost)[0].msg_len); + + const uint64_t Sealed = 0x750000000000ULL; + Map(Sealed, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t SealedHost {}; + TranslateRange(Sealed, 2 * Page, &SealedHost); + auto* SealedHeaders = reinterpret_cast(SealedHost + Page - sizeof(struct mmsghdr)); + for (int i = 0; i < 3; ++i) { + SealedHeaders[i] = {}; + SealedHeaders[i].msg_hdr.msg_iov = &MovingVector; + SealedHeaders[i].msg_hdr.msg_iovlen = 1; + } + Protect(Sealed + Page, Page, PROT_READ); + ArgumentStorage SealedBatch; + uint64_t SealedArgs[6] = {static_cast(Peer), Sealed + Page - sizeof(struct mmsghdr), 3, 0, 0, 0}; + Show("sealed_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedArgs, &SealedBatch)); + Show("sealed_submitted", SealedArgs[2]); + auto* SealedCopy = reinterpret_cast(SealedArgs[1]); + SealedCopy[0].msg_len = 32; + SendCalls = 0; + Show("sealed_finish", FinishResult(1, &SealedBatch)); + Show("sealed_later_sends", SendCalls); + Show("sealed_first_length", SealedHeaders[0].msg_len); + Show("sealed_second_length", SealedHeaders[1].msg_len); + Show("sealed_third_length", SealedHeaders[2].msg_len); + ArgumentStorage SealedOnly; + uint64_t SealedOnlyArgs[6] = {3, Sealed + Page, 1, 0, 0, 0}; + Show("sealed_only_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedOnlyArgs, &SealedOnly)); + reinterpret_cast(SealedOnlyArgs[1])[0].msg_len = 32; + Show("sealed_only_finish", FinishResult(1, &SealedOnly)); + + ArgumentStorage Embedded; + uint8_t* SplitEnd = Backing + 3 * Page; + const uint32_t Sizes32[] = {64, 0, 72}; + const char* PerfNames[] = {"perf_attr_fits_result", "perf_attr_default_result", "perf_attr_large_result"}; + for (int i = 0; i < 3; ++i) { + std::memcpy(SplitEnd - 64 + 4, &Sizes32[i], 4); + uint64_t PerfArgs[6] = {Split + Page - 64, 0, static_cast(-1), static_cast(-1), 0, 0}; + Show(PerfNames[i], Call(Sys::SYSCALL_x64_perf_event_open, PerfArgs, &Embedded)); + } + const uint32_t SchedSizes[] = {48, 56}; + const char* SchedNames[] = {"sched_attr_fits_result", "sched_attr_large_result"}; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 48, &SchedSizes[i], 4); + uint64_t SchedArgs[6] = {0, Split + Page - 48, 0, 0, 0, 0}; + Show(SchedNames[i], Call(Sys::SYSCALL_x64_sched_setattr, SchedArgs, &Embedded)); + } + const uint32_t CapHeader1[2] = {0x19980330, 0}; + const uint32_t CapHeader3[2] = {0x20080522, 0}; + uint64_t CapV1[6] = {reinterpret_cast(CapHeader1), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_v1_result", Call(Sys::SYSCALL_x64_capget, CapV1, &Embedded)); + Show("capget_v1_data", CapV1[1] - Base); + uint64_t CapV3[6] = {reinterpret_cast(CapHeader3), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_v3_result", Call(Sys::SYSCALL_x64_capget, CapV3, &Embedded)); + uint64_t CapSetV3[6] = {reinterpret_cast(CapHeader3), Split + Page - 12, 0, 0, 0, 0}; + Show("capset_v3_result", Call(Sys::SYSCALL_x64_capset, CapSetV3, &Embedded)); + uint32_t CapGuest[2] = {0x19980330, 0}; + ArgumentStorage CapCopy; + uint64_t CapCopyArgs[6] = {reinterpret_cast(CapGuest), Split + Page - 12, 0, 0, 0, 0}; + Show("capget_copy_result", Call(Sys::SYSCALL_x64_capget, CapCopyArgs, &CapCopy)); + Show("capget_copy_private", CapCopyArgs[0] != reinterpret_cast(CapGuest)); + CapGuest[0] = 0x20080522; + Show("capget_copy_version", reinterpret_cast(CapCopyArgs[0])[0]); + Show("capget_copy_finish", FinishResult(0, &CapCopy)); + Show("capget_copy_guest_version", CapGuest[0]); + uint32_t CapUnknown[2] = {0x1234, 0}; + ArgumentStorage CapInvalid; + uint64_t CapInvalidArgs[6] = {reinterpret_cast(CapUnknown), Single + 64, 0, 0, 0, 0}; + Show("capget_invalid_result", Call(Sys::SYSCALL_x64_capget, CapInvalidArgs, &CapInvalid)); + reinterpret_cast(CapInvalidArgs[0])[0] = 0x20080522; + Show("capget_invalid_finish", FinishResult(static_cast(-EINVAL), &CapInvalid)); + Show("capget_invalid_version", CapUnknown[0]); + const uint32_t HandleBytes[] = {8, 16}; + const char* HandleNames[] = {"name_to_handle_fits_result", "name_to_handle_large_result"}; + const char* OpenNames[] = {"open_by_handle_fits_result", "open_by_handle_large_result"}; + int MountId = 0; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 16, &HandleBytes[i], 4); + uint64_t HandleArgs[6] = {static_cast(AT_FDCWD), reinterpret_cast("x"), Split + Page - 16, reinterpret_cast(&MountId), 0, 0}; + Show(HandleNames[i], Call(Sys::SYSCALL_x64_name_to_handle_at, HandleArgs, &Embedded)); + uint64_t OpenArgs[6] = {3, Split + Page - 16, 0, 0, 0, 0}; + Show(OpenNames[i], Call(Sys::SYSCALL_x64_open_by_handle_at, OpenArgs, &Embedded)); + } + const uint32_t OversizedHandle = 1000; + std::memcpy(SplitEnd - 4, &OversizedHandle, 4); + uint64_t HandleHeaderSplit[6] = {static_cast(AT_FDCWD), reinterpret_cast("x"), Split + Page - 4, reinterpret_cast(&MountId), 0, 0}; + Show("name_to_handle_header_split_result", Call(Sys::SYSCALL_x64_name_to_handle_at, HandleHeaderSplit, &Embedded)); + uint64_t OpenHeaderSplit[6] = {3, Split + Page - 4, 0, 0, 0, 0}; + Show("open_by_handle_header_split_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderSplit, &Embedded)); + std::memcpy(SplitEnd - 8, &OversizedHandle, 4); + uint64_t OpenHeaderFits[6] = {3, Split + Page - 8, 0, 0, 0, 0}; + Show("open_by_handle_header_fits_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderFits, &Embedded)); + const uint32_t RequestSizes[] = {24, 32}; + const char* RequestNames[] = {"statmount_fits_result", "statmount_large_result"}; + for (int i = 0; i < 2; ++i) { + std::memcpy(SplitEnd - 24, &RequestSizes[i], 4); + uint64_t RequestArgs[6] = {Split + Page - 24, 0, 0, 0, 0, 0}; + Show(RequestNames[i], Call(Sys::SYSCALL_x64_statmount, RequestArgs, &Embedded)); + } + uint64_t PathRule[6] = {3, 1, Split + Page - 12, 0, 0, 0}; + Show("landlock_path_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PathRule, &Embedded)); + uint64_t PortRule[6] = {3, 2, Split + Page - 12, 0, 0, 0}; + Show("landlock_port_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PortRule, &Embedded)); + + const uint64_t Nameless = 0x740000000000ULL; + Map(Nameless, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NamelessHost {}; + TranslateRange(Nameless, 2 * Page, &NamelessHost); + const uint64_t NamelessGuestHeader = Nameless + Page - 16; + auto* NamelessHeader = reinterpret_cast(NamelessHost + Page - 16); + struct iovec NamelessVector = {reinterpret_cast(Single + 128), 64}; + *NamelessHeader = {}; + NamelessHeader->msg_iov = &NamelessVector; + NamelessHeader->msg_iovlen = 1; + Protect(Nameless, Page, PROT_READ); + ArgumentStorage NamelessReceive; + uint64_t NamelessArgs[6] = {3, NamelessGuestHeader, 0, 0, 0, 0}; + Show("recvmsg_nameless_result", Call(Sys::SYSCALL_x64_recvmsg, NamelessArgs, &NamelessReceive)); + NamelessReceive.Message.msg_flags = MSG_TRUNC; + Show("recvmsg_nameless_finish", FinishResult(64, &NamelessReceive)); + Show("recvmsg_nameless_flags", NamelessHeader->msg_flags); + char NameBuffer[16]; + const uint64_t Named = 0x700000000000ULL; + Map(Named, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t NamedHost {}; + TranslateRange(Named, 2 * Page, &NamedHost); + auto* NamedHeader = reinterpret_cast(NamedHost + Page - 16); + *NamedHeader = {}; + NamedHeader->msg_name = NameBuffer; + NamedHeader->msg_namelen = sizeof(NameBuffer); + NamedHeader->msg_iov = &NamelessVector; + NamedHeader->msg_iovlen = 1; + Protect(Named, Page, PROT_READ); + ArgumentStorage NamedReceive; + uint64_t NamedArgs[6] = {3, Named + Page - 16, 0, 0, 0, 0}; + Show("recvmsg_named_result", Call(Sys::SYSCALL_x64_recvmsg, NamedArgs, &NamedReceive)); + Show("recvmsg_named_private", NamedArgs[1] != NamedHost + Page - 16); + Show("recvmsg_named_name_kept", reinterpret_cast(NamedArgs[1])->msg_name == NameBuffer); + Show("recvmsg_named_finish", FinishResult(64, &NamedReceive)); + + const uint64_t Flagged = 0x730000000000ULL; + Map(Flagged, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t FlaggedHost {}; + TranslateRange(Flagged, 2 * Page, &FlaggedHost); + auto* FlaggedHeader = reinterpret_cast(FlaggedHost + Page - offsetof(struct msghdr, msg_flags)); + *FlaggedHeader = {}; + FlaggedHeader->msg_iov = &NamelessVector; + FlaggedHeader->msg_iovlen = 1; + FlaggedHeader->msg_controllen = 99; + Protect(Flagged + Page, Page, PROT_READ); + ArgumentStorage FlaggedReceive; + uint64_t FlaggedArgs[6] = {3, Flagged + Page - offsetof(struct msghdr, msg_flags), 0, 0, 0, 0}; + Show("recvmsg_flags_first_result", Call(Sys::SYSCALL_x64_recvmsg, FlaggedArgs, &FlaggedReceive)); + FlaggedReceive.Message.msg_controllen = 0; + Show("recvmsg_flags_first_finish", FinishResult(64, &FlaggedReceive)); + Show("recvmsg_flags_first_controllen", FlaggedHeader->msg_controllen); + + const uint64_t Blocks = 0x720000000000ULL; + Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t BlocksHost {}; + TranslateRange(Blocks, Page, &BlocksHost); + auto* HighIocb = reinterpret_cast(BlocksHost); + *HighIocb = {}; + HighIocb->Data = 0x99; + HighIocb->Opcode = 7; + HighIocb->Buffer = reinterpret_cast(Scatter); + HighIocb->Bytes = 2; + const TestIocb HighExpected = *HighIocb; + uint64_t HighIocbList[1] = {Blocks}; + ArgumentStorage HighCopy; + uint64_t HighCopyArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_high_copy_result", Call(Sys::SYSCALL_x64_io_submit, HighCopyArgs, &HighCopy)); + const uint64_t HighSent = reinterpret_cast(HighCopyArgs[2])[0]; + Show("io_submit_high_copy_private", HighSent != BlocksHost && FindIoCopyLocked(HighSent) != nullptr); + Show("io_submit_high_copy_vector", reinterpret_cast(reinterpret_cast(HighSent)->Buffer)[0].iov_base == reinterpret_cast(Base + 800)); + Show("io_submit_high_copy_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + ArgumentStorage HighCancel; + uint64_t HighCancelArgs[6] = {1, Blocks, reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, HighCancelArgs, &HighCancel); + Show("io_cancel_high_private", HighCancelArgs[1] == HighSent); + Show("io_submit_high_copy_hidden", Protect(Blocks, Page, PROT_NONE)); + uint64_t SealedProbe = 0; + auto HiddenRead = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyFromUser(&SealedProbe, &HighIocb->Buffer, sizeof(SealedProbe)) != 0; }; + auto HiddenWrite = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyToUser(&HighIocb->Buffer, &SealedProbe, sizeof(SealedProbe)) != 0; }; + ProtectCalls = 0; + FinishSyscallArguments(1, &HighCopy); + Show("io_submit_high_copy_sealed", HiddenRead() && HiddenWrite()); + ArgumentStorage HiddenCancel; + uint64_t HiddenCancelArgs[6] = {1, Blocks, reinterpret_cast(&CancelEvent), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, HiddenCancelArgs, &HiddenCancel); + Show("io_cancel_hidden_native", HiddenCancelArgs[1] == BlocksHost); + TestEvent HighReaped[1] = {{0x99, HighSent, 16, 0}}; + ArgumentStorage HighReap; + uint64_t HighReapArgs[6] = {1, 1, 1, reinterpret_cast(HighReaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, HighReapArgs, &HighReap); + Deliver(HighReapArgs, HighReaped, sizeof(HighReaped)); + FinishSyscallArguments(1, &HighReap); + Show("io_getevents_high_object", HighReaped[0].Object - Blocks); + Show("io_getevents_high_sealed", HiddenRead() && HiddenWrite()); + Show("io_getevents_high_protect_calls", ProtectCalls); + Show("io_getevents_high_freed", IoCopyCount.load() - CopiesBefore); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + Show("io_getevents_high_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + + Protect(Blocks, Page, PROT_READ); + ArgumentStorage SealedSubmit; + uint64_t SealedSubmitArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_read_only_result", Call(Sys::SYSCALL_x64_io_submit, SealedSubmitArgs, &SealedSubmit)); + Show("io_submit_read_only_count", SealedSubmitArgs[1]); + Show("io_submit_read_only_passed", reinterpret_cast(SealedSubmitArgs[2])[0] == BlocksHost); + Show("io_submit_read_only_copies", IoCopyCount.load() - CopiesBefore); + FinishSyscallArguments(static_cast(-EBADF), &SealedSubmit); + TestIocb Leading = ReadBlock; + uint64_t LeadingList[2] = {reinterpret_cast(&Leading), Blocks}; + ArgumentStorage LeadingSubmit; + uint64_t LeadingSubmitArgs[6] = {5, 2, reinterpret_cast(LeadingList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, LeadingSubmitArgs, &LeadingSubmit); + const auto* LeadingSent = reinterpret_cast(LeadingSubmitArgs[2]); + Show("io_submit_read_only_after_copy", LeadingSubmitArgs[1] == 2 && FindIoCopyLocked(LeadingSent[0]) != nullptr && LeadingSent[1] == BlocksHost); + FinishSyscallArguments(1, &LeadingSubmit); + ArgumentStorage LeadingDestroy; + uint64_t LeadingDestroyArgs[6] = {5, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, LeadingDestroyArgs, &LeadingDestroy); + FinishSyscallArguments(0, &LeadingDestroy); + Show("io_submit_read_only_after_copy_released", IoCopyCount.load() - CopiesBefore); + Show("io_submit_read_only_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + HighIocb->Opcode = 1; + HighIocb->Buffer = reinterpret_cast(LowBuffer); + HighIocb->Bytes = sizeof(LowBuffer); + Protect(Blocks, Page, PROT_READ); + ArgumentStorage ReadOnlyNative; + uint64_t ReadOnlyNativeArgs[6] = {1, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Show("io_submit_read_only_native_result", Call(Sys::SYSCALL_x64_io_submit, ReadOnlyNativeArgs, &ReadOnlyNative)); + Show("io_submit_read_only_native_block", reinterpret_cast(ReadOnlyNativeArgs[2])[0] == BlocksHost); + Show("io_submit_read_only_native_copies", IoCopyCount.load() - CopiesBefore); + Protect(Blocks, Page, PROT_READ | PROT_WRITE); + HighIocb->Opcode = 7; + HighIocb->Buffer = reinterpret_cast(Scatter); + HighIocb->Bytes = 2; + HighIocb->Key = 4; + ArgumentStorage KeyedHigh; + uint64_t KeyedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, KeyedHighArgs, &KeyedHigh); + FinishSyscallArguments(1, &KeyedHigh); + Show("io_submit_high_key_accepted", HighIocb->Key); + HighIocb->Key = 4; + ArgumentStorage MovedHigh; + uint64_t MovedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, MovedHighArgs, &MovedHigh); + Unmap(Blocks, Page); + void* ReusedPage = mmap(reinterpret_cast(BlocksHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + Show("io_submit_key_reused_mapped", ReusedPage == reinterpret_cast(BlocksHost)); + if (ReusedPage == reinterpret_cast(BlocksHost)) { + static_cast(ReusedPage)->Key = 4; + FinishSyscallArguments(1, &MovedHigh); + Show("io_submit_key_unmapped_skipped", static_cast(ReusedPage)->Key); + munmap(ReusedPage, Page); + } + Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + static uint64_t RacedHost; + static uint32_t RacedSeen; + static TestIocb* RacedStandIn; + static std::thread RacedSibling; + static std::atomic RacedAttempted; + static bool RacedBlocked; + TranslateRange(Blocks, Page, &RacedHost); + auto* RacedIocb = reinterpret_cast(RacedHost); + *RacedIocb = {}; + RacedIocb->Opcode = 7; + RacedIocb->Buffer = reinterpret_cast(Scatter); + RacedIocb->Bytes = 2; + RacedIocb->Key = 4; + ArgumentStorage RacedHigh; + uint64_t RacedHighArgs[6] = {7, 1, reinterpret_cast(HighIocbList), 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_submit, RacedHighArgs, &RacedHigh); + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { + RacedSibling = std::thread([] { + std::unique_lock Lock {FEX::HLE::_SyscallHandler->VMATracking.Mutex, std::try_to_lock}; + RacedBlocked = !Lock.owns_lock(); + RacedAttempted = 1; + if (!Lock.owns_lock()) { + Lock.lock(); + } + RacedSeen = reinterpret_cast(RacedHost)->Key; + Unmap(Blocks, Page); + void* StandIn = mmap(reinterpret_cast(RacedHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0); + if (StandIn == reinterpret_cast(RacedHost)) { + RacedStandIn = static_cast(StandIn); + RacedStandIn->Key = 4; + } + }); + while (RacedAttempted.load() == 0) { + std::this_thread::yield(); + } + }; + FinishSyscallArguments(1, &RacedHigh); + RacedSibling.join(); + Show("io_submit_key_store_blocked_writer", RacedBlocked); + Show("io_submit_key_store_before_unmap", RacedSeen); + Show("io_submit_key_store_stand_in", RacedStandIn != nullptr ? RacedStandIn->Key : 0xff); + Show("io_submit_key_store_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held); + if (RacedStandIn != nullptr) { + munmap(RacedStandIn, Page); + } + ArgumentStorage KeyedDestroy; + uint64_t KeyedDestroyArgs[6] = {7, 0, 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_destroy, KeyedDestroyArgs, &KeyedDestroy); + FinishSyscallArguments(0, &KeyedDestroy); + Show("io_submit_keyed_high_released", IoCopyCount.load() - CopiesBefore); + + auto* LowBlock = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + *LowBlock = {}; + LowBlock->Opcode = 7; + LowBlock->Buffer = reinterpret_cast(Scatter); + LowBlock->Bytes = 2; + const TestIocb LowExpected = *LowBlock; + uint64_t LowList[1] = {reinterpret_cast(LowBlock)}; + ArgumentStorage LowCopy; + uint64_t LowCopyArgs[6] = {1, 1, reinterpret_cast(LowList), 0, 0, 0}; + Show("low_iocb_result", Call(Sys::SYSCALL_x64_io_submit, LowCopyArgs, &LowCopy)); + const uint64_t LowSent = reinterpret_cast(LowCopyArgs[2])[0]; + Show("low_iocb_private", LowSent != reinterpret_cast(LowBlock) && FindIoCopyLocked(LowSent) != nullptr); + mprotect(LowBlock, Page, PROT_READ); + ProtectCalls = 0; + FinishSyscallArguments(1, &LowCopy); + Show("low_iocb_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0); + const auto Regions = Count.load(); + Count.store(0); + ArgumentStorage QuietCancel; + uint64_t QuietCancelArgs[6] = {1, reinterpret_cast(LowBlock), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_cancel, QuietCancelArgs, &QuietCancel); + Show("low_iocb_quiet_cancel", QuietCancelArgs[1] == LowSent); + TestEvent QuietReaped[1] = {{0, LowSent, 16, 0}}; + ArgumentStorage QuietReap; + uint64_t QuietReapArgs[6] = {1, 1, 1, reinterpret_cast(QuietReaped), 0, 0}; + Call(Sys::SYSCALL_x64_io_getevents, QuietReapArgs, &QuietReap); + Show("low_iocb_quiet_host_buffer", QuietReapArgs[3] == reinterpret_cast(QuietReap.EventBuffer.data())); + Deliver(QuietReapArgs, QuietReaped, sizeof(QuietReaped)); + FinishSyscallArguments(1, &QuietReap); + uint32_t QuietRing[8] = {0, 64, 0, 0, 0xa10a10a1, 1, 0, 32}; + uint64_t QuietRingContext = reinterpret_cast(QuietRing); + ArgumentStorage QuietSetup; + uint64_t QuietSetupArgs[6] = {64, reinterpret_cast(&QuietRingContext), 0, 0, 0, 0}; + Call(Sys::SYSCALL_x64_io_setup, QuietSetupArgs, &QuietSetup); + FinishSyscallArguments(0, &QuietSetup); + Show("low_quiet_setup_magic", QuietRing[4]); + Count.store(Regions); + Show("low_iocb_quiet_object", QuietReaped[0].Object == reinterpret_cast(LowBlock)); + Show("low_iocb_quiet_freed", IoCopyCount.load() - CopiesBefore); + Show("low_iocb_protect_calls", ProtectCalls); + Show("low_iocb_reaped_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0); + munmap(LowBlock, Page); + + for (auto& Copy : IoCopies) { + Copy.Used = true; + } + IoCopyCount = MaxIoCopies; + ArgumentStorage Crowded; + uint64_t CrowdedArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Show("io_submit_crowded_result", Call(Sys::SYSCALL_x64_io_submit, CrowdedArgs, &Crowded)); + Show("io_submit_crowded_untouched", GuestBlocksUntouched()); + IoCopies[5].Used = false; + IoCopyCount = MaxIoCopies - 1; + ArgumentStorage LastCopy; + uint64_t LastCopyArgs[6] = {1, 2, reinterpret_cast(Submitted), 0, 0, 0}; + Show("io_submit_last_copy_result", Call(Sys::SYSCALL_x64_io_submit, LastCopyArgs, &LastCopy)); + Show("io_submit_last_copy_count", LastCopyArgs[1]); + Show("io_submit_last_copy_slot", reinterpret_cast(LastCopyArgs[2])[0] == reinterpret_cast(&IoCopies[5])); + for (auto& Copy : IoCopies) { + Copy.Used = false; + } + IoCopyCount = 0; + + auto* CapPage = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + CapPage[0] = 0x1234; + ArgumentStorage CapSealed; + uint64_t CapSealedArgs[6] = {reinterpret_cast(CapPage), Single + 64, 0, 0, 0, 0}; + Show("capget_sealed_result", Call(Sys::SYSCALL_x64_capget, CapSealedArgs, &CapSealed)); + reinterpret_cast(CapSealedArgs[0])[0] = 0x20080522; + mprotect(CapPage, Page, PROT_READ); + Show("capget_sealed_finish", FinishResult(static_cast(-EINVAL), &CapSealed)); + Show("capget_sealed_version", CapPage[0]); + + struct iovec ShortVector = {reinterpret_cast(Single + 256), 32}; + struct mmsghdr Shorts[3] {}; + for (auto& Short : Shorts) { + Short.msg_hdr.msg_iov = &ShortVector; + Short.msg_hdr.msg_iovlen = 1; + } + ArgumentStorage ShortFirst; + uint64_t ShortFirstArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Show("sendmmsg_short_first_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortFirstArgs, &ShortFirst)); + reinterpret_cast(ShortFirstArgs[1])[0].msg_len = 10; + SendCalls = 0; + Show("sendmmsg_short_first_finish", FinishResult(1, &ShortFirst)); + Show("sendmmsg_short_first_sends", SendCalls); + Show("sendmmsg_short_first_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len); + for (auto& Short : Shorts) { + Short.msg_len = 0; + } + ArgumentStorage ShortSecond; + uint64_t ShortSecondArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Show("sendmmsg_short_second_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortSecondArgs, &ShortSecond)); + Show("sendmmsg_short_second_submitted", ShortSecondArgs[2]); + const int Pinned = ShortSecond.Socket; + Show("sendmmsg_pinned_distinct", Pinned >= 0 && Pinned != Peer); + Show("sendmmsg_pinned_dispatched", ShortSecondArgs[0] == static_cast(Pinned)); + reinterpret_cast(ShortSecondArgs[1])[0].msg_len = 32; + SendCalls = 0; + SendLimit = 5; + SentSocket = -1; + Show("sendmmsg_short_second_finish", FinishResult(1, &ShortSecond)); + SendLimit = ~size_t {}; + Show("sendmmsg_short_second_sends", SendCalls); + Show("sendmmsg_short_second_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len); + Show("sendmmsg_pinned_used", SentSocket == Pinned); + Show("sendmmsg_pinned_closed", fcntl(Pinned, F_GETFD) == -1 && errno == EBADF && ShortSecond.Socket == -1); + for (auto& Short : Shorts) { + Short.msg_len = 0; + } + ArgumentStorage ShortFailed; + uint64_t ShortFailedArgs[6] = {static_cast(Peer), reinterpret_cast(Shorts), 3, 0, 0, 0}; + Call(Sys::SYSCALL_x64_sendmmsg, ShortFailedArgs, &ShortFailed); + const int FailedPin = ShortFailed.Socket; + Show("sendmmsg_error_finish", FinishResult(static_cast(-EAGAIN), &ShortFailed)); + Show("sendmmsg_error_closed", FailedPin >= 0 && fcntl(FailedPin, F_GETFD) == -1 && errno == EBADF); + int Pair[2]; + if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, Pair) != 0) { + std::fprintf(stderr, "socketpair: %s\n", std::strerror(errno)); + return 1; + } + struct iovec Payloads[3] = {}; + for (int i = 0; i < 3; ++i) { + std::memset(Backing + 2048 + 16 * i, 'A' + i, 4); + Payloads[i] = {reinterpret_cast(Single + 2048 + 16 * i), 4}; + } + auto Drain = [&] { + uint64_t Packed = 0; + unsigned char Data[16]; + while (recv(Pair[1], Data, sizeof(Data), MSG_DONTWAIT) > 0) { + Packed = Packed * 0x100 + Data[0]; + } + return Packed; + }; + auto Dispatch = [&](uint64_t* Args) { + return static_cast(sendmmsg(static_cast(Args[0]), reinterpret_cast(Args[1]), static_cast(Args[2]), 0)); + }; + auto Lengths = [&](struct mmsghdr* Headers) { + return Headers[0].msg_len * 0x10000 + Headers[1].msg_len * 0x100 + Headers[2].msg_len; + }; + PassSend = true; + + struct mmsghdr Real[3] {}; + for (int i = 0; i < 3; ++i) { + Real[i].msg_hdr.msg_iov = &Payloads[i]; + Real[i].msg_hdr.msg_iovlen = 1; + } + DupFailures = 1; + ArgumentStorage Emfile; + uint64_t EmfileArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Real), 3, 0, 0, 0}; + Show("sendmmsg_emfile_result", Call(Sys::SYSCALL_x64_sendmmsg, EmfileArgs, &Emfile)); + Show("sendmmsg_emfile_submitted", EmfileArgs[2]); + Show("sendmmsg_emfile_original", EmfileArgs[0] == static_cast(Pair[0]) && Emfile.Socket == -1 && DupFailures == 0); + Show("sendmmsg_emfile_first_only", Drain()); + Show("sendmmsg_emfile_finish", FinishResult(Dispatch(EmfileArgs), &Emfile)); + Show("sendmmsg_emfile_received", Drain()); + Show("sendmmsg_emfile_lengths", Lengths(Real)); + + const uint64_t ReadOnly = 0x730000000000ULL; + Map(ReadOnly, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + uint64_t ReadOnlyHost {}; + TranslateRange(ReadOnly, 2 * Page, &ReadOnlyHost); + auto* ReadOnlyHeaders = reinterpret_cast(ReadOnlyHost + Page - sizeof(struct mmsghdr)); + for (int i = 0; i < 3; ++i) { + ReadOnlyHeaders[i] = {}; + ReadOnlyHeaders[i].msg_hdr.msg_iov = &Payloads[i]; + ReadOnlyHeaders[i].msg_hdr.msg_iovlen = 1; + } + Protect(ReadOnly + Page, Page, PROT_READ); + DupFailures = 1; + ArgumentStorage ReadOnlyBatch; + uint64_t ReadOnlyArgs[6] = {static_cast(Pair[0]), ReadOnly + Page - sizeof(struct mmsghdr), 3, 0, 0, 0}; + Show("sendmmsg_emfile_readonly_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyArgs, &ReadOnlyBatch)); + Show("sendmmsg_emfile_readonly_submitted", ReadOnlyArgs[2]); + Show("sendmmsg_emfile_readonly_finish", FinishResult(Dispatch(ReadOnlyArgs), &ReadOnlyBatch)); + Show("sendmmsg_emfile_readonly_received", Drain()); + Show("sendmmsg_emfile_readonly_lengths", Lengths(ReadOnlyHeaders)); + + DupFailures = 1; + ArgumentStorage ReadOnlyFirst; + uint64_t ReadOnlyFirstArgs[6] = {static_cast(Pair[0]), ReadOnly + Page, 1, 0, 0, 0}; + Show("sendmmsg_emfile_only_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyFirstArgs, &ReadOnlyFirst)); + Show("sendmmsg_emfile_only_finish", FinishResult(Dispatch(ReadOnlyFirstArgs), &ReadOnlyFirst)); + Show("sendmmsg_emfile_only_received", Drain()); + DupFailures = 0; + + auto* Unreadable = static_cast(mmap(nullptr, Page, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + struct mmsghdr Middle[3] {}; + for (int i = 0; i < 3; ++i) { + Middle[i].msg_hdr.msg_iov = i == 1 ? Unreadable : &Payloads[i]; + Middle[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage MiddleBatch; + uint64_t MiddleArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Middle), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_middle_result", Call(Sys::SYSCALL_x64_sendmmsg, MiddleArgs, &MiddleBatch)); + Show("sendmmsg_unreadable_middle_submitted", MiddleArgs[2]); + Show("sendmmsg_unreadable_middle_queued", MiddleBatch.Messages.size()); + Show("sendmmsg_unreadable_middle_finish", FinishResult(Dispatch(MiddleArgs), &MiddleBatch)); + Show("sendmmsg_unreadable_middle_received", Drain()); + Show("sendmmsg_unreadable_middle_lengths", Lengths(Middle)); + + struct mmsghdr Last[3] {}; + for (int i = 0; i < 3; ++i) { + Last[i].msg_hdr.msg_iov = i == 2 ? Unreadable : &Payloads[i]; + Last[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage LastBatch; + uint64_t LastArgs[6] = {static_cast(Pair[0]), reinterpret_cast(Last), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_last_result", Call(Sys::SYSCALL_x64_sendmmsg, LastArgs, &LastBatch)); + Show("sendmmsg_unreadable_last_submitted", LastArgs[2]); + Show("sendmmsg_unreadable_last_queued", LastBatch.Messages.size()); + const int LastPin = LastBatch.Socket; + Show("sendmmsg_unreadable_last_pinned", LastPin >= 0 && LastArgs[0] == static_cast(LastPin)); + Show("sendmmsg_unreadable_last_finish", FinishResult(Dispatch(LastArgs), &LastBatch)); + Show("sendmmsg_unreadable_last_received", Drain()); + Show("sendmmsg_unreadable_last_lengths", Lengths(Last)); + + struct mmsghdr First[3] {}; + for (int i = 0; i < 3; ++i) { + First[i].msg_hdr.msg_iov = i == 0 ? Unreadable : &Payloads[i]; + First[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage FirstBatch; + uint64_t FirstArgs[6] = {static_cast(Pair[0]), reinterpret_cast(First), 3, 0, 0, 0}; + Show("sendmmsg_unreadable_first_result", Call(Sys::SYSCALL_x64_sendmmsg, FirstArgs, &FirstBatch)); + Show("sendmmsg_unreadable_first_native", FirstArgs[1] == reinterpret_cast(First) && FirstArgs[2] == 3 && FirstBatch.GuestMessages == 0); + Show("sendmmsg_unreadable_first_error", static_cast(sendmmsg(Pair[0], First, 3, 0)) == static_cast(-1) && errno == EFAULT); + Show("sendmmsg_unreadable_first_received", Drain()); + PassSend = false; + + auto* LowVectors = static_cast(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + char KeptLow[16]; + LowVectors[0] = {KeptLow, sizeof(KeptLow)}; + struct mmsghdr Growing[3] {}; + Growing[0].msg_hdr.msg_iov = &ShortVector; + Growing[0].msg_hdr.msg_iovlen = 1; + for (int i = 1; i < 3; ++i) { + Growing[i].msg_hdr.msg_iov = LowVectors; + Growing[i].msg_hdr.msg_iovlen = 1; + } + ArgumentStorage Grown; + uint64_t GrownArgs[6] = {static_cast(Peer), reinterpret_cast(Growing), 3, 0, 0, 0}; + Show("sendmmsg_grown_result", Call(Sys::SYSCALL_x64_sendmmsg, GrownArgs, &Grown)); + auto* GrownCopy = reinterpret_cast(GrownArgs[1]); + Show("sendmmsg_grown_private", GrownCopy[1].msg_hdr.msg_iov != LowVectors && GrownCopy[1].msg_hdr.msg_iov[0].iov_base == KeptLow); + GrownCopy[0].msg_len = 32; + SendCalls = 0; + GrowAfterSend = LowVectors; + Show("sendmmsg_grown_finish", FinishResult(1, &Grown)); + GrowAfterSend = nullptr; + Show("sendmmsg_grown_sends", SendCalls); + Show("sendmmsg_grown_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len); + for (auto& Message : Growing) { + Message.msg_len = 0; + } + LowVectors[0] = {KeptLow, sizeof(KeptLow)}; + ArgumentStorage Vanished; + uint64_t VanishedArgs[6] = {static_cast(Peer), reinterpret_cast(Growing), 3, 0, 0, 0}; + Show("sendmmsg_vanished_result", Call(Sys::SYSCALL_x64_sendmmsg, VanishedArgs, &Vanished)); + reinterpret_cast(VanishedArgs[1])[0].msg_len = 32; + SendCalls = 0; + SendLimit = 5; + UnmapAfterSend = LowVectors; + Show("sendmmsg_vanished_finish", FinishResult(1, &Vanished)); + SendLimit = ~size_t {}; + Show("sendmmsg_vanished_sends", SendCalls); + Show("sendmmsg_vanished_unmapped", UnmapAfterSend == nullptr && msync(LowVectors, Page, MS_ASYNC) == -1 && errno == ENOMEM); + Show("sendmmsg_vanished_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len); + + uint64_t AccessRegs[32] {}; + AccessRegs[0] = 0x10000; + AccessRegs[2] = 0xfffffffeULL; + auto Decode = [&](const char* Name, uint32_t Insn) { + uint64_t Address {}; + uint32_t Size {}; + bool Plain {}; + const bool Known = DecodeAccess(Insn, AccessRegs, &Address, &Size, &Plain); + std::printf("decode_%s_known %x\n", Name, Known); + std::printf("decode_%s_offset %llx\n", Name, static_cast(Address - AccessRegs[0])); + std::printf("decode_%s_size %x\n", Name, Size); + std::printf("decode_%s_plain %x\n", Name, Plain); + }; + Decode("str_x_imm", 0xf9000401); + Decode("ldr_x_pre", 0xf85fcc01); + Decode("ldr_x_post", 0xf8408401); + Decode("stur_x", 0xf81fc001); + Decode("ldr_w_lsl", 0xb8627801); + Decode("ldr_w_sxtw", 0xb862c801); + Decode("ldr_w_uxtw", 0xb8624801); + Decode("ldr_w_reserved", 0xb8620801); + Decode("stp_x", 0xa9010c01); + Decode("ldp_w_negative", 0x297f0c01); + Decode("ldp_q_post", 0xacc10c01); + Decode("str_q", 0x3d800401); + Decode("ld1_four", 0x4c402001); + Decode("st1_post", 0x4c9f7c01); + Decode("ld1_lane", 0x0d409001); + Decode("ld4r", 0x4d60e801); + Decode("ldadd", 0xf8210002); + Decode("ldar", 0xc8dffc01); + Decode("casp", 0x48227c04); + Decode("ldxp", 0xc87f0c01); + Decode("ldapur", 0x995fc001); + Decode("ldraa", 0xf8200400); + + auto* Backings = static_cast(mmap(nullptr, 6 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); + const uint64_t Backed = reinterpret_cast(Backings); + const uint64_t SeparateGuest = 0x6f0000000000ULL; + const uint64_t Adjacent = 0x6f0000100000ULL; + AddEntry(SeparateGuest, Page, Backed, false, PROT_READ | PROT_WRITE); + AddEntry(SeparateGuest + Page, Page, Backed + 2 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Adjacent, Page, Backed + 4 * Page, false, PROT_READ | PROT_WRITE); + AddEntry(Adjacent + Page, Page, Backed + 5 * Page, false, PROT_READ | PROT_WRITE); + std::memset(Backings + Page, 0xee, Page); + uint64_t StoreRegs[32] {}; + StoreRegs[0] = SeparateGuest + Page - 4; + StoreRegs[1] = 0x1122334455667788ULL; + uint64_t SplitAddress {}; + uint32_t SplitSize {}; + bool SplitPlain {}; + DecodeAccess(0xf9000001, StoreRegs, &SplitAddress, &SplitSize, &SplitPlain); + AccessPiece SplitPieces[MaxAccessPieces] {}; + const auto SplitParts = PlanAccessLocked(SplitAddress, SplitSize, SplitPieces); + Show("split_access_parts", SplitParts); + Show("split_access_first", SplitPieces[0].Host - Backed); + Show("split_access_second", SplitPieces[1].Host - Backed); + Show("split_access_sizes", SplitPieces[0].Size * 0x10 + SplitPieces[1].Size); + Show("split_access_guests", (SplitPieces[0].Guest == SeparateGuest + Page - 4) * 0x10 + (SplitPieces[1].Guest == SeparateGuest + Page)); + Show("split_access_contiguous", HostContiguous(SplitPieces, SplitParts)); + Show("split_access_store_reachable", PiecesReachable(SplitPieces, SplitParts, true)); + alignas(16) uint8_t Window[96] {}; + const auto WindowOffset = SplitAddress & 15; + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true); + std::memcpy(Window + WindowOffset, &StoreRegs[1], sizeof(StoreRegs[1])); + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false); + uint32_t SplitWords[3] {}; + std::memcpy(&SplitWords[0], Backings + Page - 4, 4); + std::memcpy(&SplitWords[1], Backings + 2 * Page, 4); + std::memcpy(&SplitWords[2], Backings + Page, 4); + Show("split_store_low", SplitWords[0]); + Show("split_store_high", SplitWords[1]); + Show("split_store_neighbour", SplitWords[2]); + std::memset(Window, 0, sizeof(Window)); + CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true); + uint64_t SplitLoaded {}; + std::memcpy(&SplitLoaded, Window + WindowOffset, sizeof(SplitLoaded)); + Show("split_load_value", SplitLoaded); + SplitPieces[1].Prot = PROT_READ; + Show("split_readonly_store", PiecesReachable(SplitPieces, SplitParts, true)); + Show("split_readonly_load", PiecesReachable(SplitPieces, SplitParts, false)); + SplitPieces[1].Prot = PROT_NONE; + Show("split_none_load", PiecesReachable(SplitPieces, SplitParts, false)); + AccessPiece EdgePieces[MaxAccessPieces] {}; + Show("split_unmapped_parts", PlanAccessLocked(SeparateGuest + 2 * Page - 4, 8, EdgePieces)); + Show("split_inside_parts", PlanAccessLocked(SeparateGuest + 16, 64, EdgePieces)); + Show("split_inside_host", EdgePieces[0].Host - Backed); + AccessPiece JoinedPieces[MaxAccessPieces] {}; + const auto JoinedParts = PlanAccessLocked(Adjacent + Page - 4, 8, JoinedPieces); + Show("joined_access_parts", JoinedParts); + Show("joined_access_contiguous", HostContiguous(JoinedPieces, JoinedParts)); + Show("joined_access_delta", JoinedPieces[0].Host - (Adjacent + Page - 4) == Backed + 4 * Page - Adjacent); + + uint64_t OrderedRegs[32] {}; + Show("ordered_load_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs)); + Show("ordered_load_value", OrderedRegs[1]); + OrderedRegs[1] = 0xa1a2a3a4b5b6b7b8ULL; + Show("ordered_store_parts", EmulateOrdered(0xd9000001, SplitPieces, SplitParts, OrderedRegs)); + uint32_t OrderedWords[2] {}; + std::memcpy(&OrderedWords[0], Backings + Page - 4, 4); + std::memcpy(&OrderedWords[1], Backings + 2 * Page, 4); + Show("ordered_store_low", OrderedWords[0]); + Show("ordered_store_high", OrderedWords[1]); + AccessPiece WordPieces[MaxAccessPieces] {}; + const auto WordParts = PlanAccessLocked(SeparateGuest + Page - 2, 4, WordPieces); + OrderedRegs[1] = 0; + Show("ordered_signed_parts", EmulateOrdered(0x99800001, WordPieces, WordParts, OrderedRegs) == WordParts && WordParts == 2); + Show("ordered_signed_value", OrderedRegs[1]); + mprotect(Backings + 2 * Page, Page, PROT_NONE); + OrderedRegs[1] = 0x77; + Show("ordered_fault_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs)); + Show("ordered_fault_untouched", OrderedRegs[1]); + Show("gather_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true)); + Show("scatter_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false)); + mprotect(Backings + 2 * Page, Page, PROT_READ | PROT_WRITE); + Show("gather_whole", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true)); + Show("probe_instruction", ProbeInstruction(16)); + Show("probe_instruction_low", ProbeInstruction(2)); + auto OrderedKind = [](uint32_t Insn) { return static_cast(IsOrderedAccess(Insn)); }; + Show("ordered_kinds", OrderedKind(0xd9400001) << 20 | OrderedKind(0x99800001) << 16 | OrderedKind(0xc8dffc01) << 12 | OrderedKind(0xc89ffc01) << 8 | + OrderedKind(0xf8bfc001) << 4 | OrderedKind(0xf9400001)); + Show("ordered_atomics", OrderedKind(0xf8210002) << 8 | OrderedKind(0x48227c04) << 4 | OrderedKind(0xc87f0c01)); + auto WriteKind = [](uint32_t Insn) { return static_cast(IsWrite(Insn)); }; + Show("write_loads", WriteKind(0xb9800001) << 20 | WriteKind(0x99800001) << 16 | WriteKind(0x39c00001) << 12 | WriteKind(0xf9400001) << 8 | + WriteKind(0x3dc00401) << 4 | WriteKind(0xd9400001)); + Show("write_stores", WriteKind(0xf9000001) << 12 | WriteKind(0xd9000001) << 8 | WriteKind(0x3d800401) << 4 | WriteKind(0x39000001)); + Show("extend_signed_half_w", ExtendOrdered(0x59c00001, 0x8001)); + Show("extend_signed_half_x", ExtendOrdered(0x59800001, 0x8001)); + Show("extend_unsigned_byte", ExtendOrdered(0x19400001, 0x80)); + Show("extend_ldar", ExtendOrdered(0x889ffc01 | (1U << 22), 0x80000000)); + + TestHold Held {}; + std::atomic WriterIn {0}; + uint64_t HoldResults[4] {}; + std::thread Holder([&] { + { + MappingHold Hold {Held}; + Hold.Keep(); + } + HoldResults[0] = Held.Held; + std::thread Writer([&] { + std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; + WriterIn = 1; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + HoldResults[1] = WriterIn.load(); + ReleaseMappings(Held); + Writer.join(); + HoldResults[2] = WriterIn.load() * 0x10 + Held.Held; + { + MappingHold Hold {Held}; + } + HoldResults[3] = ExclusiveFromAnotherThread() * 0x10 + Held.Held; + }); + Holder.join(); + Show("hold_kept_held", HoldResults[0]); + Show("hold_blocks_writer", HoldResults[1]); + Show("hold_released", HoldResults[2]); + Show("hold_scoped", HoldResults[3]); + + struct sigaction TrapAction {}; + TrapAction.sa_sigaction = CountTrap; + TrapAction.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &TrapAction, nullptr); + uint64_t DeferResults[12] {}; + std::thread Deferring([&] { + siginfo_t User {}; + User.si_signo = SIGTRAP; + User.si_code = SI_QUEUE; + User.si_pid = getpid(); + User.si_uid = getuid(); + User.si_value.sival_int = 0x1234; + siginfo_t Breakpoint {}; + Breakpoint.si_signo = SIGTRAP; + Breakpoint.si_code = TRAP_BRKPT; + TestHold Deferred {}; + DeferResults[0] = DeferWhileHeld(Deferred, SIGTRAP, &User); + { + MappingHold Hold {Deferred}; + Hold.Keep(); + } + sigset_t Current; + pthread_sigmask(SIG_BLOCK, nullptr, &Current); + DeferResults[1] = sigismember(&Current, SIGTRAP) * 0x100 + sigismember(&Current, SIGSEGV) * 0x10 + sigismember(&Current, SIGILL); + DeferResults[2] = DeferWhileHeld(Deferred, SIGTRAP, &User) * 0x100 + DeferWhileHeld(Deferred, SIGTRAP, &Breakpoint) * 0x10 + + DeferWhileHeld(Deferred, SIGILL, &User); + DeferResults[3] = TrapsSeen.load(); + DeferResults[4] = ReleaseMappings(Deferred); + DeferResults[5] = TrapsSeen.load() * 0x10 + Deferred.Held; + DeferResults[6] = ExclusiveFromAnotherThread(); + sigset_t Trap; + sigemptyset(&Trap); + sigaddset(&Trap, SIGTRAP); + pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr); + DeferResults[7] = TrapsSeen.load(); + DeferResults[8] = static_cast(TrapCode.load()) * 0x10000ULL + static_cast(TrapValue.load()); + { + MappingHold Hold {Deferred}; + User.si_value.sival_int = 0x5678; + DeferWhileHeld(Deferred, SIGTRAP, &User); + } + DeferResults[9] = TrapsSeen.load(); + pthread_sigmask(SIG_BLOCK, nullptr, &Current); + DeferResults[10] = sigismember(&Current, SIGTRAP); + pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr); + DeferResults[11] = TrapsSeen.load() * 0x10000ULL + static_cast(TrapValue.load()); + }); + Deferring.join(); + Show("defer_unheld", DeferResults[0]); + Show("defer_held_mask", DeferResults[1]); + Show("defer_kinds", DeferResults[2]); + Show("defer_not_run_while_held", DeferResults[3]); + Show("defer_requeued", DeferResults[4]); + Show("defer_after_release", DeferResults[5]); + Show("defer_lock_free", DeferResults[6]); + Show("defer_delivered", DeferResults[7]); + Show("defer_info", DeferResults[8]); + Show("defer_scoped_pending", DeferResults[9]); + Show("defer_scoped_blocked", DeferResults[10]); + Show("defer_scoped_delivered", DeferResults[11]); + const uint64_t Delivering = 0x730000000000ULL; + Map(Delivering, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0); + static int TrapsBefore; + TrapsBefore = TrapsSeen.load(); + FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { + siginfo_t User {}; + User.si_signo = SIGTRAP; + User.si_code = SI_QUEUE; + User.si_pid = getpid(); + User.si_uid = getuid(); + DeferWhileHeld(FEX::HLE::TestThread.HighMemoryTrap.Mappings, SIGTRAP, &User); + }; + const uint32_t DeliveringValue = 0x5a; + Show("guest_store_deferred_result", CopyToGuest(Delivering, &DeliveringValue, sizeof(DeliveringValue))); + Show("guest_store_deferred_delivered", TrapsSeen.load() - TrapsBefore); + sigset_t AfterStore; + pthread_sigmask(SIG_BLOCK, nullptr, &AfterStore); + Show("guest_store_deferred_unblocked", !sigismember(&AfterStore, SIGTRAP)); + Unmap(Delivering, Page); + return 0; +} +""" + + +def added_lines(text, path): + lines = [] + inside = False + for line in text.splitlines(): + if line.startswith("diff --git "): + inside = line.endswith(" b/" + path) + continue + if inside and line.startswith("+") and not line.startswith("+++"): + lines.append(line[1:]) + return lines + + +def block(lines, signature): + start = next(i for i, line in enumerate(lines) if line.lstrip().startswith(signature)) + indent = lines[start][: len(lines[start]) - len(lines[start].lstrip())] + if lines[start].rstrip().endswith(";"): + return lines[start] + end = next(i for i in range(start + 1, len(lines)) if lines[i] in (indent + "}", indent + "};")) + return "\n".join(lines[start:end + 1]) + + +def span(lines, first, stop): + start = next(i for i, line in enumerate(lines) if line.startswith(first)) + end = next(i for i in range(start + 1, len(lines)) if lines[i].startswith(stop)) + return "\n".join(lines[start:end]) + + +def syscall_enum(code): + entries = [] + for name in sorted(set(re.findall(r"SYSCALL_x64_(\w+)", code))): + kernel = KERNEL_NAMES.get(name, name) + fallback = NEWER_SYSCALLS.get(name) + if fallback is None: + entries.append(f"SYSCALL_x64_{name} = __NR_{kernel},") + else: + entries.append(f"#ifdef __NR_{kernel}\nSYSCALL_x64_{name} = __NR_{kernel},\n#else\nSYSCALL_x64_{name} = {fallback},\n#endif") + return "enum Syscalls_x64 : int {\n" + "\n".join(entries) + "\n};" + + +def harness(): + text = PATCH.read_text() + source = added_lines(text, SOURCE) + header = [line for line in added_lines(text, HEADER) if not line.startswith(("#pragma", "#include