From 527cb8586777a9086ed24f84d54c7fd06ae319fc Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Sun, 22 Nov 2026 20:40:30 -0500 Subject: [PATCH 01/17] fix(fex): signal return restores syscall state; CurseForge runs headless (#3040) * fix(fex): signal return restores the interrupted syscall state A guest rt_sigreturn goes through FEX's syscall stub, which marks every static register as spilled. Returning to unchanged JIT code skipped the stub's reset, so later asynchronous signals skipped the register spill and guest handlers read stale registers. CoreCLR's GC suspension reads and redirects that context, which made x86-64 .NET programs fail with random access violations. Restore the value saved at signal entry. * fix(addons): run CurseForge headless from the addon browser, without a session - The CurseForge source starts the app in its own headless gamescope (droiddeck-headless, shared with the Battle.net Agent) instead of a hidden session: no SessionService, compositor output or ImageReader. - The helper's start keeps running until the app exits, so the app lives for as long as the addon browser holds that guest command; closing the dialog asks the app to quit, stops its process group and cancels the command, which ends the app, its gamescope and the guest. - An app the user already has open is reported busy and left alone. - Removes BackgroundSession and the CompositorHost start path it shared with SessionActivity, with their tests. * fix(addons): bind each CurseForge stop to its launch and keep the inspector URL out of logs A stop now only acts on the launch that registered it, so a late stop from a closed browser cannot end a newer launch, and the browser stops once. Command logs redact the inspector URL. The signal probe reports a sender thread that cannot start, sets ECX before the measured region and its test accepts a valid overshoot of the target count. * fix(fex): unblock the probe signal before sampling --- .../com/droiddeck/launcher/SessionActivity.kt | 37 +++- .../launcher/runtime/CurseForgeApp.kt | 101 ++++++--- .../launcher/runtime/GuestCommand.kt | 8 +- .../launcher/session/BackgroundSession.kt | 119 ----------- .../launcher/session/SessionFiles.kt | 1 + .../stores/gog/GogDownloadManager.java | 2 +- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 44 +--- .../launcher/wayland/CompositorHost.kt | 48 ----- .../launcher/runtime/CurseForgeAppTest.kt | 142 ++++++++++++- docs/development/x86-64-steam-client.md | 10 + ...signal-return-restores-syscall-state.patch | 12 ++ tools/fex/probes/async-signal-context.c | 84 ++++++++ .../overlay/usr/local/bin/droiddeck-agent | 23 +- .../overlay/usr/local/bin/droiddeck-battlenet | 31 +-- .../usr/local/bin/droiddeck-curseforge | 65 ++---- .../overlay/usr/local/bin/droiddeck-headless | 24 +++ tools/tests/test_battlenet.py | 19 +- tools/tests/test_curseforge_helper.py | 200 +++++++++++------- tools/tests/test_droiddeck_agent.py | 22 ++ tools/tests/test_fex_signal_syscall_state.py | 76 +++++++ tools/tests/test_hdr_live_switch.py | 10 +- 21 files changed, 663 insertions(+), 415 deletions(-) delete mode 100644 app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt create mode 100644 tools/fex/patches/0008-signal-return-restores-syscall-state.patch create mode 100644 tools/fex/probes/async-signal-context.c create mode 100755 tools/linuxfs/overlay/usr/local/bin/droiddeck-headless create mode 100644 tools/tests/test_fex_signal_syscall_state.py diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index dbbe76ac95..96aeb08be3 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -2846,7 +2846,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!SessionState.running) { SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") } - val output = CompositorHost.prepare(this) + val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } + FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb")) + com.droiddeck.launcher.input.VrControllers.publish(this) + + val turnip = TurnipDriver(this) + com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup") + if (!CompositorHost.isStarted) { + CompositorHost.displayChoice = SessionPrefs.androidDriver(this) + com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this)) + } + val driverId = if (CompositorHost.isStarted) null else turnip.install() val previous = SessionState.outputSize val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) @@ -2873,7 +2883,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pushCardboard(activeCardboard) WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path) com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path) - if (!SessionState.running) CompositorHost.logToSession(this) + if (!SessionState.running) { + val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log") + WaylandCompositor.setSessionLogFile(waylandLog) + try { + android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) + } catch (e: Exception) { + Log.w(TAG, "could not point the compositor's log at $waylandLog", e) + } + } val mode = hdrPrefMode() if (probe != null) { WaylandCompositor.nativeSetHdrDisplay( @@ -2893,8 +2911,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " ยท display ${probe.formats.ifEmpty { "SDR" }}") } - if (!SessionState.running) CompositorHost.applyHdr(this, mode) - CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit()) + if (!SessionState.running) { + val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) + SessionState.hdr = on + WaylandCompositor.nativeSetHdrOutput(on) + WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode)) + Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") + } + com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId") + CompositorHost.startOrAttach( + this, holder.surface, runtimeDir.path, + driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, + applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(), + ) onOutputAttached(holder) if (SessionState.running && size != previous) { Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index 5477c8ede1..adc2119889 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -1,25 +1,29 @@ package com.droiddeck.launcher.runtime import android.content.Context -import com.droiddeck.launcher.agent.AgentException -import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import org.json.JSONArray import org.json.JSONObject import java.time.Instant +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean object CurseForgeApp { const val NAME = "CurseForge" const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml" internal const val WOW = 1 const val HELPER = "/usr/local/bin/droiddeck-curseforge" + internal const val AGENT = "/usr/local/bin/droiddeck-agent" private const val READY_MS = 120_000L private const val INSTALL_MS = 300_000L - enum class Start { READY, BUSY, NO_DISPLAY, FAILED } + enum class Start { READY, BUSY, FAILED } class Started(val state: Start, val inspector: String? = null) - private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") + internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") class Failure(message: String, val code: String? = null) : Exception(message) { val gone get() = code == "DEVTOOLS_UNREACHABLE" @@ -31,14 +35,19 @@ object CurseForgeApp { internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") } - fun holdArgs(app: UserApps.App): List? = dir(app)?.let { listOf("hold", it) } + internal fun helperArgv(command: String, dir: String): List = listOf(HELPER, command, dir) + + internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List = + listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression) + + internal fun lastJson(lines: List): JSONObject? = + lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() } internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) } internal fun startState(exitCode: Int): Start = when (exitCode) { 0 -> Start.READY 3 -> Start.BUSY - 4 -> Start.NO_DISPLAY else -> Start.FAILED } @@ -137,47 +146,75 @@ object CurseForgeApp { return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet() } - private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? { - val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true) - .put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0) - return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true)) + internal var guest: (Context, List, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine -> + GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true, + cancelled = cancelled, redact = INSPECTOR, onLine = onLine) } - private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? { - val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0) - return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull() + private val holds = ConcurrentHashMap() + + private fun lines(context: Context, argv: List): List { + val out = ArrayList() + guest(context, argv, null) { out += it } + return out } - fun start(context: Context, app: UserApps.App): Started { + private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? = + unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer")) + + private sealed class Launch { + class Url(val inspector: String) : Launch() + class Exit(val code: Int) : Launch() + } + + private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? { + val first = LinkedBlockingQueue() + Thread({ + val code = runCatching { + guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } } + }.getOrDefault(-1) + first.offer(Launch.Exit(code)) + }, "curseforge-headless").apply { isDaemon = true; start() } + return first.poll(READY_MS, TimeUnit.MILLISECONDS) + } + + fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started { val dir = dir(app) ?: return Started(Start.FAILED) - val answer = helper(context, "start", dir, 90_000) - if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) { - stop(context, app, null) - return Started(Start.FAILED) + if (hold.get()) return Started(Start.FAILED) + holds.put(dir, hold)?.takeIf { it !== hold }?.let { + it.set(true) + runCatching { lines(context, helperArgv("stop", dir)) } } - val state = startState(answer.optInt("exitCode", -1)) - if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state) - val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty()) - if (state != Start.READY || inspector == null) { - stop(context, app, null) + val inspector = when (val first = launch(context, dir, hold)) { + is Launch.Url -> first.inspector + is Launch.Exit -> if (startState(first.code) == Start.BUSY) { + holds.remove(dir, hold) + return Started(Start.BUSY) + } else null + null -> null + } + if (inspector == null) { + stop(context, app, null, hold) return Started(Start.FAILED) } val deadline = System.currentTimeMillis() + READY_MS - while (System.currentTimeMillis() < deadline) { - val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) } - if (ready.isSuccess) return Started(Start.READY, inspector) - val error = ready.exceptionOrNull() - if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break + while (System.currentTimeMillis() < deadline && !hold.get()) { + if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector) Thread.sleep(1_000) } - stop(context, app, inspector) + stop(context, app, inspector, hold) return Started(Start.FAILED) } - fun stop(context: Context, app: UserApps.App, inspector: String?) { + fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) { val dir = dir(app) ?: return + if (holds[dir] !== hold) { + hold.set(true) + return + } if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") } - helper(context, "stop", dir, 30_000) + hold.set(true) + if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) } } private fun connect(context: Context, inspector: String) { @@ -207,7 +244,7 @@ object CurseForgeApp { while (System.currentTimeMillis() < deadline) { val listed = runCatching { installed(context, inspector, guid) } val error = listed.exceptionOrNull() - if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error + if (error is Failure && error.gone) throw error if (projectId in listed.getOrDefault(emptySet())) return true Thread.sleep(1_000) } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt index 95ea5b13c9..2c5fbad51e 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt @@ -14,20 +14,22 @@ import java.util.concurrent.atomic.AtomicBoolean object GuestCommand { fun run(context: Context, argv: List, fakeRoot: Boolean = false, logName: String? = null, linkDir: File? = null, extraBinds: List? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, - onLine: (String) -> Unit): Int { + redact: Regex? = null, onLine: (String) -> Unit): Int { val log = logName?.let { try { File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter() } catch (e: Exception) { null } } - log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}") + log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}") try { - return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) } + return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) } } finally { log?.close() } } + internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "") ?: text + private fun runLogged(context: Context, argv: List, fakeRoot: Boolean, linkDir: File?, extraBinds: List?, fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { val root = LinuxRuntime.rootDir(context) diff --git a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt b/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt deleted file mode 100644 index 50c60f5747..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/BackgroundSession.kt +++ /dev/null @@ -1,119 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.Context -import android.graphics.PixelFormat -import android.media.ImageReader -import android.os.Handler -import android.os.Looper -import android.util.Log -import com.droiddeck.launcher.agent.AgentGuest -import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller -import com.droiddeck.launcher.storage.StorageState -import com.droiddeck.launcher.wayland.CompositorHost -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit -import java.util.concurrent.atomic.AtomicBoolean - -object BackgroundSession { - private const val TAG = "BackgroundSession" - private const val WIDTH = 1280 - private const val HEIGHT = 720 - private const val REFRESH_HZ = 60f - private const val BEGIN_MS = 30_000L - private const val AGENT_MS = 120_000L - private const val STOP_MS = 30_000L - private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED) - private val main by lazy { Handler(Looper.getMainLooper()) } - private var reader: ImageReader? = null - - fun start(context: Context, program: String, args: List): String? { - val app = context.applicationContext - val claim = AtomicBoolean(false) - val began = CountDownLatch(1) - var own: String? = null - main.post { - if (claim.compareAndSet(false, true)) { - own = runCatching { begin(app, program, args) } - .onFailure { Log.w(TAG, "could not start a hidden session for $program", it) } - .getOrNull() - } - began.countDown() - } - if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null - began.await() - val session = own ?: return null - val deadline = System.currentTimeMillis() + AGENT_MS - val settle = System.currentTimeMillis() + 5_000 - while (System.currentTimeMillis() < deadline) { - if (SessionState.sessionId != session) return null - if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session - if (SessionState.phase == SessionPhase.FAILED) break - if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break - Thread.sleep(250) - } - stop(app, session) - return null - } - - fun stop(context: Context, session: String) { - val app = context.applicationContext - if (SessionState.sessionId != session) return - main.post { if (SessionState.sessionId == session) SessionService.stop(app) } - val deadline = System.currentTimeMillis() + STOP_MS - while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250) - if (!live(session)) { - main.post { release() } - return - } - Thread { - while (live(session)) Thread.sleep(1_000) - main.post { release() } - }.start() - } - - private fun live(session: String) = - SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended) - - private fun begin(context: Context, program: String, args: List): String? { - if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() || - SessionState.installing != null || StorageState.cleaning) return null - release() - SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program)) - val session = SessionState.sessionId ?: return null - SessionState.stopRequested = false - SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") - var requested = false - try { - val output = CompositorHost.prepare(context) - val size = WIDTH to HEIGHT - SessionState.outputSize = size - SessionState.refreshHz = REFRESH_HZ - CompositorHost.logToSession(context) - CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN)) - val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2) - reader = offscreen - offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main) - CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0) - CompositorHost.detach(offscreen.surface) - SessionEvents.record("compositor.started") - SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting") - requested = true - SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray()) - return session - } catch (e: Exception) { - if (requested) SessionService.stop(context) - if (!SessionState.running) { - reader?.close() - reader = null - SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString())) - } - throw e - } - } - - private fun release() { - if (SessionState.running) return - reader?.close() - reader = null - } -} 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 afb8fcb8d4..34d96eab4b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -181,6 +181,7 @@ object SessionFiles { "usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run", "usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec", "usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge", + "usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless", "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java index a09629bc4c..8864bdaf75 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogDownloadManager.java @@ -330,7 +330,7 @@ public final class GogDownloadManager { rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList( "/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", guestDir, guestSetup), - false, "gog-innoextract", null, null, false, cancelled, + false, "gog-innoextract", null, null, false, cancelled, null, line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; }); } catch (Exception e) { throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName()); diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index b8fa6c6278..514677364c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -67,14 +67,13 @@ import com.droiddeck.launcher.runtime.CurseForgeApp import com.droiddeck.launcher.runtime.UserApps import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons -import com.droiddeck.launcher.session.BackgroundSession -import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.util.concurrent.atomic.AtomicBoolean private class AddonResults { val items = mutableStateListOf() @@ -95,10 +94,7 @@ private class CurseLink(val app: UserApps.App) { private val lock = Object() @Volatile private var closed = false - private var held = false - private var ownSession: String? = null - private var started = false - @Volatile private var launching = false + @Volatile private var hold: AtomicBoolean? = null @Volatile private var inspector: String? = null private val guids = HashMap() @@ -119,29 +115,13 @@ private class CurseLink(val app: UserApps.App) { private fun link(context: Context, target: WowAddons.Target): Linked { if (closed) throw CurseState() - if (!SessionState.running) { - started = false - launching = false - held = false - ownSession = null - inspector = null - guids.clear() - val args = CurseForgeApp.holdArgs(app) ?: throw CurseState() - ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState() - } - if (closed) throw CurseState() - if (!held) { - held = true - SessionService.holdForSignIn(context, true) - } - val awake = System.currentTimeMillis() + 30_000 - while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250) val url = inspector ?: run { - launching = true - val done = CurseForgeApp.start(context, app) + val launch = AtomicBoolean(false) + hold = launch + if (closed) throw CurseState() + val done = CurseForgeApp.start(context, app, launch) when (done.state) { CurseForgeApp.Start.READY -> { - started = true inspector = done.inspector done.inspector ?: throw CurseState() } @@ -160,17 +140,11 @@ private class CurseLink(val app: UserApps.App) { fun close(context: Context) { closed = true + val launch = hold ?: return Thread { - if (launching) CurseForgeApp.stop(context, app, inspector) + CurseForgeApp.stop(context, app, inspector, launch) synchronized(lock) { - if (started) CurseForgeApp.stop(context, app, inspector) - val owned = ownSession - if (owned != null) BackgroundSession.stop(context, owned) - else if (held) SessionService.holdForSignIn(context, false) - started = false - launching = false - ownSession = null - held = false + hold = null inspector = null } }.start() diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 89ae2b1cb3..8d43d09c7b 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -10,8 +10,6 @@ import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState object CompositorHost { - private const val TAG = "DroidDeck" - @Volatile private var started = false @@ -57,52 +55,6 @@ object CompositorHost { } } - class Output internal constructor( - internal val runtimeDir: java.io.File, - internal val turnip: com.droiddeck.launcher.gpu.TurnipDriver, - internal val driverId: String?, - ) - - fun prepare(context: android.content.Context): Output { - val runtimeDir = java.io.File(context.filesDir, ".wayland-rt").apply { mkdirs() } - com.droiddeck.launcher.core.FileUtils.copyAsset(context, "wayland/keymap.xkb", java.io.File(runtimeDir, "keymap.xkb")) - com.droiddeck.launcher.input.VrControllers.publish(context) - val turnip = com.droiddeck.launcher.gpu.TurnipDriver(context) - com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "surface.driver-setup") - if (!started) { - displayChoice = SessionPrefs.androidDriver(context) - com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(context, SessionPrefs.androidDriver(context)) - } - return Output(runtimeDir, turnip, if (started) null else turnip.install()) - } - - fun logToSession(context: android.content.Context) { - val waylandLog = java.io.File(com.droiddeck.launcher.session.SessionPaths.beginOrCurrent(context), "wayland.log") - WaylandCompositor.setSessionLogFile(waylandLog) - try { - android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) - } catch (e: Exception) { - android.util.Log.w(TAG, "could not point the compositor's log at $waylandLog", e) - } - } - - fun applyHdr(context: android.content.Context, mode: String) { - val on = SessionState.hdrCapable && SessionPrefs.hdr(context, mode) - SessionState.hdr = on - WaylandCompositor.nativeSetHdrOutput(on) - WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(context, mode)) - android.util.Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session") - } - - fun start(context: android.content.Context, output: Output, surface: Surface, size: Pair, refreshHz: Float, fpsLimit: Int): Boolean { - com.droiddeck.launcher.gpu.DriverSetupLog.write(context, "compositor.start driver=${output.driverId}") - return startOrAttach( - context, surface, output.runtimeDir.path, - output.driverId?.let { output.turnip.driverPath(it) }, output.driverId?.let { output.turnip.libraryName(it) }, - context.applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz, fpsLimit, - ) - } - @Synchronized fun startOrAttach( context: android.content.Context, diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index 98cdd9376f..e3cb7ef501 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -8,6 +8,7 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue +import org.junit.After import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -21,6 +22,47 @@ import java.io.File class CurseForgeAppTest { @get:Rule val temp = TemporaryFolder() + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + + @After + fun restoreGuest() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + launches.forEach { CurseForgeApp.stop(context, app, null, it) } + holder.get()?.set(true) + CurseForgeApp.guest = original + } + + private val launches = mutableListOf() + + private fun launch(): java.util.concurrent.atomic.AtomicBoolean = java.util.concurrent.atomic.AtomicBoolean(false).also { launches += it } + + private val holder = java.util.concurrent.atomic.AtomicReference() + private val released = java.util.concurrent.CountDownLatch(1) + + private fun fakeGuest(startExit: Int, ready: Boolean = true): MutableList> { + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + if (startExit == 0) { + holder.set(cancelled) + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + released.countDown() + } else onLine("busy") + startExit + } + argv[0] == CurseForgeApp.HELPER -> 0 + ready -> { onLine(JSONObject().put("ok", true).put("value", """{"value":true}""").toString()); 0 } + else -> { onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "no")).toString()); 0 } + } + } + return calls + } + private val search = """{"success":true,"injectedCount":0, "pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150}, "mods":[ @@ -129,7 +171,7 @@ class CurseForgeAppTest { assertEquals(emptySet(), CurseForgeApp.projectIds(JSONObject())) assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) - assertEquals(CurseForgeApp.Start.NO_DISPLAY, CurseForgeApp.startState(4)) + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4)) assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(5)) } @@ -158,4 +200,102 @@ class CurseForgeAppTest { assertEquals(File(root, target.flavor), WowAddons.flavorDir(target)) } } + + @Test + fun theAppStartsInTheGuestWithoutASessionAndIsAskedThroughItsInspector() { + val calls = fakeGuest(0) + val started = CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()) + assertEquals(CurseForgeApp.Start.READY, started.state) + assertEquals(url, started.inspector) + assertEquals(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge"), calls.first()) + val probe = calls[1] + assertEquals(listOf(CurseForgeApp.AGENT, "--cdp-inspector", url), probe.take(3)) + assertEquals("10.0", probe[3]) + assertTrue(probe[4].contains("InstalledProjectsAppService")) + } + + @Test + fun theLaunchLivesUntilItIsStopped() { + fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.start(context, app, hold).state) + assertEquals(false, holder.get()?.get()) + assertEquals(1L, released.count) + CurseForgeApp.stop(context, app, url, hold) + assertTrue(released.await(5, java.util.concurrent.TimeUnit.SECONDS)) + } + + @Test + fun anAppThatIsAlreadyOpenIsNeitherUsedNorStopped() { + val calls = fakeGuest(3) + assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, launch()).state) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "start", "/root/apps/curseforge")), calls) + } + + @Test + fun stoppingAsksTheAppToQuitThenStopsItsHeadlessLaunchOnce() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val hold = launch() + CurseForgeApp.start(context, app, hold) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertEquals(CurseForgeApp.AGENT, calls[0][0]) + assertTrue(calls[0][4].contains("shutdown")) + assertEquals(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge"), calls[1]) + assertTrue(hold.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun aLateStopLeavesTheNewerLaunchRunning() { + val calls = fakeGuest(0) + val context = org.robolectric.RuntimeEnvironment.getApplication() + val old = launch() + val newer = launch() + CurseForgeApp.start(context, app, old) + CurseForgeApp.start(context, app, newer) + assertTrue(old.get()) + calls.clear() + CurseForgeApp.stop(context, app, url, old) + assertTrue(calls.isEmpty()) + assertEquals(false, newer.get()) + CurseForgeApp.stop(context, app, null, newer) + assertEquals(listOf(listOf(CurseForgeApp.HELPER, "stop", "/root/apps/curseforge")), calls) + } + + @Test + fun aStoppedLaunchNeverStarts() { + val calls = fakeGuest(0) + val hold = launch().apply { set(true) } + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), app, hold).state) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAppWithoutADirectoryIsNeverLaunched() { + val calls = fakeGuest(0) + val bare = UserApps.App("appimage:d", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED) + val hold = launch() + assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.start(org.robolectric.RuntimeEnvironment.getApplication(), bare, hold).state) + CurseForgeApp.stop(org.robolectric.RuntimeEnvironment.getApplication(), bare, url, hold) + assertTrue(calls.isEmpty()) + } + + @Test + fun theInspectorUrlIsRedactedFromCommandLogs() { + val line = CurseForgeApp.evalArgv(url, "x", 1_000).joinToString(" ") + assertTrue(line.contains(url)) + assertTrue(!GuestCommand.redacted(line, CurseForgeApp.INSPECTOR).contains("127.0.0.1")) + assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url)) + } + + @Test + fun theAgentAnswerIsTheLastJsonLine() { + assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v")) + assertNull(CurseForgeApp.lastJson(listOf("noise"))) + } } diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 87b92e5ac5..3d7876c2f5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -219,6 +219,16 @@ alone would then read as an installed client. - `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. + - `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 + the mark stayed. Every asynchronous signal after that (until the next system call ended) skipped the + register spill and handed the guest handler stale registers from the last system call: only RIP was + right. CoreCLR suspends threads for the GC with such signals and reads or redirects the interrupted + context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran + next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in + 2000 carried the interrupted registers, natively all of them. The return now restores the value saved + when the signal arrived. - **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/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch new file mode 100644 index 0000000000..6a8e14e1d0 --- /dev/null +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -0,0 +1,12 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +index b4c7b24..e6777aa 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -262,6 +262,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr + + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; ++ Frame->InSyscallInfo = Context->InSyscallInfo; + + if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { + // XXX: Unsupported since it needs state reconstruction diff --git a/tools/fex/probes/async-signal-context.c b/tools/fex/probes/async-signal-context.c new file mode 100644 index 0000000000..9c2c262a5b --- /dev/null +++ b/tools/fex/probes/async-signal-context.c @@ -0,0 +1,84 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +volatile long base; +static volatile long hits, matched, stale, stop; +static long want; +static pid_t target; +extern char probe_loop_start[], probe_loop_end[]; + +static void handler(int sig, siginfo_t *info, void *context) { + greg_t *g = ((ucontext_t *)context)->uc_mcontext.gregs; + (void)sig; + (void)info; + if (g[REG_RIP] >= (greg_t)probe_loop_start && g[REG_RIP] < (greg_t)probe_loop_end) { + long below = base - g[REG_RSP]; + if (g[REG_RBX] == 0x1111111111111111L && g[REG_R12] == 0x2222222222222222L && g[REG_R13] == 0x3333333333333333L && + g[REG_R14] == 0x4444444444444444L && g[REG_R15] == 0x5555555555555555L && (unsigned long)g[REG_RCX] <= 4096 && + (below == 0 || below == 8)) + matched++; + else + stale++; + } + hits++; +} + +static void *sender(void *arg) { + (void)arg; + while (!stop) { + syscall(SYS_tgkill, getpid(), target, SIGUSR1); + usleep(50); + } + return NULL; +} + +int main(int argc, char **argv) { + struct sigaction action = {0}; + pthread_t thread; + want = argc > 1 ? atol(argv[1]) : 2000; + action.sa_sigaction = handler; + action.sa_flags = SA_SIGINFO | SA_RESTART; + sigaction(SIGUSR1, &action, NULL); + sigset_t usr1; + sigemptyset(&usr1); + sigaddset(&usr1, SIGUSR1); + pthread_sigmask(SIG_UNBLOCK, &usr1, NULL); + target = syscall(SYS_gettid); + if (pthread_create(&thread, NULL, sender, NULL) != 0) { + fprintf(stderr, "cannot start the signal sender\n"); + return 2; + } + while (matched + stale < want) { + __asm__ volatile("mov $0x1111111111111111, %%rbx\n" + "mov $0x2222222222222222, %%r12\n" + "mov $0x3333333333333333, %%r13\n" + "mov $0x4444444444444444, %%r14\n" + "mov $0x5555555555555555, %%r15\n" + "mov %%rsp, base(%%rip)\n" + "mov $4096, %%ecx\n" + ".globl probe_loop_start\n" + "probe_loop_start:\n" + "push %%rax\n" + "1: dec %%ecx\n" + "jnz 1b\n" + "pop %%rax\n" + "mov $4096, %%ecx\n" + "2: dec %%ecx\n" + "jnz 2b\n" + ".globl probe_loop_end\n" + "probe_loop_end:\n" + : + : + : "rbx", "rcx", "r12", "r13", "r14", "r15", "memory"); + } + stop = 1; + pthread_join(thread, NULL); + printf("signals=%ld matched=%ld stale=%ld\n", hits, matched, stale); + return stale ? 1 : 0; +} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 4edfc22cb0..df0f4cedf1 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -1206,6 +1206,15 @@ def handle(agent_dir, req): raise AgentError("UNKNOWN_REQUEST", "Unknown agent request '%s'" % kind) +def reply(agent_dir, req): + try: + return dict(handle(agent_dir, req), ok=True) + except AgentError as e: + return {"ok": False, "error": {"code": e.code, "message": str(e)}} + except Exception as e: + return {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + + def answer(agent_dir, path): rid = path.stem try: @@ -1225,12 +1234,7 @@ def answer(agent_dir, path): except OSError: pass if req is not None: - try: - result = dict(handle(agent_dir, req), ok=True) - except AgentError as e: - result = {"ok": False, "error": {"code": e.code, "message": str(e)}} - except Exception as e: - result = {"ok": False, "error": {"code": "AGENT_FAILED", "message": "%s: %s" % (type(e).__name__, e)}} + result = reply(agent_dir, req) write_json(agent_dir / "resp" / (rid + ".json"), result) @@ -1257,6 +1261,13 @@ def serve(agent_dir, focus=True, poll=0.1): def main(argv): + if argv and argv[0] == "--cdp-inspector": + if len(argv) != 4: + print("usage: droiddeck-agent --cdp-inspector ", file=sys.stderr) + return 2 + print(json.dumps(reply(Path("/"), {"kind": "cdp", "inspector": argv[1], "timeout": argv[2], + "expression": argv[3], "commandLineApi": True}))) + return 0 base = os.environ.get("DD_LAUNCH_DIR") if not base: print("DD_LAUNCH_DIR is not set", file=sys.stderr) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 0cddb3fb4b..d24ead6eb5 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -79,8 +79,7 @@ AGENT_START = 90 AGENT_HELPER = "agent.js" AGENT_RUNTIME = "agent-runtime" AGENT_LOG = "agent.log" -AGENT_LOG_LIMIT = 4 << 20 -HEADLESS = ["--backend", "headless", "-w", "640", "-h", "480"] +HEADLESS = "/usr/local/bin/droiddeck-headless" PRODUCT = re.compile(r"[a-z0-9_]{1,32}") LOCALE = re.compile(r"[a-z]{2}[A-Z]{2}") COUNTRY = re.compile(r"[A-Z]{3}") @@ -1416,33 +1415,23 @@ def agent_job(root, action, uid, product="", folder="", locale="enUS", country=" windows = install_path(root, folder) emit("STATE", "starting") base = os.path.join(CACHE, "agent-%s" % uid) + os.makedirs(CACHE, exist_ok=True) for suffix in (".json", ".game", ".form", ".error"): try: os.unlink(base + suffix) except OSError: pass - runtime = os.path.join(CACHE, AGENT_RUNTIME) - os.makedirs(runtime, mode=0o700, exist_ok=True) env = agent_env() - for name in ("DISPLAY", "WAYLAND_DISPLAY"): - env.pop(name, None) - env["XDG_RUNTIME_DIR"] = runtime - cmd = ["gamescope"] + HEADLESS + ["--", os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", - windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] + cmd = [HEADLESS, os.path.join(CACHE, AGENT_RUNTIME), "--log", os.path.join(CACHE, AGENT_LOG), "--", + os.path.abspath(sys.argv[0]), "agent-serve", action, uid, product or "-", + windows or "-", locale, country, region, "Z:" + base.replace("/", "\\")] say("%s %s through the Agent: %s" % (action, uid, " ".join(cmd))) - output = os.path.join(CACHE, AGENT_LOG) - try: - if os.path.getsize(output) > AGENT_LOG_LIMIT: - os.replace(output, output + ".1") - except OSError: - pass before = {pid for pid, _ in wine_processes(pfx)} - with open(output, "ab") as log: - try: - child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=log, stderr=log, env=env) - except OSError as error: - emit("ERROR", "stopped gamescope: %s" % error) - return 1 + try: + child = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env) + except OSError as error: + emit("ERROR", "stopped gamescope: %s" % error) + return 1 seen = None mark = None moved = time.monotonic() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge index a329c15862..de334b7453 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-curseforge @@ -5,39 +5,17 @@ self=${BASH_SOURCE[0]} proc=${DD_PROC:-/proc} state=${DD_CURSEFORGE_STATE:-${XDG_RUNTIME_DIR:-/tmp}/droiddeck-curseforge} runner=${DD_APPIMAGE_RUN:-${self%/*}/droiddeck-appimage-run} +headless=${DD_HEADLESS_RUN:-${self%/*}/droiddeck-headless} wait_s=${DD_CURSEFORGE_WAIT:-60} cmd=${1:-} dir=${2:-} flag=--inspect-publish-uid=stderr -case $cmd in start|hold|stop|display) ;; *) echo "usage: droiddeck-curseforge start|hold|stop|display " >&2; exit 2 ;; esac -if [ "$cmd" != display ] && [ ! -d "$dir/app" ]; then +case $cmd in start|stop) ;; *) echo "usage: droiddeck-curseforge start|stop " >&2; exit 2 ;; esac +if [ ! -d "$dir/app" ]; then echo "droiddeck-curseforge: $dir is not an imported AppImage" >&2 exit 2 fi -x_display() { - if [ -n "${DISPLAY:-}" ]; then - printf '%s\n%s\n' "$DISPLAY" "${XAUTHORITY:-}" - return 0 - fi - local p name a prev display auth - for p in "$proc"/[0-9]*; do - name=$(tr '\0' '\n' 2>/dev/null < "$p/cmdline" | head -n 1) - case ${name##*/} in Xwayland|Xorg|Xvfb) ;; *) continue ;; esac - display= auth= prev= - while IFS= read -r a; do - case $a in :[0-9]*) [ -z "$display" ] && display=$a ;; esac - [ "$prev" = -auth ] && auth=$a - prev=$a - done < <(tr '\0' '\n' 2>/dev/null < "$p/cmdline") - if [ -n "$display" ]; then - printf '%s\n%s\n' "$display" "$auth" - return 0 - fi - done - return 1 -} - running() { local p for p in "$proc"/[0-9]*; do @@ -79,7 +57,7 @@ inspector() { } start() { - local shown display auth url pid + local url pid child= lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; } if ! ours >/dev/null; then if tracked >/dev/null || running; then @@ -87,18 +65,18 @@ start() { echo busy return 3 fi - shown=$(x_display) || { exec 9>&-; echo "no X display" >&2; return 4; } - display=$(sed -n 1p <<<"$shown") - auth=$(sed -n 2p <<<"$shown") - env -u DBUS_SESSION_BUS_ADDRESS -u WAYLAND_DISPLAY -u GAMESCOPE_WAYLAND_DISPLAY DISPLAY="$display" ${auth:+XAUTHORITY="$auth"} \ - setsid "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" "$state/log" 2>&1 9>&- & + mv -f "$state/log" "$state/log.1" 2>/dev/null + env -u DBUS_SESSION_BUS_ADDRESS setsid "$headless" "$state/runtime" --log "$state/log" -- \ + "$runner" "$dir" --minimized --inspect=127.0.0.1:0 "$flag" /dev/null 2>&1 9>&- & pid=$! + child=$pid printf '%s %s %s\n' "$pid" "$(started_at "$pid")" "$dir" > "$state/pid" fi exec 9>&- for _ in $(seq 1 $((wait_s * 2))); do if url=$(inspector); then echo "$url" + hold "$child" return 0 fi ours >/dev/null || break @@ -108,6 +86,18 @@ start() { return 5 } +hold() { + local pid + if [ -n "$1" ]; then + wait "$1" + return 0 + fi + pid=$(ours) || return 0 + while kill -0 "$pid" 2>/dev/null && [ "$(ours)" = "$pid" ]; do + sleep 1 + done +} + stop() { local pid p lock || return 1 @@ -118,6 +108,7 @@ stop() { sleep 0.5 done kill -KILL -- "-$pid" 2>/dev/null + kill -KILL "$pid" 2>/dev/null for p in "$proc"/[0-9]*; do tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && kill -KILL "${p##*/}" 2>/dev/null done @@ -127,22 +118,10 @@ stop() { } case $cmd in - display) - x_display || exit 4 - ;; start) start exit $? ;; - hold) - start >/dev/null || exit $? - trap 'stop; exit 0' TERM INT HUP - while ours >/dev/null; do - sleep 1 & - wait $! - done - exit 0 - ;; stop) stop exit 0 diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless new file mode 100755 index 0000000000..c8bc6cee0b --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-headless @@ -0,0 +1,24 @@ +#!/bin/bash +set -u +runtime=${1:-} +shift +log= +if [ "${1:-}" = --log ]; then + log=${2:-} + shift 2 +fi +if [ -z "$runtime" ] || [ "${1:-}" != -- ] || [ $# -lt 2 ]; then + echo "usage: droiddeck-headless [--log ] -- [args...]" >&2 + exit 2 +fi +shift +umask 077 +mkdir -p "$runtime" && chmod 700 "$runtime" || exit 1 +if [ -n "$log" ]; then + size=$(stat -c %s "$log" 2>/dev/null || echo 0) + [ "$size" -gt "${DD_HEADLESS_LOG_LIMIT:-4194304}" ] && mv -f "$log" "$log.1" + exec >>"$log" 2>&1 +fi +unset DISPLAY WAYLAND_DISPLAY GAMESCOPE_WAYLAND_DISPLAY XAUTHORITY +export XDG_RUNTIME_DIR=$runtime +exec gamescope --backend headless -w 640 -h 480 -- "$@" diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index 52ba9e8d46..b7bbafa3b4 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -1413,7 +1413,8 @@ class AgentJobTest(Harness): self.assertEqual(code, 0) self.assertTrue(os.path.isdir(folder)) cmd = self.started[0] - self.assertEqual(cmd[:6], ["gamescope", "--backend", "headless", "-w", "640", "-h"]) + self.assertEqual(cmd[:4], ["/usr/local/bin/droiddeck-headless", str(self.tmp / "cache" / "agent-runtime"), "--log", + str(self.tmp / "cache" / "agent.log")]) self.assertEqual(cmd[cmd.index("--") + 2:-1], ["agent-serve", "install", "gryphon", "gryphon", "Z:" + folder, "enUS", "USA", "US"]) self.assertEqual([kind for kind, _ in self.lines], ["STATE", "PROGRESS", "DONE"]) self.assertEqual(json.loads(self.lines[-1][1]), {"install_dir": "Z:" + folder, "exe": "WarcraftRumble.exe", "version": "16.1.2.119725"}) @@ -1641,16 +1642,6 @@ class AgentJobTest(Harness): path.write_bytes(json.dumps({"state": 1004}).encode("utf-8")) self.assertEqual(BNET["read_status"](str(path)), {"state": 1004}) - def test_a_large_agent_log_is_rotated_before_a_job(self): - self.install() - os.makedirs(self.tmp / "cache") - log = self.tmp / "cache" / "agent.log" - log.write_bytes(b"x" * (BNET["AGENT_LOG_LIMIT"] + 1)) - self.files = {".game": json.dumps({"installed": False})} - BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertEqual((self.tmp / "cache" / "agent.log.1").stat().st_size, BNET["AGENT_LOG_LIMIT"] + 1) - self.assertEqual(log.stat().st_size, 0) - def test_it_queues_behind_another_battle_net_job(self): self.install() self.files = {".game": json.dumps({"installed": False})} @@ -1681,13 +1672,11 @@ class AgentJobTest(Harness): self.assertEqual(self.lines[0], ("STATE", "waiting")) self.assertEqual(self.lines[1], ("STATE", "starting")) - def test_gamescope_gets_no_display_but_the_agent_keeps_the_one_gamescope_gives_it(self): + def test_the_agent_keeps_the_display_gamescope_gives_it_and_launches_through_the_shared_headless_helper(self): self.install() - os.environ.update(DISPLAY=":5", WAYLAND_DISPLAY="wayland-1") self.files = {".game": json.dumps({"installed": False})} BNET["agent_job"](self.root, "uninstall", "gryphon", poll=0) - self.assertNotIn("DISPLAY", self.envs[0]) - self.assertNotIn("WAYLAND_DISPLAY", self.envs[0]) + self.assertEqual(self.started[0][0], BNET["HEADLESS"]) self.assertEqual(self.envs[0]["PROTON_USE_XALIA"], "0") os.environ["DISPLAY"] = ":0" self.assertEqual(BNET["agent_env"]()["DISPLAY"], ":0") diff --git a/tools/tests/test_curseforge_helper.py b/tools/tests/test_curseforge_helper.py index 4dd25790db..e65388405d 100644 --- a/tools/tests/test_curseforge_helper.py +++ b/tools/tests/test_curseforge_helper.py @@ -1,17 +1,67 @@ import os import shlex import shutil -import signal import subprocess import tempfile import time import unittest from pathlib import Path -HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-curseforge" +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +HELPER = BIN / "droiddeck-curseforge" +HEADLESS = BIN / "droiddeck-headless" URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" +class HeadlessTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.bin = self.tmp / "bin" + self.bin.mkdir() + self.seen = self.tmp / "seen" + gamescope = self.bin / "gamescope" + gamescope.write_text( + "#!/bin/bash\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"GAMESCOPE=${GAMESCOPE_WAYLAND_DISPLAY-}\" " + "\"XAUTH=${XAUTHORITY-}\" \"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" + "echo logged-by-gamescope\n" % shlex.quote(str(self.seen))) + gamescope.chmod(0o755) + + def env(self, extra=None): + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", + GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", XAUTHORITY="/run/xauth") + base.update(extra or {}) + return base + + def run_headless(self, *args, env=None): + return subprocess.run(["bash", str(HEADLESS), *args], env=self.env(env), capture_output=True, text=True, timeout=30) + + def test_it_runs_the_command_in_headless_gamescope_with_a_private_runtime_and_no_session_display(self): + runtime = self.tmp / "runtime" + out = self.run_headless(str(runtime), "--", "prog", "arg one") + self.assertEqual(0, out.returncode, out.stderr) + self.assertEqual(["DISPLAY=", "WAYLAND=", "GAMESCOPE=", "XAUTH=", "RUNTIME=%s" % runtime, "--backend", "headless", + "-w", "640", "-h", "480", "--", "prog", "arg one"], self.seen.read_text().splitlines()) + self.assertEqual(0o700, runtime.stat().st_mode & 0o777) + + def test_output_goes_to_the_log_which_rotates_when_large(self): + log = self.tmp / "agent.log" + log.write_bytes(b"x" * 100) + self.assertEqual(0, self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog").returncode) + self.assertTrue(log.read_text().endswith("logged-by-gamescope\n")) + self.assertEqual(100, log.stat().st_size - len("logged-by-gamescope\n")) + self.assertFalse((self.tmp / "agent.log.1").exists()) + self.run_headless(str(self.tmp / "r"), "--log", str(log), "--", "prog", env={"DD_HEADLESS_LOG_LIMIT": "50"}) + self.assertEqual(100 + len("logged-by-gamescope\n"), (self.tmp / "agent.log.1").stat().st_size) + self.assertEqual("logged-by-gamescope\n", log.read_text()) + + def test_bad_arguments_are_refused(self): + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "prog").returncode) + self.assertEqual(2, self.run_headless(str(self.tmp / "r"), "--").returncode) + self.assertEqual(2, self.run_headless().returncode) + + class CurseForgeHelperTest(unittest.TestCase): def setUp(self): self.tmp = Path(tempfile.mkdtemp()) @@ -21,18 +71,23 @@ class CurseForgeHelperTest(unittest.TestCase): self.dir = self.tmp / "curseforge" (self.dir / "app").mkdir(parents=True) self.state = self.tmp / "state" + self.bin = self.tmp / "bin" + self.bin.mkdir() self.runner = self.tmp / "runner" self.seen = self.tmp / "seen" self.runner.write_text( "#!/bin/bash\n" - "printf '%%s\\n' \"DISPLAY=$DISPLAY\" \"XAUTHORITY=${XAUTHORITY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" " - "\"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" \"$@\" > %s\n" + "printf '%%s\\n' \"DISPLAY=${DISPLAY-}\" \"WAYLAND=${WAYLAND_DISPLAY-}\" \"DBUS=${DBUS_SESSION_BUS_ADDRESS-}\" " + "\"RUNTIME=$XDG_RUNTIME_DIR\" \"$@\" > %s\n" "mkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" - "echo 'Debugger listening on %s'\n" - "echo 'For help, see: https://nodejs.org/en/docs/inspector'\n" - "exec sleep 60\n" + "echo 'Debugger listening on %s' >&2\n" + "echo 'For help, see: https://nodejs.org/en/docs/inspector' >&2\n" + "sleep 60\n" % (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL)) self.runner.chmod(0o755) + gamescope = self.bin / "gamescope" + gamescope.write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@"\n') + gamescope.chmod(0o755) def fake(self, pid, *argv): d = self.proc / str(pid) @@ -40,15 +95,27 @@ class CurseForgeHelperTest(unittest.TestCase): (d / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in argv)) def env(self, extra=None): - base = {k: v for k, v in os.environ.items() if k not in ("DISPLAY", "XAUTHORITY")} - base.update(DD_PROC=str(self.proc), DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), - DD_CURSEFORGE_WAIT="10", WAYLAND_DISPLAY="wayland-0", DBUS_SESSION_BUS_ADDRESS="unix:path=/x") + base = dict(os.environ, PATH="%s:%s" % (self.bin, os.environ["PATH"]), DD_PROC=str(self.proc), + DD_CURSEFORGE_STATE=str(self.state), DD_APPIMAGE_RUN=str(self.runner), DD_HEADLESS_RUN=str(HEADLESS), + DD_CURSEFORGE_WAIT="10", DISPLAY=":0", WAYLAND_DISPLAY="wayland-0", XDG_RUNTIME_DIR="/run/user/session", + DBUS_SESSION_BUS_ADDRESS="unix:path=/x") base.update(extra or {}) return base def run_helper(self, *args, env=None): return subprocess.run(["bash", str(HELPER), *args], env=self.env(env), capture_output=True, text=True, timeout=60) + def launch(self, directory=None): + holder = subprocess.Popen(["bash", str(HELPER), "start", str(directory or self.dir)], env=self.env(), + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(self.finish, holder) + return holder, holder.stdout.readline().strip() + + def finish(self, holder): + if holder.poll() is None: + holder.kill() + holder.communicate() + def stop(self): self.run_helper("stop", str(self.dir)) @@ -64,86 +131,56 @@ class CurseForgeHelperTest(unittest.TestCase): time.sleep(0.1) return False - def test_the_desktop_x_display_is_found_from_xwayland(self): - self.fake(40, "/usr/bin/kwin_wayland", ":9") - self.fake(41, "/usr/bin/Xwayland", ":0", "-rootless", "-auth", "/run/droiddeck/xauth_abc", "-listenfd", "5") - out = self.run_helper("display", "") - self.assertEqual(0, out.returncode, out.stderr) - self.assertEqual([":0", "/run/droiddeck/xauth_abc"], out.stdout.splitlines()) - - def test_the_session_display_wins(self): - self.fake(41, "/usr/bin/Xwayland", ":3") - out = self.run_helper("display", "", env={"DISPLAY": ":0"}) - self.assertEqual(":0", out.stdout.splitlines()[0]) - - def test_no_display_is_reported(self): - out = self.run_helper("start", str(self.dir)) - self.assertEqual(4, out.returncode) - def test_a_running_instance_without_the_inspector_is_busy(self): self.fake(50, "/usr/bin/FEX", str(self.dir) + "/app/curseforge", "--no-sandbox") - out = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) + out = self.run_helper("start", str(self.dir)) self.assertEqual(3, out.returncode) self.assertEqual("busy", out.stdout.strip()) self.stop() self.assertTrue((self.proc / "50").exists()) - def test_start_uses_a_random_port_and_a_secret_inspector_url_kept_private(self): - self.fake(41, "/usr/bin/Xwayland", ":0", "-auth", "/run/droiddeck/xauth_abc") - out = self.run_helper("start", str(self.dir)) + def test_start_runs_the_app_in_headless_gamescope_with_a_secret_inspector_and_no_session_display(self): + holder, url = self.launch() self.addCleanup(self.stop) - self.assertEqual(0, out.returncode, out.stderr) - self.assertEqual(URL, out.stdout.strip()) + self.assertEqual(URL, url) seen = self.seen.read_text().splitlines() - self.assertEqual(["DISPLAY=:0", "XAUTHORITY=/run/droiddeck/xauth_abc", "WAYLAND=", "DBUS=", str(self.dir), - "--minimized", "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) + self.assertEqual(["DISPLAY=", "WAYLAND=", "DBUS=", "RUNTIME=%s/runtime" % self.state, str(self.dir), "--minimized", + "--inspect=127.0.0.1:0", "--inspect-publish-uid=stderr"], seen) self.assertEqual(0o700, self.state.stat().st_mode & 0o777) + self.assertEqual(0o700, (self.state / "runtime").stat().st_mode & 0o777) self.assertEqual(0o600, (self.state / "log").stat().st_mode & 0o777) - again = self.run_helper("start", str(self.dir)) - self.assertEqual(URL, again.stdout.strip()) - pid = self.pid() + _, again = self.launch() + self.assertEqual(URL, again) + + def test_start_holds_the_app_until_it_is_stopped(self): + holder, url = self.launch() + self.assertEqual(URL, url) + app = self.pid() + time.sleep(1) + self.assertIsNone(holder.poll()) + os.kill(app, 0) + self.stop() + self.assertEqual(0, holder.wait(timeout=30)) + self.assertTrue(self.gone(app), "the app is still running") + + def test_stop_ends_the_app_and_the_gamescope_it_ran_in(self): + (self.bin / "gamescope").write_text('#!/bin/bash\nwhile [ "$1" != -- ]; do shift; done\nshift\n"$@" &\nwait\n') + self.assertEqual(URL, self.launch()[1]) + gamescope = self.pid() + app = int(next(self.proc.iterdir()).name) + self.assertNotEqual(gamescope, app) + os.kill(app, 0) self.stop() self.assertFalse((self.state / "pid").exists()) - self.assertTrue(self.gone(pid), "the started instance is still running") + self.assertTrue(self.gone(gamescope), "gamescope is still running") + self.assertTrue(self.gone(app), "the app is still running") - def test_hold_keeps_the_app_until_it_is_signalled(self): - held = subprocess.Popen(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - self.addCleanup(self.end, held) - for _ in range(100): - if (self.state / "pid").exists() and self.seen.exists(): - break - time.sleep(0.1) - pid = self.pid() - time.sleep(1) - self.assertIsNone(held.poll()) - held.send_signal(signal.SIGTERM) - self.assertEqual(0, held.wait(timeout=30)) - self.assertTrue(self.gone(pid), "hold left the app running") - self.assertFalse((self.state / "pid").exists()) - - def end(self, held): - if held.poll() is None: - held.send_signal(signal.SIGTERM) - try: - held.wait(timeout=15) - except subprocess.TimeoutExpired: - held.kill() - held.wait() - record = self.state / "pid" - if record.exists(): - try: - os.killpg(self.pid(), signal.SIGKILL) - except (ProcessLookupError, PermissionError): - pass - - def test_a_launch_for_another_directory_is_busy(self): + def test_a_launch_for_another_directory_is_busy_and_left_alone(self): other = self.tmp / "other" (other / "app").mkdir(parents=True) - first = self.run_helper("start", str(self.dir), env={"DISPLAY": ":0"}) self.addCleanup(self.stop) - self.assertEqual(0, first.returncode, first.stderr) - out = self.run_helper("start", str(other), env={"DISPLAY": ":0"}) + self.assertEqual(URL, self.launch()[1]) + out = self.run_helper("start", str(other)) self.assertEqual(3, out.returncode) self.assertEqual("busy", out.stdout.strip()) pid = self.pid() @@ -151,22 +188,25 @@ class CurseForgeHelperTest(unittest.TestCase): self.assertEqual(pid, self.pid()) os.kill(pid, 0) - def test_hold_ends_when_the_app_exits(self): - proc = shlex.quote(str(self.proc)) - self.runner.write_text("#!/bin/bash\nmkdir -p %s/$$ && printf '%%s\\0' bash \"$0\" \"$@\" > %s/$$/cmdline\n" - "echo 'Debugger listening on %s'\nsleep 2\nrm -r %s/$$\n" % (proc, proc, URL, proc)) - out = subprocess.run(["bash", str(HELPER), "hold", str(self.dir)], env=self.env({"DISPLAY": ":0"}), - capture_output=True, text=True, timeout=60) - self.assertEqual(0, out.returncode, out.stderr) + def test_each_launch_starts_a_fresh_log(self): + first, _ = self.launch() + self.stop() + first.wait(timeout=30) + self.addCleanup(self.stop) + self.assertEqual(URL, self.launch()[1]) + self.assertEqual(1, (self.state / "log").read_text().count("Debugger listening")) + self.assertTrue((self.state / "log.1").exists()) def test_stop_without_a_launch_is_quiet(self): out = self.run_helper("stop", str(self.dir)) self.assertEqual(0, out.returncode) self.assertEqual("", out.stderr) + self.assertEqual("", out.stdout) def test_bad_arguments_are_refused(self): self.assertEqual(2, self.run_helper("start", str(self.tmp / "missing")).returncode) self.assertEqual(2, self.run_helper("launch", str(self.dir)).returncode) + self.assertEqual(2, self.run_helper("hold", str(self.dir)).returncode) if __name__ == "__main__": diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index 6bf1b0da8c..72931860b7 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -348,6 +348,28 @@ class AgentTest(unittest.TestCase): self.assertEqual("INVALID_TARGET", caught.exception.code) connect.assert_not_called() + def test_one_shot_inspector_eval_prints_the_session_answer_without_a_launch_dir(self): + import contextlib + import io + url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + seen = {} + + def evaluate(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None, command_line_api=False): + seen.update(expression=expression, timeout=timeout, inspector=inspector, api=command_line_api) + return {"target": "inspector", "type": "string", "value": "ok", "description": None} + + out = io.StringIO() + with patch.dict(os.environ, {}, clear=False), patch.object(agent, "cdp_eval", evaluate), contextlib.redirect_stdout(out): + os.environ.pop("DD_LAUNCH_DIR", None) + self.assertEqual(0, agent.main(["--cdp-inspector", url, "12.5", "1 + 1"])) + self.assertEqual({"target": "inspector", "type": "string", "value": "ok", "description": None, "ok": True}, json.loads(out.getvalue())) + self.assertEqual({"expression": "1 + 1", "timeout": 12.5, "inspector": url, "api": True}, seen) + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(0, agent.main(["--cdp-inspector", "ws://example.com:9229/x", "5", "1"])) + self.assertEqual("INVALID_REQUEST", json.loads(out.getvalue())["error"]["code"]) + self.assertEqual(2, agent.main(["--cdp-inspector", url])) + def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self): class Lost: def __init__(self, *args, **kwargs): diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py new file mode 100644 index 0000000000..1aaa03feb3 --- /dev/null +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -0,0 +1,76 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0008-signal-return-restores-syscall-state.patch" +PROBE = FEX / "probes/async-signal-context.c" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SignalReturnSyscallStateTest(unittest.TestCase): + def test_only_the_signal_delegator_changes(self): + files, found = hunks() + self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) + self.assertEqual(len(found), 1) + + def test_every_guest_frame_return_restores_the_interrupted_syscall_state(self): + _, found = hunks() + function, body = found[0] + self.assertIn("SignalDelegator::RestoreThreadState", function) + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + removed = [line for line in lines if line.startswith("-")] + self.assertEqual(added, [RESTORE]) + self.assertEqual(removed, []) + context = [line[1:].strip() for line in lines] + guest_frame = context.index("if (Context->UContextLocation) {") + self.assertEqual(context[guest_frame + 1], "auto Frame = Thread->CurrentFrame;") + self.assertEqual(context[guest_frame + 2], RESTORE) + self.assertLess(context.index(RESTORE), context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")) + + def test_thread_pause_returns_are_untouched(self): + _, found = hunks() + body = found[0][1] + self.assertNotIn("TYPE_PAUSE", "".join(line for line in body.splitlines() if line.startswith("+"))) + + def test_patch_is_applied_to_every_release(self): + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class AsyncSignalContextProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-async-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_reports_the_interrupted_registers(self): + result = subprocess.run([str(self.binary), "500"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreaterEqual(int(counts["matched"]), 500) + self.assertEqual(counts["stale"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_hdr_live_switch.py b/tools/tests/test_hdr_live_switch.py index 41e30ebc76..4468be5048 100644 --- a/tools/tests/test_hdr_live_switch.py +++ b/tools/tests/test_hdr_live_switch.py @@ -43,15 +43,11 @@ class HdrLiveSwitchTest(unittest.TestCase): def test_the_gate_follows_the_display_not_the_setting(self): text = (APP / "SessionActivity.kt").read_text() start = text.index("val attached = CompositorHost.isStarted") - block = text[start:text.index("CompositorHost.start(", start)] + block = text[start:text.index("DriverSetupLog.write", start)] request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))] - self.assertNotIn("SessionPrefs.hdr", block) + self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")]) self.assertIn("capable, false", request) - self.assertIn("if (!SessionState.running) CompositorHost.applyHdr(this, mode)", block) - host = (APP / "wayland/CompositorHost.kt").read_text() - gate = host[host.index("fun applyHdr("):] - gate = gate[:gate.index("\n }")] - self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(context, mode)", gate) + self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block) def test_both_switches_apply_to_the_running_session(self): helper = (APP / "session/SessionHdr.kt").read_text() From 101139ec9912e6f92676eb0a91dbdb1287dde969 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:44:14 -0500 Subject: [PATCH 02/17] feat(runtime): run the Linux side without proot by default (#3041) --- app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt | 2 +- .../main/java/com/droiddeck/launcher/session/SessionPrefs.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index eb9d67c1e4..6f09160282 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -187,7 +187,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var gpuClockPin by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false) private var prootFastPath by mutableStateOf(true) - private var nativeUserland by mutableStateOf(false) + private var nativeUserland by mutableStateOf(true) private var cursorComposite by mutableStateOf(false) private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var phantomWarning by mutableStateOf(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 0ff3d76e38..1928588c13 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1011,7 +1011,7 @@ object SessionPrefs { prefs(context).edit().putBoolean("prootNoSeccomp", on).apply() } - fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false) + fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true) fun setNativeUserland(context: Context, on: Boolean) { prefs(context).edit().putBoolean("nativeUserland", on).apply() From f43cc43d05d80a90341e3f1412cb2302bc24d709 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:27:28 -0500 Subject: [PATCH 03/17] fix(ui): the empty Steam page's ball bounces edge to edge, and the logo traces in around it on the slam (#3050) --- .../droiddeck/launcher/ui/LauncherPreviews.kt | 1 + .../com/droiddeck/launcher/ui/EmptyLibrary.kt | 103 +++++++++++------- .../com/droiddeck/launcher/ui/LiftSheet.kt | 3 +- .../com/droiddeck/launcher/ui/SteamHome.kt | 4 +- 4 files changed, 69 insertions(+), 42 deletions(-) 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 e0003e1348..681b32a10b 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -15,6 +15,7 @@ private fun Launcher(tab: String, games: List Unit)? = null, fade: @Composable () -> Unit) { - val clock = rememberMarkClock(avoid) - Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) { + var origin by remember { mutableStateOf(Offset.Zero) } + val clock = rememberMarkClock(avoid?.translate(-origin.x, -origin.y)) + Box( + Modifier.fillMaxSize() + .onGloballyPositioned { origin = it.positionInRoot() } + .onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }, + ) { if (wall != null) wall() else EmptyWall(clock) fade() Mark(clock) } } -private const val TRACE_MS = 1250f -private const val FILL_FROM = 450f private const val POP_FROM = 900f private const val IMPACT = 2200f private const val RIPPLE_MS = 1250f private const val HIT_MS = 900f private const val END = 3600f +private const val REVEAL_MS = 2300f +private const val TRACE_DRAW_MS = 900f +private const val TRACE_FADE_MS = 500f +private const val REVEAL_FILL_FROM = 600f +private const val REVEAL_FILL_MS = 450f +private const val REVEAL_FADE_FROM = 1700f private const val POKE = 880f private const val DRIFT_MS = 75_000f @@ -82,8 +93,7 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock { val haptics = LocalHapticFeedback.current val keepOff by rememberUpdatedState(avoid) val speed = with(LocalDensity.current) { 64.dp.toPx() } - val inset = with(LocalDensity.current) { 10.dp.toPx() } - val clearance = with(LocalDensity.current) { 16.dp.toPx() } + val clearance = with(LocalDensity.current) { 4.dp.toPx() } LaunchedEffect(clock) { var last = -1L var vx = speed * 0.8f @@ -109,16 +119,28 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock { var x = clock.at.x + vx * dt / 1000f var y = clock.at.y + vy * dt / 1000f - val hw = f.halfWidth - val hh = f.halfHeight - if (x - hw < inset) { x = inset + hw; vx = abs(vx) } - if (x + hw > clock.page.width - inset) { x = clock.page.width - inset - hw; vx = -abs(vx) } - if (y - hh < inset) { y = inset + hh; vy = abs(vy) } - if (y + hh > clock.page.height - inset) { y = clock.page.height - inset - hh; vy = -abs(vy) } + val hw = f.ball + val hh = f.ball + if (x - hw < 0f) { x = hw; vx = abs(vx) } + if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) } + if (y - hh < 0f) { y = hh; vy = abs(vy) } + if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) } keepOff?.inflate(clearance)?.let { r -> - if (x + hw > r.left && x - hw < r.right && y + hh > r.top && y - hh < r.bottom) { - val outX = if (x < r.center.x) r.left - (x + hw) else r.right - (x - hw) - val outY = if (y < r.center.y) r.top - (y + hh) else r.bottom - (y - hh) + val nearX = x.coerceIn(r.left, r.right) + val nearY = y.coerceIn(r.top, r.bottom) + val gapX = x - nearX + val gapY = y - nearY + val gap = hypot(gapX, gapY) + if (gap in 0.0001f..f.ball) { + val nx = gapX / gap + val ny = gapY / gap + x = nearX + nx * f.ball + y = nearY + ny * f.ball + val into = vx * nx + vy * ny + if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny } + } else if (gap <= 0.0001f) { + val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x + val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) } else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) } } @@ -294,30 +316,33 @@ private fun Mark(clock: MarkClock) { } else 0f translate(0f, shake) { - val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f)) - if (fill > 0f) { - val lift = 8f * k * (1f - fill) - val edge = 5f * f.s - LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } - LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } - drawPath(left, slabEdge.copy(alpha = fill)) - drawPath(right, slabEdge.copy(alpha = fill)) - LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) } - LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) } - drawPath(left, ink.copy(alpha = fill)) - drawPath(right, ink.copy(alpha = fill)) - } - - if (intro < TRACE_MS) { - val drawn = TraceEase.transform(clamp01(intro / 775f)) - val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f - LogoShape.left(left, 0f, f::px) - LogoShape.right(right, f::px) - for (half in listOf(left, right)) { - measure.setPath(half, false) - piece.reset() - measure.getSegment(0f, measure.length * drawn, piece, true) - drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(2f * f.s)) + val since = t - IMPACT + if (since in 0f..REVEAL_MS) { + val fade = 1f - clamp01((since - REVEAL_FADE_FROM) / (REVEAL_MS - REVEAL_FADE_FROM)) + val fill = Out.transform(clamp01((since - REVEAL_FILL_FROM) / REVEAL_FILL_MS)) * fade + if (fill > 0f) { + val lift = 8f * k * (1f - fill / fade) + val edge = 5f * f.s + LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } + LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } + drawPath(left, slabEdge.copy(alpha = fill)) + drawPath(right, slabEdge.copy(alpha = fill)) + LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) } + LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) } + drawPath(left, ink.copy(alpha = fill)) + drawPath(right, ink.copy(alpha = fill)) + } + val drawn = TraceEase.transform(clamp01(since / TRACE_DRAW_MS)) + val alpha = (if (since < TRACE_DRAW_MS) 1f else 1f - (since - TRACE_DRAW_MS) / TRACE_FADE_MS).coerceIn(0f, 1f) * fade + if (alpha > 0f) { + LogoShape.left(left, 0f, f::px) + LogoShape.right(right, f::px) + for (half in listOf(left, right)) { + measure.setPath(half, false) + piece.reset() + measure.getSegment(0f, measure.length * drawn, piece, true) + drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(3f * f.s)) + } } } 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 88b32cf5de..920bb7f7f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -189,6 +189,7 @@ internal fun LiftHero( onOpenChange: (Boolean) -> Unit = {}, start: Dp = 44.dp, bottom: Dp = 44.dp, + onTextBounds: (Rect) -> Unit = {}, drop: DropSheetState? = null, overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {}, ) { @@ -573,7 +574,7 @@ internal fun LiftHero( } } - Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) { + Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) { Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() } Spacer(Modifier.height(18.dp)) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { 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 20dd2c2807..f9c81f4e42 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -140,6 +140,7 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) onOpen = a.onSteamSettings, onPrimary = a.onPlay, modifier = modifier.clipToBounds(), start = if (narrow) 20.dp else 44.dp, bottom = 44.dp, + onTextBounds = { words = it }, background = { when { games.isEmpty() -> EmptyLibrary( @@ -160,13 +161,12 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) } if (narrow) Column( - verticalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.onPlaced { words = it.boundsInParent() }, + verticalArrangement = Arrangement.spacedBy(12.dp), ) { Wordmark(30.dp) runtimeStatus() } else Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), - modifier = Modifier.onPlaced { words = it.boundsInParent() }, ) { Wordmark(if (narrow) 30.dp else 40.dp) runtimeStatus() From 84c877813f4fb41865e84dbd11653fcf0738a632 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 03:15:53 -0500 Subject: [PATCH 04/17] fix(addons): CurseForge rows follow CurseForge's own installed list (#3042) * fix(addons): CurseForge rows follow CurseForge's own installed list The CurseForge source reads installed state and available updates from CurseForge's installed projects after asking it to rescan the game instance, so addons removed from disk show Install again and out of date ones show Update, which updates through CurseForge. Deleting an addon from the addon list uninstalls it through CurseForge when CurseForge manages it, so its list and the files stay in step. * Delete addons through CurseForge only while it is already linked * Link CurseForge on the Addons tab and give its rows Update and Uninstall * Match WoWInterface addons to the AddOns folders on disk The WoWInterface source now reads each addon's folder list and marks it installed when every folder is on disk, whichever source installed it. Deletes from that source go through CurseForge while it is linked. * Fix Compose tests hanging after a dropped UI dispatch and stop CurseForge on tab dispose A non-Compose test that runs the real App after a Compose test in the same Robolectric sandbox leaves AndroidUiDispatcher flagged as scheduled while its looper message is dropped by the sandbox reset, so global snapshot changes are never applied and every later Compose test times out waiting for idle. The shared compose rule now detects that state and re-arms the dispatcher. CurseLink.close runs the stop on a job owned by the link, so the tab test can join it and prove no CurseForge work remains after the tab is disposed. * Match add-on folders by case, offer only real updates, settle deletes on disk A delete that CurseForge finished before its link dropped now counts as done when the folder is already gone. Managed uninstalls only consider projects whose folders are all present, and folder names resolve case-insensitively everywhere. Update is offered only for a newer version, falling back to the source's current file when versions do not compare. The test compose rule also re-posts a dropped frame dispatch. --- .../droiddeck/launcher/FrontEndActivity.kt | 2 +- .../launcher/runtime/CurseForgeApp.kt | 68 ++++- .../launcher/runtime/WowAddonCatalog.kt | 36 ++- .../droiddeck/launcher/runtime/WowAddons.kt | 7 + .../com/droiddeck/launcher/ui/AddonBrowser.kt | 217 +++++++++++--- .../com/droiddeck/launcher/ui/GameDetail.kt | 43 ++- .../launcher/runtime/CurseForgeAppTest.kt | 275 +++++++++++++++++- .../launcher/runtime/WowAddonCatalogTest.kt | 34 ++- .../com/droiddeck/launcher/ui/AddonRowTest.kt | 94 ++++++ .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 193 ++++++++++++ .../launcher/ui/RobolectricComposeRule.kt | 45 +++ .../launcher/ui/RobolectricComposeRuleTest.kt | 90 ++++++ 12 files changed, 1029 insertions(+), 75 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 6f09160282..1c0d4f8ef9 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -1531,7 +1531,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet onAddonImport = { sg, target -> importAddons(sg.name, target) }, onAddonDelete = { target, name -> saveAction(getString(R.string.main_addons_deleting, name)) { - com.droiddeck.launcher.runtime.WowAddons.delete(target, name) + com.droiddeck.launcher.ui.deleteAddon(this, target, name) getString(R.string.main_addons_deleted, name) } }, diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt index adc2119889..a5fb9a4a40 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/CurseForgeApp.kt @@ -4,6 +4,7 @@ import android.content.Context import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import org.json.JSONArray import org.json.JSONObject +import java.io.File import java.time.Instant import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.LinkedBlockingQueue @@ -18,11 +19,14 @@ object CurseForgeApp { internal const val AGENT = "/usr/local/bin/droiddeck-agent" private const val READY_MS = 120_000L private const val INSTALL_MS = 300_000L + private const val OUT_OF_DATE = 2 enum class Start { READY, BUSY, FAILED } class Started(val state: Start, val inspector: String? = null) + class Project(val id: String, val installedModId: String, val folders: List, val update: Boolean) + internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") class Failure(message: String, val code: String? = null) : Exception(message) { @@ -141,9 +145,23 @@ object CurseForgeApp { return detected?.takeIf { it.isNotBlank() } } - internal fun projectIds(value: Any?): Set { - val list = value as? JSONArray ?: return emptySet() - return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet() + internal fun parseProjects(value: Any?): List { + val list = value as? JSONArray ?: return emptyList() + return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p -> + val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null + val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty() + Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked")) + } + } + + internal fun owner(projects: List, folder: String): Project? = + projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } } + + internal fun byFolder(projects: List): Map = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap() + + internal fun onDisk(projects: List, addOns: File): List { + val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet() + return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } } } internal var guest: (Context, List, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine -> @@ -232,22 +250,44 @@ object CurseForgeApp { fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page = parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000)) - fun installed(context: Context, inspector: String, guid: String): Set { + fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List { connect(context, inspector) - return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))")) + if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000) + return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS)) + } + + private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " + + "locked: !!(p.installedVersion && p.installedVersion.isLocked), " + + "folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))" + + private fun settle(context: Context, inspector: String, guid: String, done: (List) -> Boolean): Boolean { + val deadline = System.currentTimeMillis() + INSTALL_MS + while (System.currentTimeMillis() < deadline) { + val listed = runCatching { projects(context, inspector, guid) } + val error = listed.exceptionOrNull() + if (error is Failure && error.gone) throw error + listed.getOrNull()?.let { if (done(it)) return true } + Thread.sleep(1_000) + } + return false } fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean { connect(context, inspector) if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false - val deadline = System.currentTimeMillis() + INSTALL_MS - while (System.currentTimeMillis() < deadline) { - val listed = runCatching { installed(context, inspector, guid) } - val error = listed.exceptionOrNull() - if (error is Failure && error.gone) throw error - if (projectId in listed.getOrDefault(emptySet())) return true - Thread.sleep(1_000) - } - return false + return settle(context, inspector, guid) { list -> list.any { it.id == projectId } } + } + + fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean { + connect(context, inspector) + if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false + return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } } + } + + fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean { + connect(context, inspector) + val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray + if (failed == null || failed.length() > 0) return false + return settle(context, inspector, guid) { list -> list.none { it.id == project.id } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt index bca0627bec..5a0cf0bb98 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddonCatalog.kt @@ -29,6 +29,7 @@ object WowAddonCatalog { val downloads: Long, val updated: Long, val thumb: String?, + val folders: List = emptyList(), ) class Page(val items: List, val more: Boolean) @@ -114,9 +115,11 @@ object WowAddonCatalog { } val thumbs = o.optJSONArray("UIIMG_Thumbs") val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null + val dirs = o.optJSONArray("UIDir") + val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() } val addon = Addon( id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"), - o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, + o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders, ) out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L)) } @@ -241,9 +244,32 @@ object WowAddonCatalog { return details.version } - internal fun sameVersion(a: String, b: String): Boolean { - fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase() - return norm(a) == norm(b) + private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase() + + internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b) + + private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""") + + private fun numericVersion(v: String): Pair, String>? { + val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null + val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null } + return parts to match.groupValues[2] + } + + internal fun newer(have: String, latest: String): Boolean? { + val (a, aRest) = numericVersion(have) ?: return null + val (b, bRest) = numericVersion(latest) ?: return null + for (i in 0 until maxOf(a.size, b.size)) { + val x = a.getOrElse(i) { 0L } + val y = b.getOrElse(i) { 0L } + if (x != y) return y > x + } + return if (aRest == bRest) false else null + } + + internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean { + if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false + return newer(have, latest) ?: sameSource } internal fun findUpdates(entries: List, installed: List): Map { @@ -253,7 +279,7 @@ object WowAddonCatalog { val id = item.wowiId ?: return@mapNotNull null val version = item.version ?: return@mapNotNull null val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null - if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest + if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest }.toMap() } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index 799cfe7717..b8a9367947 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -69,6 +69,13 @@ object WowAddons { target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } .map { it.name }.sortedBy { it.lowercase() } + fun present(folders: List, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists) + + fun folder(addOns: File, name: String): File? { + val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } + return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) } + } + fun details(target: Target): List { val origins = origins(target) return installed(target).map { name -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index 514677364c..ee4f5eb1db 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -37,6 +37,7 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.withFrameNanos import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment @@ -53,6 +54,7 @@ import androidx.compose.ui.input.InputMode import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction @@ -60,6 +62,8 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextOverflow 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 com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.AddedGames @@ -68,12 +72,16 @@ import com.droiddeck.launcher.runtime.UserApps import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddons import com.droiddeck.launcher.session.SessionState +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference private class AddonResults { val items = mutableStateListOf() @@ -83,23 +91,40 @@ private class AddonResults { var more by mutableStateOf(false) } -private enum class AddonStatus { INSTALL, UPDATE, INSTALLED } +internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED } private enum class AddonSource { WOWI, CURSE } -private class CurseState(val notice: Int? = null) : Exception() +internal class CurseState(val notice: Int? = null) : Exception() -private class CurseLink(val app: UserApps.App) { +internal class CurseLink(val app: UserApps.App) { class Linked(val inspector: String, val guid: String) private val lock = Object() + private val work = SupervisorJob() @Volatile private var closed = false @Volatile private var hold: AtomicBoolean? = null @Volatile private var inspector: String? = null private val guids = HashMap() + private val scanLock = Object() + private val scans = HashMap>>() + var generation by mutableIntStateOf(0) + private set - fun call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T { - val linked = synchronized(lock) { link(context, target) } + fun refresh() { + generation++ + } + + fun installed(context: Context, target: WowAddons.Target, key: Any): List = CurseForgeApp.onDisk( + synchronized(scanLock) { + scans[target.addOns.path]?.takeIf { it.first == key }?.second + ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { scans[target.addOns.path] = key to it } + }, + target.addOns, + ) + + fun call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T { + val linked = synchronized(lock) { link(context, target, launch) } try { return block(linked) } catch (e: CurseForgeApp.Failure) { @@ -107,22 +132,25 @@ private class CurseLink(val app: UserApps.App) { if (inspector == linked.inspector) { inspector = null guids.clear() + current.compareAndSet(this, null) } } throw e } } - private fun link(context: Context, target: WowAddons.Target): Linked { + private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked { if (closed) throw CurseState() val url = inspector ?: run { - val launch = AtomicBoolean(false) - hold = launch + if (!launch) throw CurseState() + val hold = AtomicBoolean(false) + this.hold = hold if (closed) throw CurseState() - val done = CurseForgeApp.start(context, app, launch) + val done = CurseForgeApp.start(context, app, hold) when (done.state) { CurseForgeApp.Start.READY -> { inspector = done.inspector + if (!closed) current.set(this) done.inspector ?: throw CurseState() } CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy) @@ -138,23 +166,66 @@ private class CurseLink(val app: UserApps.App) { return Linked(url, guid) } - fun close(context: Context) { + fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked -> + val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns) + val project = CurseForgeApp.owner(projects, folder) ?: return@call false + if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState() + true + } + + internal val stopped: Job get() = work + + fun close(context: Context): Job { closed = true - val launch = hold ?: return - Thread { - CurseForgeApp.stop(context, app, inspector, launch) + current.compareAndSet(this, null) + val launch = hold + return CoroutineScope(work + Dispatchers.IO).launch { + if (launch != null) CurseForgeApp.stop(context, app, inspector, launch) synchronized(lock) { hold = null inspector = null } - }.start() + }.also { work.complete() } + } + + companion object { + private val current = AtomicReference() + + fun live(): CurseLink? = current.get() } } private const val PAGES_AHEAD = 8 +private const val CURSE_UPDATE = "update" +private const val UNINSTALLING = -1 + +private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update } + +private class Present(val curse: Map = emptyMap(), val disk: Map = emptyMap()) @Composable -internal fun AddonBrowserDialog(targets: List, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) { +internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? { + val context = LocalContext.current.applicationContext + val owner = LocalLifecycleOwner.current + var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) } + DisposableEffect(owner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_START) visible = true + if (event == Lifecycle.Event.ON_STOP) visible = false + } + owner.lifecycle.addObserver(observer) + onDispose { owner.lifecycle.removeObserver(observer) } + } + val active = visible && !sessionRunning + val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) } + DisposableEffect(link) { + onDispose { link?.close(context) } + } + return link +} + +@Composable +internal fun AddonBrowserDialog(targets: List, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) { val context = LocalContext.current.applicationContext val scope = rememberCoroutineScope() val shown = rememberShown(onDismiss) @@ -164,11 +235,8 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd var category by remember { mutableStateOf(null) } var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) } var source by remember { mutableStateOf(AddonSource.WOWI) } - val curse = if (source == AddonSource.CURSE) curseForge else null - val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) } - DisposableEffect(link) { - onDispose { link?.close(context) } - } + val curse = if (source == AddonSource.CURSE && link != null) curseForge else null + LaunchedEffect(link) { link?.refresh() } var notice by remember { mutableStateOf(null) } var curseInstalls by remember { mutableIntStateOf(0) } val results = remember(text, category, sort, target, curse) { AddonResults() } @@ -178,20 +246,22 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) } } val presentKey = curse to target.addOns - val snapshot by produceState(presentKey to emptyMap(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) { + val scanKey = link?.generation to WowAddons.imports + val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) { val into = target val key = curse to into.addOns value = key to withContext(Dispatchers.IO) { - if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap()) - else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() + if (curse != null && link != null) Present(curse = runCatching { + link.installed(context, into, scanKey).associate { it.id to curseMark(it) } + }.getOrDefault(emptyMap())) + else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) } } - val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap() + val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present() fun status(addon: WowAddonCatalog.Addon): AddonStatus { - if (addon.id !in present) return AddonStatus.INSTALL - val have = present[addon.id] + if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary - return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE + return diskStatus(addon.folders, present.disk, latest, addon.id) } fun load(page: Int) { if (results.loading) return @@ -230,16 +300,23 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd val via = link?.takeIf { curse != null } if (via != null) { val into = target + val updating = status(addon) == AddonStatus.UPDATE installing[key] = 0 scope.launch { - val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } } + val done = withContext(Dispatchers.IO) { + runCatching { + via.call(context, into) { + if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id) + else CurseForgeApp.install(context, it.inspector, it.guid, addon.id) + } + } + } installing.remove(key) val ok = done.getOrNull() == true - if (ok) { - WowAddons.changed() - curseInstalls++ - } + WowAddons.changed() + curseInstalls++ val message = when { + ok && updating -> context.getString(R.string.user_apps_updated, addon.name) ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor) else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString) ?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name) @@ -261,6 +338,32 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd Toast.makeText(context, message.first, Toast.LENGTH_LONG).show() } } + fun uninstall(addon: WowAddonCatalog.Addon) { + val key = installKey(addon, target) + if (key in installing) return + if (SessionState.running) { + Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show() + return + } + val into = target + val via = link?.takeIf { curse != null } + installing[key] = UNINSTALLING + scope.launch { + val done = withContext(Dispatchers.IO) { + runCatching { + val folders = if (via != null) via.call(context, into) { linked -> + CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty() + } else addon.folders + folders.forEach { name -> WowAddons.folder(into.addOns, name)?.let { deleteAddon(context, into, it.name, link) } } + } + } + installing.remove(key) + installed.remove(key) + WowAddons.changed() + curseInstalls++ + if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show() + } + } val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi) val grid = rememberLazyGridState() LaunchedEffect(results, grid) { @@ -342,7 +445,7 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd ) { items(results.items, key = { it.id }) { addon -> val key = installKey(addon, target) - AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) } + AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) } } item(span = { GridItemSpan(maxLineSpan) }) { Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { @@ -365,7 +468,22 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd } @Composable -private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) { +internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) { + var asking by remember(addon.id) { mutableStateOf(false) } + val first = remember(addon.id) { FocusRequester() } + var refocus by remember(addon.id) { mutableStateOf(false) } + val inputMode = LocalInputModeManager.current + LaunchedEffect(status, progress) { + if (!refocus) return@LaunchedEffect + withFrameNanos { } + runCatching { first.requestFocus() } + if (progress == null) refocus = false + } + fun act(block: () -> Unit) { + refocus = inputMode.inputMode == InputMode.Keyboard + block() + } + val lead = action.focusRequester(first) val colors = MaterialTheme.colorScheme val pal = LocalPalette.current Row( @@ -383,13 +501,24 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } - val size = action + val uninstall = stringResource(R.string.common_uninstall) when { - progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall) - status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {} - else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall) + progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {} + progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall) + status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) } + else -> { + if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) } + SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true } + } } } + if (asking) ConfirmDialog( + title = stringResource(R.string.stores_uninstall_title, addon.name), + text = stringResource(R.string.games_delete_addon_body), + confirm = stringResource(R.string.common_uninstall), + onConfirm = { asking = false; act(onUninstall) }, + onDismiss = { asking = false }, + ) } private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent { @@ -438,4 +567,16 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target } } +internal fun diskStatus(folders: List, onDisk: Map, latest: String, id: String): AddonStatus { + if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL + val have = onDisk.getValue(folders.first().lowercase()) + return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED +} + +internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) { + val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true + val left = WowAddons.folder(target.addOns, folder) + if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name) +} + private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path 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 447d3ef73f..5f9d6d0ebc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -295,7 +295,7 @@ internal fun GameDetail( GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) } GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail) GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a) - GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a) + GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a) GameTab.INSTALL -> InstallTab(game, installed, item, store) } } @@ -1047,9 +1047,11 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) { } @Composable -private fun AddonsTab(g: Library.SteamGame, targets: List, a: FrontEndActions) { +private fun AddonsTab(g: Library.SteamGame, targets: List, sessionRunning: Boolean, a: FrontEndActions) { var browsing by remember(g.gameId) { mutableStateOf(null) } - browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } } + val curseForge = CurseForgeApp.find(UserAppsState.items) + val link = rememberCurseLink(curseForge, sessionRunning) + browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } } Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { CurseForgeEntry(a) targets.forEach { target -> @@ -1060,6 +1062,12 @@ private fun AddonsTab(g: Library.SteamGame, targets: List, a: val updates by produceState(emptyMap(), names) { value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) } } + val scanKey = link?.generation to WowAddons.imports + val managed by produceState(emptyMap(), link, target.addOns, scanKey) { + value = if (link == null) emptyMap() else withContext(Dispatchers.IO) { + runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap()) + } + } if (targets.size > 1) SectionLabel(target.flavor) MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target } MenuItem( @@ -1070,7 +1078,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List, a: target.addOns.mkdirs() a.onBrowseFiles(target.addOns) } - names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } } + names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } } } } } @@ -1124,8 +1132,10 @@ private fun CurseForgeEntry(a: FrontEndActions) { } @Composable -private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) { +internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair? = null) { val name = item.name + val update = wowiUpdate.takeIf { curse == null } + val outdated = update != null || curse?.first?.update == true var asking by remember(target.addOns, name) { mutableStateOf(false) } var progress by remember(target.addOns, name) { mutableStateOf(null) } val context = LocalContext.current @@ -1135,26 +1145,33 @@ private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) { Column(Modifier.weight(1f)) { Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) - val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" ยท ") + val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" ยท ") if (detail.isNotEmpty()) Text( progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp, - color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } - if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) { + if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) { progress = 0 scope.launch { - val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } } + val message = withContext(Dispatchers.IO) { + if (curse != null) { + val (project, link) = curse + val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false) + WowAddons.changed() + if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name) + } else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first } + } progress = null - android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show() + if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show() } } - if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } + if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } } if (asking) ConfirmDialog( - title = stringResource(R.string.games_delete_addon_title, name), + title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name), text = stringResource(R.string.games_delete_addon_body), - confirm = delete, + confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete, onConfirm = { a.onAddonDelete(target, name) }, onDismiss = { asking = false }, ) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt index e3cb7ef501..47d892993b 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/CurseForgeAppTest.kt @@ -166,9 +166,16 @@ class CurseForgeAppTest { } @Test - fun installedIdsAndExitCodes() { - assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]"""))) - assertEquals(emptySet(), CurseForgeApp.projectIds(JSONObject())) + fun installedProjectsAndExitCodes() { + val projects = CurseForgeApp.parseProjects(JSONArray("""[ + {"id":"486246","installedModId":"a_486246","status":3,"locked":false,"folders":["RXPGuides","RXPGuides_Extra"]}, + {"id":"2","installedModId":"b_2","status":2,"locked":true,"folders":[]}, + {"id":null}]""")) + assertEquals(listOf("486246", "2"), projects.map { it.id }) + assertEquals("486246", CurseForgeApp.owner(projects, "RXPGuides_Extra")?.id) + assertNull(CurseForgeApp.owner(projects, "TomTom")) + assertFalse(projects[1].update) + assertTrue(CurseForgeApp.parseProjects(JSONObject()).isEmpty()) assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0)) assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3)) assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4)) @@ -293,6 +300,268 @@ class CurseForgeAppTest { assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url)) } + private class Curse(val addOns: File, val flavor: String = "") { + val projects = java.util.concurrent.CopyOnWriteArrayList() + val methods = java.util.Collections.synchronizedList(mutableListOf()) + @Volatile var unreachableAfterDelete = false + @Volatile var unreachable = false + + fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status) + + fun add(id: String, folders: List, status: Int, onDisk: List = folders) { + onDisk.forEach { File(addOns, it).mkdirs() } + projects += JSONObject().put("id", id).put("installedModId", "m_$id").put("status", status).put("locked", false).put("folders", JSONArray(folders)) + } + + private fun folders(p: JSONObject) = (0 until p.getJSONArray("folders").length()).map { p.getJSONArray("folders").getString(it) } + + fun answer(expression: String): Any? { + val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(expression)?.groupValues?.get(1) ?: return true + methods += method + return when (method) { + "scanGameInstance" -> { + projects.removeAll { p -> !File(addOns, p.getJSONArray("folders").getString(0)).isDirectory } + true + } + "getProjects" -> JSONArray(projects.map { JSONObject(it.toString()) }) + "updateMod" -> { + projects.forEach { it.put("status", 1) } + true + } + "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") + "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor)) + "deleteMods" -> { + projects.removeAll { p -> + (p.getString("installedModId") in expression).also { gone -> + if (gone) folders(p).forEach { name -> WowAddons.folder(addOns, name)?.deleteRecursively() } + } + } + if (unreachableAfterDelete) unreachable = true + JSONArray() + } + else -> true + } + } + } + + private fun fakeCurse(addOns: File = temp.newFolder("AddOns"), flavor: String = "", calls: MutableList> = mutableListOf()): Curse { + val curse = Curse(addOns, flavor) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + calls += argv + when { + argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> { + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + 0 + } + argv[0] == CurseForgeApp.HELPER -> 0 + curse.unreachable -> { + onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "gone")).toString()) + 0 + } + else -> { + val value = JSONObject().put("value", curse.answer(argv[4]) ?: JSONObject.NULL) + onLine(JSONObject().put("ok", true).put("value", value.toString()).toString()) + 0 + } + } + } + return curse + } + + private fun wow(): WowAddons.Target { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val games = temp.newFolder("Games") + val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() } + com.droiddeck.launcher.session.SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games")) + return WowAddons.Target("_retail_", addOns) + } + + @Test + fun anEntryCurseForgeStillListsShowsAsNotInstalledOnceItsFolderIsGone() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively()) + val listed = CurseForgeApp.projects(context, url, "g") + assertEquals(listOf("298842", "18808"), listed.map { it.id }) + assertEquals(listOf("18808"), CurseForgeApp.onDisk(listed, curse.addOns).map { it.id }) + } + + @Test + fun aProjectWithAnyFolderMissingOrNoFoldersIsNotInstalled() { + val addOns = temp.newFolder("Split") + File(addOns, "DBM-Core").mkdirs() + val split = CurseForgeApp.Project("3358", "m_3358", listOf("DBM-Core", "DBM-StatusBarTimers"), false) + val bare = CurseForgeApp.Project("1", "m_1", emptyList(), false) + assertTrue(CurseForgeApp.onDisk(listOf(split, bare), addOns).isEmpty()) + File(addOns, "DBM-StatusBarTimers").mkdirs() + assertEquals(listOf("3358"), CurseForgeApp.onDisk(listOf(split, bare), addOns).map { it.id }) + } + + @Test + fun aDeleteWhileCurseForgeIsLinkedGoesThroughItsUninstall() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + assertTrue(com.droiddeck.launcher.ui.CurseLink.live() === link) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) + } finally { + link.close(context) + } + assertNull(com.droiddeck.launcher.ui.CurseLink.live()) + } + + @Test + fun aDeleteWithoutALiveLinkRemovesTheFolderAtOnceWithoutStartingCurseForge() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls) + curse.add("298842", "Leatrix_Maps", 1) + assertNull(com.droiddeck.launcher.ui.CurseLink.live()) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(calls.isEmpty()) + assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).none { it.id == "298842" }) + } + + @Test + fun aLinkThatNeverStartedIsNotUsedToDelete() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val calls = java.util.Collections.synchronizedList(mutableListOf>()) + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls) + curse.add("298842", "Leatrix_Maps", 1) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps", com.droiddeck.launcher.ui.CurseLink(app)) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(calls.isEmpty()) + } + + @Test + fun anAddonWhoseFolderWasDeletedShowsAsNotInstalledAfterTheRescan() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + assertEquals(listOf("298842"), CurseForgeApp.projects(context, url, "g", rescan = true).map { it.id }) + assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively()) + assertTrue(CurseForgeApp.projects(context, url, "g").isNotEmpty()) + assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).isEmpty()) + assertTrue("scanGameInstance" in curse.methods) + } + + @Test + fun aNewerFileShowsAsAnUpdateUntilCurseForgeUpdatesIt() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 2) + curse.add("18808", "TomTom", 1) + val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update } + assertEquals(mapOf("298842" to true, "18808" to false), before) + assertTrue(CurseForgeApp.update(context, url, "g", "298842")) + assertTrue("updateMod" in curse.methods) + assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update }) + } + + @Test + fun uninstallingThroughCurseForgeClearsItsListAndTheFolder() { + val curse = fakeCurse() + val context = org.robolectric.RuntimeEnvironment.getApplication() + curse.add("298842", "Leatrix_Maps", 1) + curse.add("18808", "TomTom", 1) + val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!! + assertTrue(CurseForgeApp.uninstall(context, url, "g", project)) + assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id }) + assertFalse(File(curse.addOns, "Leatrix_Maps").exists()) + assertTrue(File(curse.addOns, "TomTom").isDirectory) + } + + @Test + fun anUninstallThatRemovedTheFolderBeforeCurseForgeWentAwayCountsAsDeleted() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("298842", "Leatrix_Maps", 1) + curse.unreachableAfterDelete = true + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + val before = WowAddons.imports + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + assertTrue(WowAddons.imports > before) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun aLocalDeleteInAProjectWithAMissingFolderKeepsItsOtherFolders() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("3358", listOf("DBM-Core", "DBM-GUI", "DBM-StatusBarTimers"), 1, onDisk = listOf("DBM-Core", "DBM-GUI")) + curse.add("298842", "Leatrix_Maps", 1) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + com.droiddeck.launcher.ui.deleteAddon(context, target, "DBM-Core") + assertFalse("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "DBM-Core").exists()) + assertTrue(File(target.addOns, "DBM-GUI").isDirectory) + com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps") + assertTrue("deleteMods" in curse.methods) + assertFalse(File(target.addOns, "Leatrix_Maps").exists()) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun foldersMatchCurseForgesNamesWhateverTheirCase() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_") + curse.add("12345", listOf("Questie"), 1, onDisk = listOf("questie")) + val listed = CurseForgeApp.projects(context, url, "g") + assertEquals(listOf("12345"), CurseForgeApp.onDisk(listed, target.addOns).map { it.id }) + assertEquals("12345", CurseForgeApp.byFolder(listed)["questie"]?.id) + assertEquals("questie", WowAddons.folder(target.addOns, "Questie")?.name) + val link = com.droiddeck.launcher.ui.CurseLink(app) + try { + link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) } + com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie") + assertTrue("deleteMods" in curse.methods) + assertNull(WowAddons.folder(target.addOns, "Questie")) + } finally { + kotlinx.coroutines.runBlocking { link.close(context).join() } + } + } + + @Test + fun aLocalDeleteFindsTheFolderWhateverItsCaseAndAnAbsentFolderIsAlreadyDeleted() { + val context = org.robolectric.RuntimeEnvironment.getApplication() + val target = wow() + File(target.addOns, "questie").mkdirs() + File(target.addOns, "TomTom").mkdirs() + com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie", null) + assertNull(WowAddons.folder(target.addOns, "Questie")) + assertTrue(File(target.addOns, "TomTom").isDirectory) + val before = WowAddons.imports + com.droiddeck.launcher.ui.deleteAddon(context, target, "Gone", null) + assertTrue(WowAddons.imports > before) + } + @Test fun theAgentAnswerIsTheLastJsonLine() { assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v")) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt index 451ec81bc3..e298c39822 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonCatalogTest.kt @@ -15,7 +15,7 @@ class WowAddonCatalogTest { private val context get() = RuntimeEnvironment.getApplication() private val files = """[ - {"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"]}, + {"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"],"UIDir":["Bartender4"," Bartender4_Options "]}, {"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null}, {"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null}, {"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]} @@ -44,6 +44,12 @@ class WowAddonCatalogTest { assertEquals("19", e[0].category) } + @Test fun fileListEntriesCarryTheirAddonFolders() { + val e = WowAddonCatalog.parseWowiFiles(files) + assertEquals(listOf("Bartender4", "Bartender4_Options"), e[0].addon.folders) + assertEquals(emptyList(), e[1].addon.folders) + } + @Test fun versionsMapToFlavors() { assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0")) assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5")) @@ -198,6 +204,32 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4")) } + @Test fun versionsCompareNumericSegmentsFirst() { + assertEquals(true, WowAddonCatalog.newer("v4.11.38-7-ge56e9d8", "4.11.39")) + assertEquals(true, WowAddonCatalog.newer("1.9", "1.10")) + assertEquals(true, WowAddonCatalog.newer("2", "2.0.1")) + assertEquals(false, WowAddonCatalog.newer("11.2.0", "6.2.5")) + assertEquals(false, WowAddonCatalog.newer("2.0", "2")) + assertNull(WowAddonCatalog.newer("11.4.10-beta1", "11.4.10")) + assertNull(WowAddonCatalog.newer("release", "1.0")) + } + + @Test fun anUpdateIsOfferedOnlyForANewerVersionOrTheSameSourcesCurrentFile() { + assertTrue(WowAddonCatalog.offersUpdate("1.9", "1.10", sameSource = false)) + assertFalse(WowAddonCatalog.offersUpdate("11.2.0", "6.2.5", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("v1.2", "1.2", sameSource = true)) + assertTrue(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = false)) + assertFalse(WowAddonCatalog.offersUpdate(null, "1.0", sameSource = true)) + assertFalse(WowAddonCatalog.offersUpdate("1.0", "", sameSource = true)) + } + + @Test fun findUpdatesNeverOffersADowngrade() { + val installed = listOf(WowAddons.Installed("Ahead", "3.0", "10"), WowAddons.Installed("Tagged", "r55-alpha", "20")) + val updates = WowAddonCatalog.findUpdates(listOf(entry("10", "2.9"), entry("20", "r56")), installed) + assertEquals(setOf("Tagged"), updates.keys) + } + @Test fun md5Check() { val f = File(context.cacheDir, "wowaddon-md5-test.zip") f.writeText("hello") diff --git a/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt new file mode 100644 index 0000000000..20ccd9c069 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/AddonRowTest.kt @@ -0,0 +1,94 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.WowAddonCatalog +import com.droiddeck.launcher.runtime.WowAddons +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 = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class) +class AddonRowTest { + @get:Rule val compose = createRobolectricComposeRule() + + private val addon = WowAddonCatalog.Addon("298842", "Leatrix Maps", "Leatrix", "", 0, 0, null) + private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id) + + private fun show(status: AddonStatus, uninstalls: MutableList = mutableListOf(), installs: MutableList = mutableListOf()) { + val state = mutableStateOf(status) + compose.setContent { + DroidDeckTheme { + AddonRow(addon, state.value, null, Modifier, { uninstalls += addon.id }) { installs += addon.id } + } + } + } + + @Test fun aMissingAddonOffersOnlyInstall() { + val installs = mutableListOf() + show(AddonStatus.INSTALL, installs = installs) + compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0) + compose.onNodeWithText(text(R.string.store_install)).performClick() + assertEquals(listOf("298842"), installs) + } + + @Test fun aCurrentAddonOffersOnlyUninstallAfterAConfirm() { + val uninstalls = mutableListOf() + show(AddonStatus.INSTALLED, uninstalls) + compose.onAllNodesWithText(text(R.string.store_install)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0) + compose.onAllNodesWithText(text(R.string.stores_installed_chip)).assertCountEquals(0) + compose.onNodeWithText(text(R.string.common_uninstall)).performClick() + assertEquals(emptyList(), uninstalls) + compose.onAllNodesWithText(text(R.string.common_uninstall))[1].performClick() + assertEquals(listOf("298842"), uninstalls) + } + + @Test fun anOutdatedAddonOffersUpdateAndUninstall() { + val installs = mutableListOf() + show(AddonStatus.UPDATE, installs = installs) + compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(1) + compose.onNodeWithText(text(R.string.common_update)).performClick() + assertEquals(listOf("298842"), installs) + } + + private fun disk(vararg addons: WowAddons.Installed) = addons.associateBy { it.name.lowercase() } + + @Test fun anotherSourcesAddonOnDiskIsUpdatableOnlyToANewerVersion() { + val onDisk = disk(WowAddons.Installed("Questie", "11.2.0", null), WowAddons.Installed("QuestieDB", null, null)) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "6.2.5", "1")) + assertEquals(AddonStatus.UPDATE, diskStatus(listOf("Questie"), onDisk, "11.3.0", "1")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "v11.2.0", "1")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("QuestieDB"), onDisk, "1.0", "1")) + } + + @Test fun anIncomparableVersionIsAnUpdateOnlyFromTheSameSource() { + val onDisk = disk(WowAddons.Installed("TomTom", "v4.0.1-release", "12")) + assertEquals(AddonStatus.UPDATE, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "12")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "99")) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "4.0.0", "12")) + } + + @Test fun foldersOnDiskMatchWhateverTheirCase() { + val onDisk = disk(WowAddons.Installed("questie", "11.2.0", null)) + assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "11.2.0", "1")) + } + + @Test fun anAddonCountsAsInstalledOnlyWhenEveryFolderIsOnDisk() { + val onDisk = disk(WowAddons.Installed("Bartender4", "4.19.2", null)) + assertEquals(AddonStatus.INSTALL, diskStatus(listOf("Bartender4", "Bartender4_Options"), onDisk, "4.19.2", "1")) + assertEquals(AddonStatus.INSTALL, diskStatus(emptyList(), onDisk, "4.19.2", "1")) + assertEquals(AddonStatus.INSTALL, diskStatus(listOf("TomTom"), onDisk, "4.4.1", "1")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt new file mode 100644 index 0000000000..39eb286fea --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -0,0 +1,193 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.onAllNodesWithContentDescription +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.AppImageManager +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.UserApps +import com.droiddeck.launcher.runtime.WowAddonCatalog +import com.droiddeck.launcher.runtime.WowAddons +import com.droiddeck.launcher.session.SessionPrefs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withContext +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File +import java.util.Collections + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class) +class CurseLinkTabTest { + @get:Rule val compose = createRobolectricComposeRule() + @get:Rule val temp = TemporaryFolder() + + private val original = CurseForgeApp.guest + private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e" + private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED) + private val helper = Collections.synchronizedList(mutableListOf()) + private val methods = Collections.synchronizedList(mutableListOf()) + private val context get() = RuntimeEnvironment.getApplication() + + @After + fun restore() { + CurseForgeApp.guest = original + } + + private fun text(id: Int) = context.getString(id) + + private fun wow(): WowAddons.Target { + val games = temp.newFolder("Games") + val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() } + File(addOns, "Leatrix_Maps").mkdirs() + SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games")) + CurseForgeApp.guest = { _, argv, cancelled, onLine -> + if (argv[0] == CurseForgeApp.HELPER) { + helper += argv[1] + if (argv[1] == "start") { + onLine(url) + while (cancelled?.get() != true) Thread.sleep(10) + } + 0 + } else { + val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(argv[4])?.groupValues?.get(1) + method?.let { methods += it } + val answer: Any = when (method) { + "detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g") + "getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", "/root/Games/World of Warcraft/_retail_")) + "getProjects" -> JSONArray().put(JSONObject().put("id", "298842").put("installedModId", "m").put("status", 1).put("locked", false).put("folders", JSONArray().put("Leatrix_Maps"))) + else -> true + } + onLine(JSONObject().put("ok", true).put("value", JSONObject().put("value", answer).toString()).toString()) + 0 + } + } + return WowAddons.Target("_retail_", addOns) + } + + @Test + fun theTabAndItsDialogShareOneCurseForgeThatStopsWhenTheTabLeaves() { + val target = wow() + val shown = mutableStateOf(true) + val seen = Collections.synchronizedList(mutableListOf>()) + var opened: CurseLink? = null + compose.setContent { + if (shown.value) { + val link = rememberCurseLink(app, sessionRunning = false) + opened = link + LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } } + LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } } + } + } + compose.waitUntil(20_000) { seen.size == 2 } + assertEquals(listOf(listOf("298842"), listOf("298842")), seen.toList()) + assertEquals(listOf("start"), helper.toList()) + assertEquals(1, methods.count { it == "scanGameInstance" }) + assertTrue(CurseLink.live() != null) + compose.runOnIdle { shown.value = false } + compose.waitForIdle() + compose.waitUntil(20_000) { "stop" in helper } + assertNull(CurseLink.live()) + assertTrue("shutdown" in methods) + assertEquals(1, helper.count { it == "start" }) + runBlocking { withTimeout(20_000) { opened!!.stopped.join() } } + compose.waitUntil(5_000) { Thread.getAllStackTraces().keys.none { it.isAlive && it.name.startsWith("curseforge") } } + val calls = helper.size + methods.size + Thread.sleep(1_500) + assertEquals(calls, helper.size + methods.size) + } + + @Test + fun aNewGenerationRescansButReusesTheRunningCurseForge() { + val target = wow() + val link = CurseLink(app) + try { + link.installed(context, target, 0) + link.installed(context, target, 0) + link.refresh() + link.installed(context, target, link.generation) + assertEquals(2, methods.count { it == "scanGameInstance" }) + assertEquals(1, helper.count { it == "start" }) + } finally { + runBlocking { link.close(context).join() } + } + } + + @Test + fun noCurseForgeStartsWhileASessionRuns() { + wow() + var link: CurseLink? = CurseLink(app) + compose.setContent { link = rememberCurseLink(app, sessionRunning = true) } + compose.waitForIdle() + assertNull(link) + assertTrue(helper.isEmpty()) + } + + @Test + fun aStaleEntryWhoseFolderIsGoneIsNotManaged() { + val target = wow() + assertTrue(File(target.addOns, "Leatrix_Maps").deleteRecursively()) + val link = CurseLink(app) + try { + assertTrue(link.installed(context, target, 0).isEmpty()) + } finally { + runBlocking { link.close(context).join() } + } + } + + private val actions = FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, + ) + + private fun row(update: Boolean?, wowi: Boolean) { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + val item = WowAddons.Installed("Leatrix_Maps", "1.60.35", null) + val newer = WowAddonCatalog.Addon("1", "Leatrix Maps", "Leatrix", "1.60.36", 0, 0, null).takeIf { wowi } + val curse = update?.let { CurseForgeApp.Project("298842", "m", listOf("Leatrix_Maps"), it) to CurseLink(app) } + compose.setContent { DroidDeckTheme { AddonRow(item, newer, target, actions, curse) } } + } + + @Test + fun aManagedRowWithAnUpdateOffersUpdateAndUninstall() { + row(update = true, wowi = false) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(0) + } + + @Test + fun aCurrentManagedRowIgnoresOtherSourcesAndOffersOnlyUninstall() { + row(update = false, wowi = true) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(0) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1) + } + + @Test + fun anUnmanagedRowKeepsTheLocalUpdateAndDelete() { + row(update = null, wowi = true) + compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(1) + compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(0) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt index a26973f87e..ebe743b644 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRule.kt @@ -1,11 +1,15 @@ package com.droiddeck.launcher.ui import android.content.ComponentName +import android.os.Handler +import android.view.Choreographer import androidx.activity.ComponentActivity +import androidx.compose.ui.platform.AndroidUiDispatcher import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.runtime.snapshots.Snapshot import org.robolectric.RuntimeEnvironment import org.robolectric.Shadows.shadowOf +import kotlin.coroutines.ContinuationInterceptor fun createRobolectricComposeRule() = createComposeRule().also { RingVeil.reset() @@ -13,5 +17,46 @@ fun createRobolectricComposeRule() = createComposeRule().also { shadowOf(context.packageManager).addActivityIfNotPresent( ComponentName(context, ComponentActivity::class.java), ) + resumeDroppedUiDispatch() Snapshot.sendApplyNotifications() } + +internal class UiDispatch { + private val type = AndroidUiDispatcher::class.java + private val dispatcher = AndroidUiDispatcher.Main[ContinuationInterceptor] as AndroidUiDispatcher + private fun field(name: String) = type.getDeclaredField(name).apply { isAccessible = true } + val lock: Any = field("lock").get(dispatcher)!! + val handler = field("handler").get(dispatcher) as Handler + val choreographer = field("choreographer").get(dispatcher) as Choreographer + val callback: Any = field("dispatchCallback").get(dispatcher)!! + private val trampolineFlag = field("scheduledTrampolineDispatch") + private val frameFlag = field("scheduledFrameDispatch") + + fun trampolineDropped() = trampolineFlag.getBoolean(dispatcher) && !handler.hasMessages(0) + + fun frameDropped() = frameFlag.getBoolean(dispatcher) && !frameQueued() + + private fun frameQueued(): Boolean { + val queues = Choreographer::class.java.getDeclaredField("mCallbackQueues").apply { isAccessible = true }.get(choreographer) as Array<*> + return queues.any { queue -> + var record = queue?.let { q -> q.javaClass.getDeclaredField("mHead").apply { isAccessible = true }.get(q) } + var found = false + while (record != null && !found) { + val recordType = record.javaClass + found = recordType.getDeclaredField("action").apply { isAccessible = true }.get(record) === callback + record = recordType.getDeclaredField("next").apply { isAccessible = true }.get(record) + } + found + } + } +} + +internal fun uiDispatchDropped(): Boolean = UiDispatch().run { synchronized(lock) { trampolineDropped() || frameDropped() } } + +internal fun resumeDroppedUiDispatch() { + val ui = UiDispatch() + synchronized(ui.lock) { + if (ui.trampolineDropped()) ui.handler.post(ui.callback as Runnable) + if (ui.frameDropped()) ui.choreographer.postFrameCallback(ui.callback as Choreographer.FrameCallback) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt new file mode 100644 index 0000000000..22ee813a5b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/RobolectricComposeRuleTest.kt @@ -0,0 +1,90 @@ +package com.droiddeck.launcher.ui + +import android.os.Looper +import android.view.Choreographer +import androidx.compose.runtime.MutableIntState +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.platform.AndroidUiDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +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.Shadows.shadowOf +import org.robolectric.annotation.Config +import java.time.Duration + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = android.app.Application::class) +class RobolectricComposeRuleTest { + private fun dropPendingUiDispatch() { + val ui = UiDispatch() + ui.handler.removeCallbacksAndMessages(null) + dropPendingFrame() + } + + private fun dropPendingFrame() { + val ui = UiDispatch() + ui.choreographer.removeFrameCallback(ui.callback as Choreographer.FrameCallback) + } + + private fun awaitFrameAfterTrampoline(ran: MutableIntState) { + CoroutineScope(AndroidUiDispatcher.Main).launch { withFrameNanos { ran.intValue++ } } + shadowOf(Looper.getMainLooper()).runOneTask() + } + + @Test + fun uiWorkDroppedByAnEarlierTestsLooperResetRunsAgainForTheNextComposeTest() { + val ran = mutableIntStateOf(0) + CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ } + dropPendingUiDispatch() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(0, ran.intValue) + assertTrue(uiDispatchDropped()) + createRobolectricComposeRule() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aDispatchStillQueuedIsLeftAlone() { + val ran = mutableIntStateOf(0) + CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ } + assertFalse(uiDispatchDropped()) + resumeDroppedUiDispatch() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aFrameDroppedAfterTheTrampolineDrainedRunsAgainForTheNextComposeTest() { + val ran = mutableIntStateOf(0) + awaitFrameAfterTrampoline(ran) + dropPendingFrame() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(0, ran.intValue) + assertTrue(uiDispatchDropped()) + createRobolectricComposeRule() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } + + @Test + fun aFrameStillQueuedIsLeftAlone() { + val ran = mutableIntStateOf(0) + awaitFrameAfterTrampoline(ran) + assertEquals(0, ran.intValue) + assertFalse(uiDispatchDropped()) + resumeDroppedUiDispatch() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(1, ran.intValue) + assertFalse(uiDispatchDropped()) + } +} From 43b17483fb63e8c636b11fe6ede4d490d95ce816 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 04:00:04 -0500 Subject: [PATCH 05/17] fix(addons): read only the needed .toc fields instead of the whole file (#3056) Some addons keep their data as metadata lines in the .toc (one has a 57 MB .toc with 400k "## X-..." lines). Opening the Addons tab read the whole file into one string and kept every metadata line in a map, so each opening allocated 220-270 MB for a moment and could push the app past its heap limit. Stream the .toc line by line, keep only Version and X-WoWI-ID, and stop once both are found. --- .../droiddeck/launcher/runtime/WowAddons.kt | 15 +++++++---- .../launcher/runtime/WowAddonsTest.kt | 27 ++++++++++++++++++- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index b8a9367947..fcdb6525e6 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -45,6 +45,9 @@ object WowAddons { class Origin(val id: String, val version: String) private const val ORIGINS = ".droiddeck-sources" + private const val TOC_VERSION = "Version" + private const val TOC_WOWI_ID = "X-WoWI-ID" + private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID) internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 @@ -81,18 +84,20 @@ object WowAddons { return installed(target).map { name -> val toc = toc(File(target.addOns, name)) val origin = origins[name] - Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"]) + Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID]) } } - internal fun tocFields(text: String): Map { + internal fun tocFields(lines: Sequence, keys: Set = TOC_KEYS): Map { val out = LinkedHashMap() - for (raw in text.lineSequence()) { + for (raw in lines) { val line = raw.trim().removePrefix("\uFEFF") if (!line.startsWith("##") || ':' !in line) continue val key = line.removePrefix("##").substringBefore(':').trim() + if (key !in keys || key in out) continue val value = line.substringAfter(':').trim() - if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value) + if (value.isNotEmpty() && '@' !in value) out[key] = value + if (out.size == keys.size) break } return out } @@ -102,7 +107,7 @@ object WowAddons { val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) } ?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) } ?: tocs.minByOrNull { it.name.length } ?: return emptyMap() - return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap()) + return runCatching { main.bufferedReader().useLines { tocFields(it) } }.getOrDefault(emptyMap()) } internal fun parseOrigins(text: String): Map = text.lineSequence().mapNotNull { line -> diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt index d64880e0d6..f1cee3d958 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt @@ -220,12 +220,37 @@ class WowAddonsTest { } @Test fun tocFieldsReadVersionAndSourceIds() { - val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n") + val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n".lineSequence(), setOf("Version", "X-WoWI-ID", "X-Curse-Project-ID")) assertEquals("1.4.2", fields["Version"]) assertEquals("1234", fields["X-WoWI-ID"]) assertEquals(null, fields["X-Curse-Project-ID"]) } + @Test fun tocFieldsKeepOnlyTheRequestedKeysAndStopOnceFound() { + var read = 0 + val lines = sequence { + yield("## Version: 2.0") + yield("## X-WoWI-ID: 5") + repeat(100_000) { read++; yield("## X-Data-$it: payload") } + } + val fields = WowAddons.tocFields(lines) + assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5"), fields) + assertEquals(0, read) + } + + @Test fun detailsSkipDataRowsInLargeTocs() { + val target = target() + val db = File(target.addOns, "BigDB").apply { mkdirs() } + File(db, "BigDB_Mists.toc").bufferedWriter().use { w -> + w.write("## Title: BigDB\nsrc\\main.lua\n") + repeat(50_000) { w.write("## X-Data-$it: ${"x".repeat(200)}\n") } + w.write("## Version: 3.1\n") + } + val details = WowAddons.details(target).single() + assertEquals("3.1", details.version) + assertEquals(null, details.wowiId) + } + @Test fun detailsUseTheTocAndTheRecordedSource() { val target = target() val foo = File(target.addOns, "Foo").apply { mkdirs() } From c78adda7ca3ec758aac73c219c9f4dec58fd8283 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 05:57:05 -0500 Subject: [PATCH 06/17] fix(addons): show installed addons as installed while the manager rescans (#3057) * fix(addons): show installed addons as installed while the manager rescans Opening the download dialog starts a fresh scan of the addon manager's installed projects, and every row showed Install until it answered (about 20 s). Rows now start from the manager's last report, kept only for projects whose folders are all still on disk, and its new report takes over, Update state included. * fix(addons): match installed addons by their toc project id before the first report Before the addon manager has reported at all, a search row whose project id matches an installed addon's X-Curse-Project-ID shows as installed. Placeholder ids are ignored and the manager's report always takes over. * fix(addons): read toc fields from flavour tocs and keep known state when a scan fails An addon whose main toc is a stub keeps its version and project id in the flavour tocs, so missing fields are now filled from the next toc in order. A failed manager scan now falls back to the last known installed state instead of clearing it. --- .../droiddeck/launcher/runtime/WowAddons.kt | 27 +++++--- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 24 +++++-- .../launcher/runtime/WowAddonsTest.kt | 29 +++++++- .../launcher/ui/CurseLinkReportTest.kt | 68 +++++++++++++++++++ .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 14 ++++ 5 files changed, 148 insertions(+), 14 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt index fcdb6525e6..35536449ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/WowAddons.kt @@ -40,14 +40,15 @@ object WowAddons { class Addon(val name: String, val root: String) - class Installed(val name: String, val version: String?, val wowiId: String?) + class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null) class Origin(val id: String, val version: String) private const val ORIGINS = ".droiddeck-sources" private const val TOC_VERSION = "Version" private const val TOC_WOWI_ID = "X-WoWI-ID" - private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID) + private const val TOC_CURSE_ID = "X-Curse-Project-ID" + private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID) internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 @@ -84,7 +85,7 @@ object WowAddons { return installed(target).map { name -> val toc = toc(File(target.addOns, name)) val origin = origins[name] - Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID]) + Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID]) } } @@ -103,11 +104,21 @@ object WowAddons { } private fun toc(folder: File): Map { - val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) } - val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) } - ?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) } - ?: tocs.minByOrNull { it.name.length } ?: return emptyMap() - return runCatching { main.bufferedReader().useLines { tocFields(it) } }.getOrDefault(emptyMap()) + val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith( + compareBy( + { !it.name.dropLast(4).equals(folder.name, ignoreCase = true) }, + { !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }, + { it.name.length }, + { it.name }, + ), + ) + val out = LinkedHashMap() + for (file in tocs) { + if (out.size == TOC_KEYS.size) break + val missing = TOC_KEYS - out.keys + runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll) + } + return out } internal fun parseOrigins(text: String): Map = text.lineSequence().mapNotNull { line -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index ee4f5eb1db..de9322f069 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -80,6 +80,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference @@ -118,11 +119,17 @@ internal class CurseLink(val app: UserApps.App) { fun installed(context: Context, target: WowAddons.Target, key: Any): List = CurseForgeApp.onDisk( synchronized(scanLock) { scans[target.addOns.path]?.takeIf { it.first == key }?.second - ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { scans[target.addOns.path] = key to it } + ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { + scans[target.addOns.path] = key to it + report(target, it) + } }, target.addOns, ) + fun marks(context: Context, target: WowAddons.Target, key: Any): Map = + runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) } + fun call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T { val linked = synchronized(lock) { link(context, target, launch) } try { @@ -190,6 +197,16 @@ internal class CurseLink(val app: UserApps.App) { companion object { private val current = AtomicReference() + private val reported = ConcurrentHashMap>() + + fun lastReported(target: WowAddons.Target, disk: () -> List = { WowAddons.details(target) }): Map { + val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null } + return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null } + } + + internal fun report(target: WowAddons.Target, projects: List) { + reported[target.addOns.path] = projects + } fun live(): CurseLink? = current.get() } @@ -250,10 +267,9 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) { val into = target val key = curse to into.addOns + if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) } value = key to withContext(Dispatchers.IO) { - if (curse != null && link != null) Present(curse = runCatching { - link.installed(context, into, scanKey).associate { it.id to curseMark(it) } - }.getOrDefault(emptyMap())) + if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey)) else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) } } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt index f1cee3d958..6ea502407e 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/WowAddonsTest.kt @@ -231,10 +231,11 @@ class WowAddonsTest { val lines = sequence { yield("## Version: 2.0") yield("## X-WoWI-ID: 5") + yield("## X-Curse-Project-ID: 9") repeat(100_000) { read++; yield("## X-Data-$it: payload") } } val fields = WowAddons.tocFields(lines) - assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5"), fields) + assertEquals(mapOf("Version" to "2.0", "X-WoWI-ID" to "5", "X-Curse-Project-ID" to "9"), fields) assertEquals(0, read) } @@ -254,15 +255,39 @@ class WowAddonsTest { @Test fun detailsUseTheTocAndTheRecordedSource() { val target = target() val foo = File(target.addOns, "Foo").apply { mkdirs() } - File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n") + File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n## X-Curse-Project-ID: 334372\n") File(target.addOns, "Bar").mkdirs() val details = WowAddons.details(target).associateBy { it.name } assertEquals(setOf("Bar", "Foo"), details.keys) assertEquals("1.0", details.getValue("Foo").version) assertEquals("77", details.getValue("Foo").wowiId) + assertEquals("334372", details.getValue("Foo").curseId) + assertEquals(null, details.getValue("Bar").curseId) assertEquals(null, details.getValue("Bar").version) } + @Test fun detailsFillFieldsTheMainTocLacksFromTheFlavourTocs() { + val target = target() + val questie = File(target.addOns, "Questie").apply { mkdirs() } + File(questie, "Questie.toc").writeText("## Interface: 00000\n## Title: Questie\n") + File(questie, "Questie_Vanilla.toc").writeText("## Version: 12.6.4\n## X-Curse-Project-ID: 334372\n") + File(questie, "Questie_Wrath.toc").writeText("## Version: 12.6.4\n") + val questieDetails = WowAddons.details(target).single() + assertEquals("12.6.4", questieDetails.version) + assertEquals("334372", questieDetails.curseId) + } + + @Test fun detailsKeepTheMainTocWhenItHasTheFields() { + val target = target() + val foo = File(target.addOns, "Foo").apply { mkdirs() } + File(foo, "Foo.toc").writeText("## Version: 2.0\n## X-Curse-Project-ID: 5\n") + File(foo, "Foo_Classic.toc").writeText("## Version: 1.0\n## X-Curse-Project-ID: 6\n## X-WoWI-ID: 7\n") + val fooDetails = WowAddons.details(target).single() + assertEquals("2.0", fooDetails.version) + assertEquals("5", fooDetails.curseId) + assertEquals("7", fooDetails.wowiId) + } + @Test fun importRecordsTheSourceAndPlainImportsClearIt() { val target = target() WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0")) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt new file mode 100644 index 0000000000..7fee7a4f87 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkReportTest.kt @@ -0,0 +1,68 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.runtime.CurseForgeApp +import com.droiddeck.launcher.runtime.WowAddons +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class CurseLinkReportTest { + @get:Rule val temp = TemporaryFolder() + + private fun target(vararg folders: String): WowAddons.Target { + val addOns = temp.newFolder("AddOns") + folders.forEach { java.io.File(addOns, it).mkdirs() } + return WowAddons.Target("_retail_", addOns) + } + + private fun project(id: String, vararg folders: String, update: Boolean = false) = CurseForgeApp.Project(id, "m$id", folders.toList(), update) + + @Test fun beforeAnyReportNothingIsKnown() { + assertEquals(emptyMap(), CurseLink.lastReported(target("Questie"))) + } + + @Test fun beforeCurseForgeReportsAddonsWhoseFoldersAreAllOnDiskShowAsInstalled() { + val target = target("questie", "QuestieDB", "Auctionator") + CurseLink.report(target, listOf( + project("334372", "Questie", "QuestieDB", update = true), + project("1", "Auctionator"), + project("2", "Details", "Details_Streamer"), + project("3", "Auctionator", "Auctionator_Extra"), + )) + assertEquals(mapOf("334372" to null, "1" to null), CurseLink.lastReported(target)) + } + + @Test fun anAddonRemovedFromDiskSinceTheLastReportIsNotInstalled() { + val target = target("Questie") + CurseLink.report(target, listOf(project("334372", "Questie"))) + java.io.File(target.addOns, "Questie").delete() + assertEquals(emptyMap(), CurseLink.lastReported(target)) + } + + private fun toc(target: WowAddons.Target, folder: String, curseId: String) { + val dir = java.io.File(target.addOns, folder).apply { mkdirs() } + java.io.File(dir, "$folder.toc").writeText("## Interface: 110207\n## Title: $folder\n## X-Curse-Project-ID: $curseId\n$folder.lua\n") + } + + @Test fun beforeAnyReportAnAddonWhoseTocNamesTheProjectShowsAsInstalled() { + val target = target() + toc(target, "Questie", "334372") + toc(target, "Auctionator", "@project-id@") + assertEquals(mapOf("334372" to null), CurseLink.lastReported(target)) + } + + @Test fun aPlaceholderProjectIdIsIgnored() { + val target = target() + toc(target, "Auctionator", "@project-id@") + assertEquals(emptyMap(), CurseLink.lastReported(target)) + } + + @Test fun curseForgesReportOverridesTheTocProjectId() { + val target = target() + toc(target, "Questie", "334372") + toc(target, "Auctionator", "1") + CurseLink.report(target, listOf(project("1", "Auctionator", update = true))) + assertEquals(mapOf("1" to null), CurseLink.lastReported(target)) + } +} 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 39eb286fea..16d4c35e9c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -128,6 +128,20 @@ class CurseLinkTabTest { } } + @Test + fun aFailedScanKeepsTheLastReportInsteadOfClearingIt() { + val target = wow() + val link = CurseLink(app) + try { + val reported = link.marks(context, target, 0) + assertTrue(reported.isNotEmpty()) + runBlocking { link.close(context).join() } + assertEquals(reported.mapValues { null }, link.marks(context, target, 1)) + } finally { + runBlocking { link.close(context).join() } + } + } + @Test fun noCurseForgeStartsWhileASessionRuns() { wow() From 6400a9ef098d2cd583e830e4ae1b07857c263522 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 06:47:25 -0500 Subject: [PATCH 07/17] fix(addons): uninstall addons the manager has not listed yet (#3060) A row shown as installed by its toc project id before the manager's first report had nothing to delete when the manager did not list the project, and the dialog reported success. The dialog now falls back to the folders whose toc names the project, deletes them through the existing addon delete, and shows the delete error when no folder matches. --- .../com/droiddeck/launcher/ui/AddonBrowser.kt | 16 +++++-- .../droiddeck/launcher/ui/CurseLinkTabTest.kt | 46 +++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt index de9322f069..5251fb12bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddonBrowser.kt @@ -80,6 +80,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File +import java.io.IOException import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference @@ -367,10 +368,10 @@ internal fun AddonBrowserDialog(targets: List, initial: WowAdd scope.launch { val done = withContext(Dispatchers.IO) { runCatching { - val folders = if (via != null) via.call(context, into) { linked -> + val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked -> CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty() - } else addon.folders - folders.forEach { name -> WowAddons.folder(into.addOns, name)?.let { deleteAddon(context, into, it.name, link) } } + }) else addon.folders + deleteAddons(context, into, folders, link) } } installing.remove(key) @@ -589,6 +590,15 @@ internal fun diskStatus(folders: List, onDisk: Map): List = + listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } } + +internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List, link: CurseLink?) { + val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) } + if (found.isEmpty()) throw IOException("No addon folder to delete") + found.forEach { deleteAddon(context, target, it.name, link) } +} + internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) { val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true val left = WowAddons.folder(target.addOns, folder) 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 16d4c35e9c..0ea4048e3a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CurseLinkTabTest.kt @@ -19,7 +19,9 @@ import org.json.JSONArray import org.json.JSONObject import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -29,6 +31,9 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.LinkOption import java.util.Collections @RunWith(RobolectricTestRunner::class) @@ -142,6 +147,47 @@ class CurseLinkTabTest { } } + private fun tocFolder(addOns: File, name: String, curseId: String) = + File(addOns, name).apply { mkdirs(); File(this, "$name.toc").writeText("## X-Curse-Project-ID: $curseId\n") } + + @Test + fun anAddonTheManagerDoesNotListIsFoundByItsTocProjectId() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Questie", "334372") + tocFolder(target.addOns, "Other", "1") + assertEquals(listOf("Questie"), curseFolders(target, "334372", emptyList())) + assertEquals(listOf("Listed"), curseFolders(target, "334372", listOf("Listed"))) + } + + @Test + fun uninstallingByTocProjectIdDeletesOnlyTheMatchedFolders() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Questie", "334372") + tocFolder(target.addOns, "Other", "1") + deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) + assertEquals(listOf("Other"), WowAddons.installed(target)) + } + + @Test + fun uninstallingALinkedAddonLeavesTheLinkTargetAlone() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + val outside = tocFolder(temp.newFolder("outside"), "Questie", "334372") + File(outside, "keep.lua").writeText("keep") + Files.createSymbolicLink(File(target.addOns, "Questie").toPath(), outside.toPath()) + deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) + assertFalse(Files.exists(File(target.addOns, "Questie").toPath(), LinkOption.NOFOLLOW_LINKS)) + assertEquals("keep", File(outside, "keep.lua").readText()) + assertTrue(File(outside, "Questie.toc").isFile) + } + + @Test + fun uninstallingWithNothingToDeleteFails() { + val target = WowAddons.Target("_retail_", temp.newFolder("AddOns")) + tocFolder(target.addOns, "Other", "1") + assertThrows(IOException::class.java) { deleteAddons(context, target, curseFolders(target, "334372", emptyList()), null) } + assertEquals(listOf("Other"), WowAddons.installed(target)) + } + @Test fun noCurseForgeStartsWhileASessionRuns() { wow() From 2478c449482d247b0663a633f61db979b35cc784 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 07:20:33 -0500 Subject: [PATCH 08/17] fix(fex): free host signal state when a guest leaves its handler (#3052) * fix(fex): free host signal state when a guest leaves its handler FEX keeps each signal's host context on the host stack and frees it only on rt_sigreturn. A guest that leaves its handler another way (siglongjmp, or CoreCLR resuming a catch after a NullReferenceException) left about 2 KB of host stack and one SignalHandlerRefCounter count behind. Some 3500 such exceptions on one thread overran the guard-less 8 MB host stack, and the CurseForge agent died with "Internal CLR error. (0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second addon scan. 0009 chains each thread's signal frames with the guest frame range and alternate stack they used. A signal that arrives in JIT code at the host level of the newest frame, after the guest stack pointer has left that frame, drops the left frames and stores its context where the newest live frame (or the dispatcher entry) left the host stack. rt_sigreturn pops its frame and any newer ones it skips; thread stop clears the chain. Signals inside system calls or thunk callbacks are left alone. This follows the approach suggested in FEX-Emu/FEX#2487. 0008 now restores InSyscallInfo only for signals that interrupted JIT code, the only case that saves it. Restoring 0 for a signal that interrupted a system call cleared the mark while the call was still running; an itimer loop around time() crashed in 15 of 15 runs. Pocket FIT Elite: siglongjmp out of a SIGSEGV handler died after about 3500 iterations under FEX-2611.1 with and without 0008 and finishes 200000 with 0009; the new probe (350000 escapes on and off the alternate stack, mixed with returning handlers and nested handlers) finishes under 0009 and crashes before 2000 iterations without it. The 0008 probe still reports no stale registers. * test(fex): check every delivery hunk of the 0009 patch * fix(fex): reset the host stack when a system call ends a block * fix(fex): thunk calls mark the guest state as spilled * fix(fex): signal returns apply the handler's register changes * docs(fex): describe patches 0010 to 0012 and credit the upstream fix * test(fex): require AVX2 for the ymm probe and keep vdso canaries live --- README.md | 2 +- docs/development/x86-64-steam-client.md | 64 ++++++- ...signal-return-restores-syscall-state.patch | 16 +- ...gnal-handler-escape-frees-host-stack.patch | 174 ++++++++++++++++++ .../0010-syscall-exit-resets-host-stack.patch | 23 +++ .../0011-thunk-calls-mark-spilled-state.patch | 109 +++++++++++ ...ignal-return-applies-guest-registers.patch | 112 +++++++++++ tools/fex/probes/signal-handler-escape.c | 90 +++++++++ tools/fex/probes/signal-register-update.c | 88 +++++++++ tools/fex/probes/syscall-host-stack.c | 65 +++++++ tools/fex/probes/vdso-signal-state.c | 49 +++++ tools/tests/test_fex_signal_handler_escape.py | 117 ++++++++++++ .../tests/test_fex_signal_register_update.py | 134 ++++++++++++++ tools/tests/test_fex_signal_syscall_state.py | 12 +- tools/tests/test_fex_syscall_host_stack.py | 67 +++++++ tools/tests/test_fex_thunk_signal_state.py | 124 +++++++++++++ 16 files changed, 1234 insertions(+), 12 deletions(-) create mode 100644 tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch create mode 100644 tools/fex/patches/0010-syscall-exit-resets-host-stack.patch create mode 100644 tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch create mode 100644 tools/fex/patches/0012-signal-return-applies-guest-registers.patch create mode 100644 tools/fex/probes/signal-handler-escape.c create mode 100644 tools/fex/probes/signal-register-update.c create mode 100644 tools/fex/probes/syscall-host-stack.c create mode 100644 tools/fex/probes/vdso-signal-state.c create mode 100644 tools/tests/test_fex_signal_handler_escape.py create mode 100644 tools/tests/test_fex_signal_register_update.py create mode 100644 tools/tests/test_fex_syscall_host_stack.py create mode 100644 tools/tests/test_fex_thunk_signal_state.py diff --git a/README.md b/README.md index b6f80f6220..a1094c8d14 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,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. +- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - `WriteProcessMemory` hooks fall back to `/proc//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index 3d7876c2f5..d4b99759d5 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -228,7 +228,69 @@ alone would then read as an installed client. context, so x86-64 .NET programs failed at random (`AccessViolationException` in whatever code ran next, then SIGABRT). `tools/fex/probes/async-signal-context.c` shows it: under FEX-2611.1 one signal in 2000 carried the interrupted registers, natively all of them. The return now restores the value saved - when the signal arrived. + when the signal arrived, and only when the signal interrupted JIT code, which is the only case that + saves it. Restoring it for a signal that interrupted a system call cleared the mark while that call + was still running, so the next signal in the call's return path spilled clobbered registers: + `setitimer` at 100 Hz around `time()` crashed in 15 of 15 runs, and with the guard as often as the + same build without the patch (about half; a separate crash that FEX-2611.1 also shows). + - `0009-signal-handler-escape-frees-host-stack`: FEX keeps each signal's host context on the host + stack and frees it only on `rt_sigreturn`. A guest that leaves its handler another way (`siglongjmp`, + or CoreCLR resuming a `catch` after a NullReferenceException) left that 2 KB block and one + `SignalHandlerRefCounter` count behind. About 3500 such exceptions on one thread overran the 8 MB + host stack, which has no guard page, and the CurseForge agent died with "Internal CLR error. + (0x80131506)" and "Stack overflow occurred on the same thread again!" at the start of its second + addon scan. FEX now chains each thread's signal frames with the guest frame range and alternate + stack they used. When a signal arrives in JIT code that runs at the host level of the newest frame + and the guest stack pointer shows the guest has left that frame (above its frame, or back off the + alternate stack above where the outermost frame on it interrupted), the left frames are dropped and + the new context is stored where the newest live frame (or the dispatcher entry) left the host stack. + `rt_sigreturn` pops its frame and any newer ones it skips. Signals that arrive inside system calls or + thunk callbacks are left alone. `tools/fex/probes/signal-handler-escape.c` leaves handlers on and + off the alternate stack, mixes them with handlers that return, and leaves nested handlers: FEX-2611.1 + with 0001 to 0008 crashed (SIGSEGV) before 2000 iterations of it, and `siglongjmp` out of a SIGSEGV + handler died after about 3500; with this patch 350000 escapes and 200000 straight `siglongjmp`s + finish, as natively. The approach is the one suggested in FEX-Emu/FEX#2487. + - `0010-syscall-exit-resets-host-stack` (`Fixed-upstream: FEX-2612`): a backport of FEX's + "JIT: Ensure IR ops that jump out of the JIT reset the stack" (FEX-Emu/FEX#6122). A system call or + code-entry removal that ends a block jumps to the dispatcher without dropping the block's spill + slots, and the syscall handler's fast path branches straight into the next block, so every such + exit leaked up to 32 bytes per spill slot of host stack. AVX and MMX code keeps enough values live to + spill, and `tools/fex/probes/syscall-host-stack.c` overran the 8 MB host stack after about 65000 + system calls; with the patch 2000000 finish, as natively. The CPUID hunk of the upstream commit is + left out, since CPUID returns to the JIT in 2611. + - `0011-thunk-calls-mark-spilled-state`: a thunk call (every vDSO `clock_gettime`, `gettimeofday` + and `time`, and the host library thunks) spills the static registers to the guest frame and calls + host code, which clobbers the caller-saved host registers. A signal that arrived in the JIT code + after the host call returned and before the registers were refilled took the interrupted state from + those clobbered host registers: the guest handler got garbage registers, and the interrupted code + resumed with them, or FEX built the signal frame at a garbage stack pointer and crashed. The thunk + call now marks every static register as spilled (`InSyscallInfo = 0xFFFF`, as the system call + handler does) until the refill ends, and a fully spilled mark takes only RIP from the host PC and + leaves the frame's GPRs, vector registers and flags alone (the 16-bit mask could not name the + x16/x17 and v16 to v31 registers the host call clobbers). Every guest signal now saves and clears the + mark, so guest handlers and nested signals never inherit it, and every return puts back the value it + saved; 0008 restored it only for JIT code because the other paths saved none. A handler that changes + RIP restarts at the dispatcher with no mark, and thunk callbacks into guest code run with none. + `tools/fex/probes/vdso-signal-state.c` calls `clock_gettime` under a 1 kHz `SIGALRM` and checks the + values held across each call: FEX-2611 crashed in 3 of 8 runs, with 0001 to 0010 in 7 of 8; with + this patch 0 of 28, as natively. This was the "separate crash" noted under 0008. + - `0012-signal-return-applies-guest-registers`: a signal return that kept RIP threw away every + register change the guest handler made in its `ucontext`; only a changed RIP made FEX reload the + guest state from it. CoreCLR suspends threads for garbage collection with a signal and, in fully + interruptible code, runs the collection from that handler and writes the moved object references + back into the interrupted registers, so under FEX the thread resumed with pointers into the old heap. + The CurseForge agent's crashes during parallel addon scans (an `AccessViolationException` in + `Curse.Hashing.MurmurHash2.ComputeHash` or `RegexInterpreter`, or "Internal CLR error. (0x80131506)" + with a stack overflow) look like this, but they still happen with this patch, so it is not a fix for + them. When RIP is + unchanged, each guest GPR the handler changed is now written where the resumed code reads it: the + guest frame for registers the interrupted code had spilled (all of them inside a system call or + thunk call), otherwise the static host register. Unchanged registers are left alone, signals that + interrupted code outside the JIT (and not inside a system call or thunk call) keep the old + behaviour, and 32-bit frames compare and write only the low 32 bits. `tools/fex/probes/signal-register-update.c` + spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): + FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all + three see it on the first signal, as natively. - **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/0008-signal-return-restores-syscall-state.patch b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch index 6a8e14e1d0..6592a94550 100644 --- a/tools/fex/patches/0008-signal-return-restores-syscall-state.patch +++ b/tools/fex/patches/0008-signal-return-restores-syscall-state.patch @@ -1,12 +1,18 @@ diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -index b4c7b24..e6777aa 100644 +index b4c7b24..643185d 100644 --- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp -@@ -262,6 +262,7 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr - - if (Context->UContextLocation) { +@@ -264,12 +264,13 @@ void SignalDelegator::RestoreThreadState(FEXCore::Core::InternalThreadState* Thr auto Frame = Thread->CurrentFrame; -+ Frame->InSyscallInfo = Context->InSyscallInfo; if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { // 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; + } + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); + } else { + if (Type == RestoreType::TYPE_NONREALTIME) { 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 new file mode 100644 index 0000000000..fbeec5ec96 --- /dev/null +++ b/tools/fex/patches/0009-signal-handler-escape-frees-host-stack.patch @@ -0,0 +1,174 @@ +diff --git a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +index 02bb6bf..2e72492 100644 +--- a/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h ++++ b/Source/Tools/LinuxEmulation/ArchHelpers/MContext.h +@@ -49,6 +49,11 @@ struct X86ContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + static constexpr int RedZoneSize = 128; + }; +@@ -76,6 +81,11 @@ struct ArmContextBackup { + uint64_t FPStateLocation; + uint64_t UContextLocation; + uint64_t SigInfoLocation; ++ uint64_t PrevGuestFrame; ++ uint64_t GuestFrameEnd; ++ uint64_t GuestInterruptedSP; ++ uint64_t GuestAltBase; ++ uint64_t GuestAltEnd; + FEXCore::Core::CPUState GuestState; + + // 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 +--- 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* + #endif + } + ++namespace { ++ bool OnGuestAltStack(const ArchHelpers::Context::ContextBackup* Backup, uint64_t SP) { ++ return Backup->GuestAltEnd != 0 && SP >= Backup->GuestAltBase && SP <= Backup->GuestAltEnd; ++ } ++ ++ bool GuestLeftFrame(const ArchHelpers::Context::ContextBackup* Backup, uint64_t GuestSP, uint32_t Limit) { ++ const bool SPOnAlt = OnGuestAltStack(Backup, GuestSP); ++ if (SPOnAlt == OnGuestAltStack(Backup, Backup->GuestFrameEnd)) { ++ return GuestSP >= Backup->GuestFrameEnd; ++ } ++ if (SPOnAlt) { ++ return false; ++ } ++ auto Entry = Backup; ++ while (OnGuestAltStack(Backup, Entry->GuestInterruptedSP)) { ++ if (--Limit == 0 || !Entry->PrevGuestFrame) { ++ return false; ++ } ++ Entry = reinterpret_cast(Entry->PrevGuestFrame); ++ } ++ return OnGuestAltStack(Backup, Entry->GuestFrameEnd) && Entry->GuestAltBase == Backup->GuestAltBase && ++ Entry->GuestAltEnd == Backup->GuestAltEnd && GuestSP >= Entry->GuestInterruptedSP; ++ } ++} ++ + 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 + } + + OldSP = *reinterpret_cast(GuestSP); ++ ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; ++ uint64_t Entry = SignalInfo.GuestFrames; ++ for (uint32_t Depth = 1; Entry && Depth <= SignalInfo.GuestFrameCount; ++Depth) { ++ auto EntryBackup = reinterpret_cast(Entry); ++ if (Entry == OldSP) { ++ SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame; ++ SignalInfo.GuestFrameCount -= Depth; ++ Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1; ++ break; ++ } ++ Entry = EntryBackup->PrevGuestFrame; ++ } + } + + uintptr_t NewSP = OldSP; +@@ -287,6 +325,7 @@ bool SignalDelegator::HandleDispatcherGuestSignal(FEXCore::Core::InternalThreadS + auto ContextBackup = StoreThreadState(Thread, Signal, ucontext); + + auto Frame = Thread->CurrentFrame; ++ auto& SignalInfo = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread)->SignalInfo; + + // 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 + + uint64_t OldGuestSP = Frame->State.gregs[FEXCore::X86State::REG_RSP]; + uint64_t NewGuestSP = OldGuestSP; ++ uint64_t GuestAltBase = 0; ++ uint64_t GuestAltEnd = 0; + + // 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 + // 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; ++ GuestAltBase = AltStackBase; ++ GuestAltEnd = AltStackEnd; + 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 + } + } + ++#ifdef ARCHITECTURE_arm64 ++ auto Newest = reinterpret_cast(SignalInfo.GuestFrames); ++ if (WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames && ++ Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1 && GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount)) { ++ uint32_t LeftFrames = 0; ++ while (Newest && LeftFrames < SignalInfo.GuestFrameCount && ++ GuestLeftFrame(Newest, OldGuestSP, SignalInfo.GuestFrameCount - LeftFrames)) { ++ Newest = reinterpret_cast(Newest->PrevGuestFrame); ++ ++LeftFrames; ++ } ++ ++ const uint64_t HostTop = Newest ? reinterpret_cast(Newest) : Frame->ReturningStackLocation; ++ const uint64_t MovedBackup = FEXCore::AlignDown( ++ HostTop - ArchHelpers::Context::ContextBackup::RedZoneSize - sizeof(ArchHelpers::Context::ContextBackup), 16); ++ if (MovedBackup > reinterpret_cast(ContextBackup)) { ++ memmove(reinterpret_cast(MovedBackup), ContextBackup, sizeof(ArchHelpers::Context::ContextBackup)); ++ ContextBackup = reinterpret_cast(MovedBackup); ++ ContextBackup->PrevSP = HostTop; ++ ArchHelpers::Context::SetSp(ucontext, MovedBackup); ++ SignalInfo.GuestFrames = reinterpret_cast(Newest); ++ SignalInfo.GuestFrameCount -= LeftFrames; ++ Frame->SignalHandlerRefCounter -= LeftFrames; ++ } ++ } ++#endif ++ ++ ContextBackup->GuestFrameEnd = NewGuestSP; ++ ContextBackup->GuestInterruptedSP = OldGuestSP; ++ ContextBackup->GuestAltBase = GuestAltBase; ++ ContextBackup->GuestAltEnd = GuestAltEnd; ++ ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames; ++ SignalInfo.GuestFrames = reinterpret_cast(ContextBackup); ++ ++SignalInfo.GuestFrameCount; ++ + // siginfo_t + siginfo_t* HostSigInfo = reinterpret_cast(info); + +@@ -491,6 +568,8 @@ bool SignalDelegator::HandleSignalPause(FEXCore::Core::InternalThreadState* Thre + + // Our ref counting doesn't matter anymore + Thread->CurrentFrame->SignalHandlerRefCounter = 0; ++ ThreadObject->SignalInfo.GuestFrames = 0; ++ ThreadObject->SignalInfo.GuestFrameCount = 0; + + // 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 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h +@@ -83,6 +83,9 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators { + // Queue of thread local signal frames that have been deferred. + // Async signals aren't guaranteed to be delivered in any particular order, but FEX treats them as FILO. + fextl::vector DeferredSignalFrames; ++ ++ uint64_t GuestFrames {}; ++ uint32_t GuestFrameCount {}; + } SignalInfo {}; + + // Seccomp thread specific data. diff --git a/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch new file mode 100644 index 0000000000..790a5390d8 --- /dev/null +++ b/tools/fex/patches/0010-syscall-exit-resets-host-stack.patch @@ -0,0 +1,23 @@ +Fixed-upstream: FEX-2612 +diff --git a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +index c2b1d8e287..fcdf261484 100644 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -285,6 +285,8 @@ DEF_OP(CondJump) { + DEF_OP(Syscall) { + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Jump to the syscall dispatch handler. We won't return after this. + ldr(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, Pointers.ThreadDispatchSyscallHandler)); + br(TMP1); +@@ -376,6 +378,8 @@ DEF_OP(ThreadRemoveCodeEntry) { + + SpillStaticRegs(TMP1); + ++ ResetStack(); ++ + // Store the new RIP to go to. + str(GetReg(Op->NewRIP).X(), STATE, offsetof(FEXCore::Core::CpuStateFrame, State.rip)); + diff --git a/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch new file mode 100644 index 0000000000..626c726b59 --- /dev/null +++ b/tools/fex/patches/0011-thunk-calls-mark-spilled-state.patch @@ -0,0 +1,109 @@ +diff --git a/FEXCore/Source/Interface/Core/Core.cpp b/FEXCore/Source/Interface/Core/Core.cpp +--- a/FEXCore/Source/Interface/Core/Core.cpp ++++ b/FEXCore/Source/Interface/Core/Core.cpp +@@ -383,7 +383,11 @@ + } + + void ContextImpl::HandleCallback(FEXCore::Core::InternalThreadState* Thread, uint64_t RIP) { +- static_cast(Thread->CTX)->Dispatcher->ExecuteJITCallback(Thread->CurrentFrame, RIP); ++ auto Frame = Thread->CurrentFrame; ++ const auto InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ static_cast(Thread->CTX)->Dispatcher->ExecuteJITCallback(Frame, RIP); ++ Frame->InSyscallInfo = InSyscallInfo; + } + + 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 +--- a/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp ++++ b/FEXCore/Source/Interface/Core/JIT/BranchOps.cpp +@@ -305,6 +305,9 @@ + + PushDynamicRegs(TMP1); + ++ LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF); ++ str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); ++ + mov(ARMEmitter::Size::i64Bit, ARMEmitter::Reg::r0, GetReg(Op->ArgPtr)); + + InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash); +@@ -320,6 +323,8 @@ + FillStaticRegs({ + .NZCV = false, + }); ++ ++ str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo)); + } + + DEF_OP(ValidateCode) { +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp +@@ -107,6 +107,10 @@ + #ifdef ARCHITECTURE_arm64 + Thread->CurrentFrame->State.rip = CTX->RestoreRIPFromHostPC(Thread, ArchHelpers::Context::GetPc(ucontext)); + ++ if ((IgnoreMask & 0xFFFF) == 0xFFFF) { ++ return; ++ } ++ + for (size_t i = 0; i < Config.SRAGPRCount; i++) { + const uint8_t SRAIdxMap = Config.SRAGPRMapping[i]; + if (IgnoreMask & (1U << SRAIdxMap)) { +@@ -301,12 +305,10 @@ + if (Context->UContextLocation) { + auto Frame = Thread->CurrentFrame; + +- if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) { +- // 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; +- } ++ // 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; + + if (Is64BitMode) { + RestoreFrame_x64(Thread, Context, Frame, ucontext); +@@ -361,6 +363,9 @@ + ContextBackup->InSyscallInfo = Thread->CurrentFrame->InSyscallInfo; + Thread->CurrentFrame->InSyscallInfo = 0; + } else { ++ ContextBackup->InSyscallInfo = Frame->InSyscallInfo; ++ Frame->InSyscallInfo = 0; ++ + if (!IsAddressInDispatcher(OldPC)) { + // 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 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -131,7 +131,7 @@ + if (Context->OriginalRIP != guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_RIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ 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 +@@ -211,7 +211,7 @@ + // 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. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ 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 +@@ -290,7 +290,7 @@ + if (Context->OriginalRIP != guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_EIP] || Context->FaultToTopAndGeneratedException) { + + // Restore previous `InSyscallInfo` structure. +- Frame->InSyscallInfo = Context->InSyscallInfo; ++ 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 diff --git a/tools/fex/patches/0012-signal-return-applies-guest-registers.patch b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch new file mode 100644 index 0000000000..d97a75bee3 --- /dev/null +++ b/tools/fex/patches/0012-signal-return-applies-guest-registers.patch @@ -0,0 +1,112 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h +@@ -263,6 +263,8 @@ + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); + void RestoreRTFrame_ia32(FEXCore::Core::InternalThreadState* Thread, ArchHelpers::Context::ContextBackup* Context, + FEXCore::Core::CpuStateFrame* Frame, void* ucontext); ++ void ResumeWithGuestGPRs(ArchHelpers::Context::ContextBackup* Context, FEXCore::Core::CpuStateFrame* Frame, void* ucontext, ++ const uint64_t* GuestGPRs, size_t Count, uint64_t Mask); + + ///< 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 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp +@@ -122,6 +122,32 @@ + } + } + ++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 bool AllSpilled = Spilled == 0xFFFF; ++ if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) { ++ return; ++ } ++ ++ for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) { ++ const uint8_t HostReg = Config.SRAGPRMapping[i]; ++ const bool InFrame = AllSpilled || (Spilled & (1U << HostReg)); ++ const uint64_t Delivered = InFrame ? Frame->State.gregs[i] : ArchHelpers::Context::GetArmReg(ucontext, HostReg); ++ if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) { ++ continue; ++ } ++ ++ if (InFrame) { ++ Frame->State.gregs[i] = GuestGPRs[i]; ++ } else { ++ ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]); ++ } ++ } ++#endif ++} ++ + 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 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], sizeof(Frame->State.mm[0])); + } ++ } else { ++ uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS]; ++#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x]; ++ COPY_REG(R8); ++ COPY_REG(R9); ++ COPY_REG(R10); ++ COPY_REG(R11); ++ COPY_REG(R12); ++ COPY_REG(R13); ++ COPY_REG(R14); ++ COPY_REG(R15); ++ COPY_REG(RDI); ++ COPY_REG(RSI); ++ COPY_REG(RBP); ++ COPY_REG(RBX); ++ COPY_REG(RDX); ++ COPY_REG(RAX); ++ COPY_REG(RCX); ++ COPY_REG(RSP); ++#undef COPY_REG ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL); + } + } + +@@ -280,6 +327,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->sc.ax; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->sc.cx; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->sc.dx; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->sc.bx; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->sc.sp; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->sc.bp; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->sc.si; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->sc.di; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + +@@ -359,6 +417,17 @@ + const auto modulo_i = (i + CurrentOffset) % 8; + memcpy(&Frame->State.mm[modulo_i], &fpstate->_st[i], 10); + } ++ } else { ++ uint64_t GuestGPRs[8]; ++ GuestGPRs[FEXCore::X86State::REG_RAX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RAX]; ++ GuestGPRs[FEXCore::X86State::REG_RCX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RCX]; ++ GuestGPRs[FEXCore::X86State::REG_RDX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDX]; ++ GuestGPRs[FEXCore::X86State::REG_RBX] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBX]; ++ GuestGPRs[FEXCore::X86State::REG_RSP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSP]; ++ GuestGPRs[FEXCore::X86State::REG_RBP] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RBP]; ++ GuestGPRs[FEXCore::X86State::REG_RSI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RSI]; ++ GuestGPRs[FEXCore::X86State::REG_RDI] = guest_uctx->uc.uc_mcontext.gregs[FEXCore::x86::FEX_REG_RDI]; ++ ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL); + } + } + diff --git a/tools/fex/probes/signal-handler-escape.c b/tools/fex/probes/signal-handler-escape.c new file mode 100644 index 0000000000..71e1a12fca --- /dev/null +++ b/tools/fex/probes/signal-handler-escape.c @@ -0,0 +1,90 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +static sigjmp_buf main_env, inner_env; +static volatile int depth, nested_mode; +static volatile long escapes, nested, returns, wrong; + +static void fault(long i) { + *(volatile int *)(long)(8 + (i & 7)) = 1; +} + +static void segv(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + if (!nested_mode) { + escapes++; + siglongjmp(main_env, 1); + } + if (depth == 1) { + nested++; + siglongjmp(inner_env, 1); + } + depth = 1; + for (volatile int k = 0; k < 3; k++) + if (sigsetjmp(inner_env, 0) == 0) + fault(k); + depth = 0; + escapes++; + siglongjmp(main_env, 1); +} + +static void trap(int sig, siginfo_t *info, void *context) { + (void)sig; + (void)info; + (void)context; + returns++; +} + +static void install(int onstack) { + struct sigaction action; + memset(&action, 0, sizeof(action)); + action.sa_sigaction = segv; + action.sa_flags = SA_SIGINFO | SA_NODEFER | (onstack ? SA_ONSTACK : 0); + sigaction(SIGSEGV, &action, NULL); +} + +static long run(long count, int with_trap) { + long start = escapes; + for (volatile long i = 0; i < count; i++) { + if (with_trap) { + volatile long before = i * 3; + __asm__ volatile("int3" ::: "memory"); + if (before != i * 3) + wrong++; + } + if (sigsetjmp(main_env, 1) == 0) + fault(i); + } + return escapes - start; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 50000; + stack_t ss = {.ss_sp = malloc(262144), .ss_size = 262144}; + struct sigaction action; + sigaltstack(&ss, NULL); + memset(&action, 0, sizeof(action)); + action.sa_sigaction = trap; + action.sa_flags = SA_SIGINFO; + sigaction(SIGTRAP, &action, NULL); + + install(1); + long onstack = run(want, 0); + install(0); + long offstack = run(want, 0); + install(1); + long mixed = run(want, 1); + nested_mode = 1; + long outer = run(want, 0); + + printf("onstack=%ld offstack=%ld mixed=%ld returns=%ld outer=%ld nested=%ld wrong=%ld\n", onstack, offstack, mixed, returns, + outer, nested, wrong); + return onstack == want && offstack == want && mixed == want && returns == want && outer == want && nested == 3 * want && !wrong ? 0 + : 1; +} diff --git a/tools/fex/probes/signal-register-update.c b/tools/fex/probes/signal-register-update.c new file mode 100644 index 0000000000..a1fdaec4d5 --- /dev/null +++ b/tools/fex/probes/signal-register-update.c @@ -0,0 +1,88 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#define MARK 0x5eed + +static volatile sig_atomic_t alarms; +static volatile sig_atomic_t give_up; + +static void count_alarm(void) { + if (++alarms > 100) { + give_up = 1; + } +} + +static void on_alarm(int sig, siginfo_t *si, void *ctx) { + (void)sig; + (void)si; + ucontext_t *uc = ctx; + count_alarm(); +#ifdef __x86_64__ + uc->uc_mcontext.gregs[REG_R12] = MARK; +#else + uc->uc_mcontext.gregs[REG_ESI] = MARK; +#endif +} + +#ifdef __i386__ +static void on_alarm_legacy(int sig, struct sigcontext sc) { + (void)sig; + count_alarm(); + ((volatile struct sigcontext *)&sc)->esi = MARK; +} +#endif + +int main(int argc, char **argv) { + int legacy = argc > 1 && strcmp(argv[1], "legacy") == 0; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_flags = SA_RESTART; +#ifdef __i386__ + if (legacy) { + sa.sa_handler = (void (*)(int))on_alarm_legacy; + } else +#endif + { + legacy = 0; + sa.sa_sigaction = on_alarm; + sa.sa_flags |= SA_SIGINFO; + } + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 20000}, {0, 20000}}; + setitimer(ITIMER_REAL, &it, NULL); + + unsigned long spins, seen; +#ifdef __x86_64__ + __asm__ volatile("xor %%r12, %%r12\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%r12, %%r12\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%r12, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "r12", "cc"); +#else + __asm__ volatile("xor %%esi, %%esi\n" + "xor %0, %0\n" + "1: inc %0\n" + "test %%esi, %%esi\n" + "jnz 2f\n" + "cmpl $0, %2\n" + "je 1b\n" + "2: mov %%esi, %1\n" + : "=&r"(spins), "=&r"(seen) + : "m"(give_up) + : "esi", "cc"); +#endif + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("frame=%s seen=%d alarms=%d spins=%lu\n", legacy ? "legacy" : "rt", seen == MARK, (int)alarms, spins); + return seen == MARK ? 0 : 1; +} diff --git a/tools/fex/probes/syscall-host-stack.c b/tools/fex/probes/syscall-host-stack.c new file mode 100644 index 0000000000..bd348fcfd3 --- /dev/null +++ b/tools/fex/probes/syscall-host-stack.c @@ -0,0 +1,65 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define YMM_STEP(a, b) "vpaddq %%ymm" #b ", %%ymm" #a ", %%ymm" #a "\n" +#define MMX_STEP(a, b) "paddq %%mm" #b ", %%mm" #a "\n" + +static int has_avx2(void) { + unsigned a, b, c, d; + if (!__get_cpuid(1, &a, &b, &c, &d) || !(c & bit_AVX) || !(c & bit_OSXSAVE)) + return 0; + unsigned lo, hi; + __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0)); + if ((lo & 6) != 6 || !__get_cpuid_count(7, 0, &a, &b, &c, &d)) + return 0; + return (b & bit_AVX2) != 0; +} + +static long ymm_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + YMM_STEP(0, 1) YMM_STEP(1, 2) YMM_STEP(2, 3) YMM_STEP(3, 4) YMM_STEP(4, 5) YMM_STEP(5, 6) YMM_STEP(6, 7) YMM_STEP(7, 8) + YMM_STEP(8, 9) YMM_STEP(9, 10) YMM_STEP(10, 11) YMM_STEP(11, 12) YMM_STEP(12, 13) YMM_STEP(13, 14) YMM_STEP(14, 15) + YMM_STEP(15, 0) YMM_STEP(0, 15) YMM_STEP(1, 14) YMM_STEP(2, 13) YMM_STEP(3, 12) YMM_STEP(4, 11) YMM_STEP(5, 10) + YMM_STEP(6, 9) YMM_STEP(7, 8) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", + "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"); + } + __asm__ volatile("vzeroupper" ::: "memory"); + return pid; +} + +static long mmx_round(long n) { + long pid = 0; + for (long i = 0; i < n; i++) { + __asm__ volatile( + MMX_STEP(0, 1) MMX_STEP(1, 2) MMX_STEP(2, 3) MMX_STEP(3, 4) MMX_STEP(4, 5) MMX_STEP(5, 6) MMX_STEP(6, 7) MMX_STEP(7, 0) + "mov %1, %%eax\n" + "syscall\n" + : "=a"(pid) + : "i"(SYS_getpid) + : "rcx", "r11", "memory", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7"); + } + __asm__ volatile("emms" ::: "memory"); + return pid; +} + +int main(int argc, char **argv) { + long want = argc > 1 ? atol(argv[1]) : 2000000; + int avx = has_avx2(); + long done = 0; + for (; done < want; done += 1000) { + if (avx ? ymm_round(1000) <= 0 : mmx_round(1000) <= 0) + return 2; + } + printf("mode=%s syscalls=%ld\n", avx ? "avx" : "mmx", done); + return 0; +} diff --git a/tools/fex/probes/vdso-signal-state.c b/tools/fex/probes/vdso-signal-state.c new file mode 100644 index 0000000000..56057594c3 --- /dev/null +++ b/tools/fex/probes/vdso-signal-state.c @@ -0,0 +1,49 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static volatile sig_atomic_t alarms; + +static void on_alarm(int sig) { + (void)sig; + alarms++; +} + +int main(int argc, char **argv) { + int seconds = argc > 1 ? atoi(argv[1]) : 3; + struct sigaction sa; + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = on_alarm; + sa.sa_flags = SA_RESTART; + sigaction(SIGALRM, &sa, NULL); + struct itimerval it = {{0, 1000}, {0, 1000}}; + setitimer(ITIMER_REAL, &it, NULL); + + struct timespec start, now, last; + clock_gettime(CLOCK_MONOTONIC, &start); + last = start; + unsigned long calls = 0, bad = 0; + unsigned long a = 1, b = 3, c = 1 ^ 0x5a5a5a5a5a5a5a5aUL; + do { + clock_gettime(CLOCK_MONOTONIC, &now); + calls++; + __asm__ volatile("" : "+r"(a), "+r"(b), "+r"(c)); + if (b != a * 3 || c != (a ^ 0x5a5a5a5a5a5a5a5aUL)) + bad++; + if (now.tv_sec < last.tv_sec || (now.tv_sec == last.tv_sec && now.tv_nsec < last.tv_nsec)) + bad++; + last = now; + a = a * 6364136223846793005UL + 1442695040888963407UL; + b = a * 3; + c = a ^ 0x5a5a5a5a5a5a5a5aUL; + } while ((now.tv_sec - start.tv_sec) * 1000000000L + (now.tv_nsec - start.tv_nsec) < seconds * 1000000000L); + + struct itimerval off = {{0, 0}, {0, 0}}; + setitimer(ITIMER_REAL, &off, NULL); + printf("calls=%lu alarms=%d bad=%lu\n", calls, (int)alarms, bad); + return bad || alarms == 0; +} diff --git a/tools/tests/test_fex_signal_handler_escape.py b/tools/tests/test_fex_signal_handler_escape.py new file mode 100644 index 0000000000..c208b874bf --- /dev/null +++ b/tools/tests/test_fex_signal_handler_escape.py @@ -0,0 +1,117 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0009-signal-handler-escape-frees-host-stack.patch" +PROBE = FEX / "probes/signal-handler-escape.c" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +CONTEXT = "Source/Tools/LinuxEmulation/ArchHelpers/MContext.h" +THREADS = "Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h" +FIELDS = ["PrevGuestFrame", "GuestFrameEnd", "GuestInterruptedSP", "GuestAltBase", "GuestAltEnd"] + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +class SignalHandlerEscapeTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([CONTEXT, DELEGATOR, THREADS])) + + def test_nothing_is_removed(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertFalse("//" in line or "/*" in line, f"{name}: {line}") + + def test_both_context_backups_record_the_guest_frame(self): + lines = added(files()[CONTEXT]) + self.assertEqual(lines, [f"uint64_t {field};" for field in FIELDS] * 2) + + def test_each_thread_keeps_its_frame_chain(self): + self.assertEqual([line for line in added(files()[THREADS]) if line], ["uint64_t GuestFrames {};", "uint32_t GuestFrameCount {};"]) + + def test_delivery_pushes_and_reclaims_only_left_frames_at_the_dispatch_level(self): + found = hunks(files()[DELEGATOR]) + delivery = "".join(body for function, body in found if "HandleDispatcherGuestSignal" in function) + lines = added(delivery) + self.assertIn("#ifdef ARCHITECTURE_arm64", lines) + gate = " ".join(lines) + self.assertIn("WasInJIT && Newest && ContextBackup->PrevSP == SignalInfo.GuestFrames", gate) + self.assertIn("Frame->SignalHandlerRefCounter == SignalInfo.GuestFrameCount + 1", gate) + self.assertIn("GuestLeftFrame(Newest, OldGuestSP", gate) + self.assertIn("ContextBackup->PrevSP = HostTop;", lines) + self.assertIn("Frame->SignalHandlerRefCounter -= LeftFrames;", lines) + self.assertIn("SignalInfo.GuestFrames = reinterpret_cast(ContextBackup);", lines) + self.assertIn("++SignalInfo.GuestFrameCount;", lines) + self.assertLess(lines.index("#endif"), lines.index("ContextBackup->PrevGuestFrame = SignalInfo.GuestFrames;")) + + def test_signal_return_pops_its_frame_and_any_newer_ones(self): + found = hunks(files()[DELEGATOR]) + restore = "".join(body for function, body in found if "RestoreThreadState" in function) + lines = added(restore) + self.assertIn("if (Entry == OldSP) {", lines) + self.assertIn("SignalInfo.GuestFrames = EntryBackup->PrevGuestFrame;", lines) + self.assertIn("Thread->CurrentFrame->SignalHandlerRefCounter -= Depth - 1;", lines) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_thread_stop_clears_the_chain(self): + found = hunks(files()[DELEGATOR]) + pause = "".join(body for function, body in found if "HandleSignalPause" in function) + self.assertEqual(added(pause), ["ThreadObject->SignalInfo.GuestFrames = 0;", "ThreadObject->SignalInfo.GuestFrameCount = 0;"]) + + def test_patch_follows_the_syscall_state_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0008-signal-return-restores-syscall-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + self.assertIn("tools/fex/patches/*.patch", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SignalHandlerEscapeProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-escape-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_survives_every_escape(self): + result = subprocess.run([str(self.binary), "20000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + for phase in ("onstack", "offstack", "mixed", "returns", "outer"): + self.assertEqual(counts[phase], "20000", phase) + self.assertEqual(counts["nested"], "60000") + self.assertEqual(counts["wrong"], "0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_register_update.py b/tools/tests/test_fex_signal_register_update.py new file mode 100644 index 0000000000..dabc5afff3 --- /dev/null +++ b/tools/tests/test_fex_signal_register_update.py @@ -0,0 +1,134 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0012-signal-return-applies-guest-registers.patch" +PROBE = FEX / "probes/signal-register-update.c" +HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.h" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +X64_ORDER = ["RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"] + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def added(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(section): + return [line[1:].strip() for line in section.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def helper(): + lines = added(files()[FRAMES]) + start = next(i for i, line in enumerate(lines) if line.startswith("void SignalDelegator::ResumeWithGuestGPRs(")) + end = lines.index("#endif", start) + return lines[start:end + 1] + + +class SignalRegisterUpdateTest(unittest.TestCase): + def test_only_signal_frame_files_change(self): + self.assertEqual(sorted(files()), sorted([FRAMES, HEADER])) + + def test_patch_only_adds_code(self): + for name, section in files().items(): + self.assertEqual(removed(section), [], name) + + def test_added_code_has_no_comments(self): + for name, section in files().items(): + for line in added(section): + self.assertNotIn("//", line, name) + self.assertNotIn("/*", line, name) + + def test_helper_is_declared_once(self): + self.assertEqual(sum(line.startswith("void ResumeWithGuestGPRs(") for line in added(files()[HEADER])), 1) + + def test_only_changed_registers_are_written_back(self): + body = helper() + self.assertIn("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {", body) + self.assertEqual(body[body.index("if (((Delivered ^ GuestGPRs[i]) & Mask) == 0) {") + 1], "continue;") + + def test_spilled_registers_go_to_the_frame_and_live_ones_to_host_registers(self): + body = helper() + self.assertIn("const bool InFrame = AllSpilled || (Spilled & (1U << HostReg));", body) + self.assertIn("Frame->State.gregs[i] = GuestGPRs[i];", body) + self.assertIn("ArchHelpers::Context::SetArmReg(ucontext, HostReg, GuestGPRs[i]);", body) + self.assertIn("for (size_t i = 0; i < Count && i < Config.SRAGPRCount; i++) {", body) + + def test_signals_outside_jit_code_are_left_alone(self): + body = helper() + guard = body.index("if (!AllSpilled && !(Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT)) {") + self.assertEqual(body[guard + 1], "return;") + self.assertEqual(body[2], "#ifdef ARCHITECTURE_arm64") + + def test_every_frame_type_applies_registers_when_rip_is_unchanged(self): + lines = added(files()[FRAMES]) + calls = [line for line in lines if line.startswith("ResumeWithGuestGPRs(")] + self.assertEqual(calls, [ + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, FEXCore::Core::CPUState::NUM_GPRS, ~0ULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + "ResumeWithGuestGPRs(Context, Frame, ucontext, GuestGPRs, 8, 0xFFFF'FFFFULL);", + ]) + branches = [lines[i + 1] for i, line in enumerate(lines[:-1]) if line == "} else {" and lines[i + 1].startswith("uint64_t GuestGPRs[")] + self.assertEqual(branches, ["uint64_t GuestGPRs[FEXCore::Core::CPUState::NUM_GPRS];", "uint64_t GuestGPRs[8];", "uint64_t GuestGPRs[8];"]) + + def test_registers_are_stored_by_guest_register_index(self): + lines = added(files()[FRAMES]) + x64 = [m.group(1) for line in lines for m in [re.fullmatch(r"COPY_REG\((\w+)\);", line)] if m] + self.assertEqual(sorted(x64), sorted(X64_ORDER)) + self.assertIn("#define COPY_REG(x) GuestGPRs[FEXCore::X86State::REG_##x] = guest_uctx->uc_mcontext.gregs[FEXCore::x86_64::FEX_REG_##x];", lines) + legacy = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->sc\.(\w+);", "\n".join(lines)) + self.assertEqual(sorted(legacy), sorted((r, r[1:].lower()) for r in X64_ORDER[:8])) + rt = re.findall(r"GuestGPRs\[FEXCore::X86State::REG_(\w+)\] = guest_uctx->uc\.uc_mcontext\.gregs\[FEXCore::x86::FEX_REG_(\w+)\];", "\n".join(lines)) + self.assertEqual(sorted(rt), sorted((r, r) for r in X64_ORDER[:8])) + + def test_patch_follows_the_thunk_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0011-thunk-calls-mark-spilled-state.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86 code") +class SignalRegisterUpdateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not cls.compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-signal-regs-")) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def build(self, *flags): + binary = self.tmp / ("probe" + "".join(flags)) + result = subprocess.run([self.compiler, "-O2", *flags, "-o", str(binary), str(PROBE)], capture_output=True, text=True) + return binary if result.returncode == 0 else None + + def check(self, binary, *args): + result = subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertIn("seen=1", result.stdout) + + def test_native_kernel_applies_handler_register_changes(self): + self.check(self.build()) + + def test_native_kernel_applies_handler_register_changes_in_32_bit_frames(self): + binary = self.build("-m32") + if binary is None: + self.skipTest("no 32-bit toolchain") + self.check(binary) + self.check(binary, "legacy") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_signal_syscall_state.py b/tools/tests/test_fex_signal_syscall_state.py index 1aaa03feb3..5638a41fea 100644 --- a/tools/tests/test_fex_signal_syscall_state.py +++ b/tools/tests/test_fex_signal_syscall_state.py @@ -24,7 +24,7 @@ class SignalReturnSyscallStateTest(unittest.TestCase): self.assertEqual(files, ["Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp"]) self.assertEqual(len(found), 1) - def test_every_guest_frame_return_restores_the_interrupted_syscall_state(self): + def test_only_returns_to_jit_code_restore_the_saved_syscall_state(self): _, found = hunks() function, body = found[0] self.assertIn("SignalDelegator::RestoreThreadState", function) @@ -34,10 +34,12 @@ class SignalReturnSyscallStateTest(unittest.TestCase): self.assertEqual(added, [RESTORE]) self.assertEqual(removed, []) context = [line[1:].strip() for line in lines] - guest_frame = context.index("if (Context->UContextLocation) {") - self.assertEqual(context[guest_frame + 1], "auto Frame = Thread->CurrentFrame;") - self.assertEqual(context[guest_frame + 2], RESTORE) - self.assertLess(context.index(RESTORE), context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {")) + self.assertEqual(context[0], "auto Frame = Thread->CurrentFrame;") + in_jit = context.index("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {") + restore = context.index(RESTORE) + self.assertLess(in_jit, restore) + self.assertEqual(context[restore + 1], "}") + self.assertLess(restore, context.index("RestoreFrame_x64(Thread, Context, Frame, ucontext);")) def test_thread_pause_returns_are_untouched(self): _, found = hunks() diff --git a/tools/tests/test_fex_syscall_host_stack.py b/tools/tests/test_fex_syscall_host_stack.py new file mode 100644 index 0000000000..018863cf59 --- /dev/null +++ b/tools/tests/test_fex_syscall_host_stack.py @@ -0,0 +1,67 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0010-syscall-exit-resets-host-stack.patch" +PROBE = FEX / "probes/syscall-host-stack.c" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" + + +def hunks(): + text = PATCH.read_text() + files = re.findall(r"^diff --git a/(\S+) ", text, re.M) + return files, re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", text, re.M) + + +class SyscallHostStackTest(unittest.TestCase): + def test_only_the_branch_ops_change(self): + files, found = hunks() + self.assertEqual(files, [BRANCH_OPS]) + self.assertEqual(len(found), 2) + + def test_both_ops_that_leave_the_block_reset_the_stack_after_spilling(self): + _, found = hunks() + for (function, body), op in zip(found, ("DEF_OP(Syscall)", "DEF_OP(ThreadRemoveCodeEntry)")): + lines = body.splitlines() + added = [line[1:].strip() for line in lines if line.startswith("+")] + self.assertEqual([line for line in added if line], ["ResetStack();"], op) + self.assertEqual([line for line in lines if line.startswith("-")], [], op) + context = [line[1:].strip() for line in lines] + self.assertIn(op, function + " " + " ".join(context)) + self.assertLess(context.index("SpillStaticRegs(TMP1);"), context.index("ResetStack();"), op) + + def test_patch_is_skipped_once_upstream_ships_it(self): + self.assertEqual(PATCH.read_text().splitlines()[0], "Fixed-upstream: FEX-2612") + self.assertIn("Fixed-upstream: FEX-", (FEX / "build-in-arch.sh").read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class SyscallHostStackProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-syscall-stack-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_runs_every_syscall(self): + result = subprocess.run([str(self.binary), "200000"], capture_output=True, text=True, timeout=120) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertIn(counts["mode"], ("avx", "mmx")) + self.assertEqual(counts["syscalls"], "200000") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_thunk_signal_state.py b/tools/tests/test_fex_thunk_signal_state.py new file mode 100644 index 0000000000..83d6008589 --- /dev/null +++ b/tools/tests/test_fex_thunk_signal_state.py @@ -0,0 +1,124 @@ +import platform +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +FEX = Path(__file__).resolve().parents[1] / "fex" +PATCH = FEX / "patches/0011-thunk-calls-mark-spilled-state.patch" +PROBE = FEX / "probes/vdso-signal-state.c" +CORE = "FEXCore/Source/Interface/Core/Core.cpp" +BRANCH_OPS = "FEXCore/Source/Interface/Core/JIT/BranchOps.cpp" +DELEGATOR = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp" +FRAMES = "Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator/GuestFramesManagement.cpp" +MARK = "str(TMP1, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +CLEAR = "str(ARMEmitter::XReg::zr, STATE, offsetof(FEXCore::Core::CpuStateFrame, InSyscallInfo));" +RESTORE = "Frame->InSyscallInfo = Context->InSyscallInfo;" + + +def files(): + sections = re.split(r"^diff --git a/(\S+) \S+\n", PATCH.read_text(), flags=re.M) + return {sections[i]: sections[i + 1] for i in range(1, len(sections), 2)} + + +def hunks(section): + return re.findall(r"^@@ [^@]+ @@ ?(.*)\n((?:[ +\-].*\n?)*)", section, re.M) + + +def added(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("+") and not line.startswith("+++")] + + +def removed(body): + return [line[1:].strip() for line in body.splitlines() if line.startswith("-") and not line.startswith("---")] + + +def context(body): + return [line[1:].strip() for line in body.splitlines() if line[:1] in (" ", "+")] + + +class ThunkSignalStateTest(unittest.TestCase): + def test_only_signal_state_files_change(self): + self.assertEqual(sorted(files()), sorted([BRANCH_OPS, CORE, DELEGATOR, FRAMES])) + + def test_added_code_has_no_new_comments(self): + for name, section in files().items(): + moved = set(removed(section)) + for line in added(section): + if "//" in line or "/*" in line: + self.assertIn(line, moved, f"{name}: {line}") + + def test_thunk_call_marks_all_state_spilled_until_the_refill(self): + section = files()[BRANCH_OPS] + lines = context(section) + self.assertEqual([line for line in added(section) if line], ["LoadConstant(ARMEmitter::Size::i64Bit, TMP1, 0xFFFF);", MARK, CLEAR]) + self.assertEqual(removed(section), []) + self.assertLess(lines.index("PushDynamicRegs(TMP1);"), lines.index(MARK)) + self.assertLess(lines.index(MARK), lines.index("InsertNamedThunkRelocation(ARMEmitter::Reg::r2, Op->ThunkNameHash);")) + refill = lines.index("FillStaticRegs({") + self.assertEqual(lines[refill + 1:refill + 3], [".NZCV = false,", "});"]) + self.assertLess(refill, lines.index(CLEAR)) + + def test_fully_spilled_state_is_never_respilled_from_host_registers(self): + found = hunks(files()[DELEGATOR]) + spill = "".join(body for function, body in found if "SpillSRA" in function or "IgnoreMask" in body) + lines = context(spill) + guard = lines.index("if ((IgnoreMask & 0xFFFF) == 0xFFFF) {") + self.assertIn("RestoreRIPFromHostPC", lines[guard - 2]) + self.assertEqual(lines[guard + 1], "return;") + self.assertIn("for (size_t i = 0; i < Config.SRAGPRCount; i++) {", lines[guard + 2:guard + 5]) + + def test_every_guest_signal_saves_and_clears_the_mark(self): + section = files()[DELEGATOR] + lines = added(section) + self.assertIn("ContextBackup->InSyscallInfo = Frame->InSyscallInfo;", lines) + self.assertIn("Frame->InSyscallInfo = 0;", lines) + self.assertIn(RESTORE, lines) + self.assertIn("if (Context->Flags & ArchHelpers::Context::ContextFlags::CONTEXT_FLAG_INJIT) {", removed(section)) + self.assertNotIn("TYPE_PAUSE", " ".join(lines)) + + def test_redirected_returns_restart_with_no_mark(self): + section = files()[FRAMES] + self.assertEqual(added(section), ["Frame->InSyscallInfo = 0;"] * 3) + self.assertEqual(removed(section), [RESTORE] * 3) + + def test_guest_callbacks_run_with_no_mark(self): + lines = added(files()[CORE]) + self.assertEqual(lines[1:3], ["const auto InSyscallInfo = Frame->InSyscallInfo;", "Frame->InSyscallInfo = 0;"]) + self.assertEqual(lines[-1], "Frame->InSyscallInfo = InSyscallInfo;") + self.assertIn("ExecuteJITCallback(Frame, RIP);", lines[-2]) + + def test_patch_follows_the_host_stack_patch_on_every_release(self): + names = sorted(path.name for path in (FEX / "patches").glob("*.patch")) + self.assertEqual(names[names.index(PATCH.name) - 1], "0010-syscall-exit-resets-host-stack.patch") + self.assertNotIn("Fixed-upstream", PATCH.read_text()) + + +@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code") +class VdsoSignalStateProbeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang") + if not compiler: + raise unittest.SkipTest("no C compiler") + cls.tmp = Path(tempfile.mkdtemp(prefix="fex-vdso-signal-")) + cls.binary = cls.tmp / "probe" + subprocess.run([compiler, "-O2", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_native_kernel_keeps_registers_across_interrupted_clock_calls(self): + result = subprocess.run([str(self.binary), "1"], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout) + counts = dict(part.split("=") for part in result.stdout.split()) + self.assertGreater(int(counts["calls"]), 0) + self.assertGreater(int(counts["alarms"]), 0) + self.assertEqual(counts["bad"], "0") + + +if __name__ == "__main__": + unittest.main() From d5b9cf5b41d0c282d17f3b213f7f75d4da1d0072 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:18:06 -0500 Subject: [PATCH 09/17] feat(ui): the Updates icon shows the build you're on (#3064) --- .../com/droiddeck/launcher/ui/FrontEndRail.kt | 3 +- .../droiddeck/launcher/ui/FrontEndScreen.kt | 1 + .../droiddeck/launcher/ui/UpdatesRailIcon.kt | 49 +++++++++++++++++++ .../launcher/ui/UpdatesRailIconTest.kt | 22 +++++++++ 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 5503ef22a1..65dc828be8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -58,7 +58,6 @@ import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.SdStorage import androidx.compose.material.icons.filled.Sync import androidx.compose.material.icons.filled.MoreHoriz -import androidx.compose.material.icons.filled.SystemUpdate import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.material3.Icon @@ -208,7 +207,7 @@ internal fun railLabelIcon(key: String): Pair = when (key) { "storage" -> R.string.rail_storage to Icons.Filled.SdStorage "sync" -> R.string.rail_sync to Icons.Filled.Sync NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz - else -> R.string.rail_updates to Icons.Filled.SystemUpdate + else -> R.string.rail_updates to updatesIcon(RunningBuild.kind()) } internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) || 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 0fa75a5855..c2f49c2ef2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -454,6 +454,7 @@ internal suspend fun focusSoon(target: () -> FocusRequester) { @Composable fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { val frontFocus = remember { FrontFocus() } + androidx.compose.runtime.SideEffect { RunningBuild.channel = s.updates.follow.channel } val textInput = androidx.compose.ui.platform.LocalTextInputService.current val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } } androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt new file mode 100644 index 0000000000..8206bb035e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/UpdatesRailIcon.kt @@ -0,0 +1,49 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.SystemUpdate +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathFillType +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.update.AppUpdates + +internal enum class BuildKind { STABLE, PREVIEW, TEST, LOCAL } + +internal object RunningBuild { + var channel by mutableStateOf(AppUpdates.Channel.STABLE) + + fun kind(me: AppUpdates.Installed = AppUpdates.installed(), channel: AppUpdates.Channel = this.channel): BuildKind = when { + me.pr > 0 -> BuildKind.TEST + !me.ciBuild -> BuildKind.LOCAL + channel == AppUpdates.Channel.NIGHTLY -> BuildKind.PREVIEW + else -> BuildKind.STABLE + } +} + +private const val PHONE = "M17,1.01L7,1c-1.1,0 -2,0.9 -2,2v18c0,1.1 0.9,2 2,2h10c1.1,0 2,-0.9 2,-2V3c0,-1.1 -0.9,-1.99 -2,-1.99zM17,19H7V5h10v14z" +private const val LETTER_P = "M9.6,7.6 H12.6 A2.4,2.4 0 0 1 12.6,12.4 H11.4 V16.4 H9.6 Z M11.4,9.2 V10.8 H12.6 A0.8,0.8 0 0 0 12.6,9.2 Z" +private const val LETTER_T = "M8.6,7.6 H15.4 V9.3 H12.9 V16.4 H11.1 V9.3 H8.6 Z" +private const val LETTER_L = "M9.8,7.6 H11.6 V14.7 H15 V16.4 H9.8 Z" + +private fun phoneWith(name: String, letter: String) = + ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f) + .addPath(addPathNodes(PHONE), fill = SolidColor(Color.Black)) + .addPath(addPathNodes(letter), fill = SolidColor(Color.Black), pathFillType = PathFillType.EvenOdd) + .build() + +private val PreviewIcon by lazy { phoneWith("UpdatesPreview", LETTER_P) } +private val TestIcon by lazy { phoneWith("UpdatesTest", LETTER_T) } +private val LocalIcon by lazy { phoneWith("UpdatesLocal", LETTER_L) } + +internal fun updatesIcon(kind: BuildKind): ImageVector = when (kind) { + BuildKind.STABLE -> Icons.Filled.SystemUpdate + BuildKind.PREVIEW -> PreviewIcon + BuildKind.TEST -> TestIcon + BuildKind.LOCAL -> LocalIcon +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt new file mode 100644 index 0000000000..d96dc487b6 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/UpdatesRailIconTest.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.update.AppUpdates +import com.droiddeck.launcher.update.AppUpdates.Channel +import org.junit.Assert.assertEquals +import org.junit.Test + +class UpdatesRailIconTest { + private fun me(pr: Int = 0, ci: Boolean = true) = AppUpdates.Installed("abc", pr, "1.0", 1, ci, ciBuild = ci) + + @Test + fun releaseBuildsFollowTheirChannel() { + assertEquals(BuildKind.STABLE, RunningBuild.kind(me(), Channel.STABLE)) + assertEquals(BuildKind.PREVIEW, RunningBuild.kind(me(), Channel.NIGHTLY)) + } + + @Test + fun prBuildsAreTestAndNonCiBuildsAreLocal() { + assertEquals(BuildKind.TEST, RunningBuild.kind(me(pr = 12), Channel.TEST)) + assertEquals(BuildKind.LOCAL, RunningBuild.kind(me(ci = false), Channel.STABLE)) + } +} From 3e558ab33e3311d4c74a66a6f864f90286ca8213 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:59:58 -0500 Subject: [PATCH 10/17] feat(ui): Decky and Boot movies get their own tabs, with a Decky plugin store (#3068) --- .../java/com/droiddeck/launcher/DeckyMenu.kt | 55 ++++ .../droiddeck/launcher/FrontEndActivity.kt | 7 +- .../droiddeck/launcher/runtime/DeckyStore.kt | 102 ++++++++ .../droiddeck/launcher/ui/BootMovieSection.kt | 2 +- .../com/droiddeck/launcher/ui/DeckyIcon.kt | 16 ++ .../com/droiddeck/launcher/ui/DeckyPage.kt | 245 ++++++++++++++++++ .../droiddeck/launcher/ui/FrontEndContent.kt | 4 + .../com/droiddeck/launcher/ui/FrontEndRail.kt | 3 + .../com/droiddeck/launcher/ui/LiftSheet.kt | 2 + .../launcher/ui/ModeSettingsDialog.kt | 80 +----- .../java/com/droiddeck/launcher/ui/NavTabs.kt | 6 +- .../launcher/ui/RailSettingsPages.kt | 13 + .../droiddeck/launcher/ui/SettingsIndex.kt | 2 + 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 | 26 +- .../launcher/runtime/DeckyStoreTest.kt | 47 ++++ .../com/droiddeck/launcher/ui/NavTabsTest.kt | 14 +- docs/settings-map.md | 2 + 49 files changed, 538 insertions(+), 248 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt b/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt index 240202daec..983eea5ea0 100644 --- a/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt +++ b/app/src/main/java/com/droiddeck/launcher/DeckyMenu.kt @@ -6,6 +6,7 @@ import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.runtime.DeckyManager +import com.droiddeck.launcher.runtime.DeckyStore import com.droiddeck.launcher.session.SessionState import java.io.File @@ -21,6 +22,59 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val var deckySupervisor by mutableStateOf(false) var deckyPendingZip by mutableStateOf(null) var deckyReleaseRequest = 0 + var deckyPlugins by mutableStateOf>(emptyList()) + var deckyStore by mutableStateOf?>(null) + var deckyStoreFailed by mutableStateOf(false) + private var storeRequest = 0 + + fun refreshPlugins() { + Thread({ + val found = DeckyStore.installed(activity) + ui.post { deckyPlugins = found } + }, "decky-plugins").start() + } + + fun refreshStore() { + val request = ++storeRequest + deckyStore = null; deckyStoreFailed = false + Thread({ + val listing = DeckyStore.fetch() + ui.post { + if (request != storeRequest) return@post + deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null + } + }, "decky-store").start() + } + + fun installStorePlugin(plugin: DeckyStore.Plugin) { + val version = plugin.latest ?: return + if (deckyStage != null || SessionState.running || deckyInstalled == null) return + deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1 + Thread({ + val problem = runCatching { + DeckyStore.install(activity, plugin, version) { label, value -> + val binary = DeckyManager.downloadingBinary + ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary } + } + }.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) } + ui.post { + deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false + android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show() + refreshPlugins() + } + }, "install-decky-store").start() + } + + fun removePlugin(plugin: DeckyStore.Installed) { + if (deckyStage != null || SessionState.running) return + Thread({ + val problem = DeckyStore.remove(activity, plugin) + ui.post { + if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show() + refreshPlugins() + } + }, "remove-decky-plugin").start() + } fun refreshDecky() { val request = ++deckyReleaseRequest @@ -90,6 +144,7 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false val message = problem ?: activity.getString(R.string.decky_plugin_installed) android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() + refreshPlugins() } }, "import-decky-plugin").start() } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index 1c0d4f8ef9..af3eddf8e7 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -921,7 +921,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) } request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri -> val section = uri.pathSegments.firstOrNull() - navRequest = if (section in setOf("storage", "sync", "downloads")) section + navRequest = if (section in setOf("storage", "sync", "downloads", "decky", "boot-movies")) section else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key request.data = null gameLinkReading = false @@ -2690,6 +2690,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent, deckyDownloadingBinary = decky.deckyDownloadingBinary, deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running, + deckyPlugins = decky.deckyPlugins, deckyStore = decky.deckyStore, deckyStoreFailed = decky.deckyStoreFailed, ), ModeSettingsActions( onIntegration = ::configureIntegration, @@ -2800,6 +2801,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet decky.deckyInstalled = null decky.deckySupervisor = false }, + onDeckyStoreRefresh = { decky.refreshStore() }, + onDeckyStoreInstall = { plugin -> decky.installStorePlugin(plugin) }, + onDeckyRemove = { plugin -> decky.removePlugin(plugin) }, onPickDeckyPluginZip = { pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip))) }, @@ -3090,6 +3094,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet decky.deckyInstalled = deckyInstalled decky.deckySupervisor = deckySupervisor decky.refreshDecky() + decky.refreshPlugins() } fetchAddedGameArt() } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt new file mode 100644 index 0000000000..451c5c2f82 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyStore.kt @@ -0,0 +1,102 @@ +package com.droiddeck.launcher.runtime + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.Downloader +import com.droiddeck.launcher.session.SessionState +import java.io.File +import org.json.JSONArray +import org.json.JSONObject + +object DeckyStore { + private const val TAG = "DeckyStore" + private const val LISTING = "https://plugins.deckbrew.xyz/plugins" + private const val ARTIFACTS = "https://cdn.tzatzikiweeb.moe/file/steam-deck-homebrew/versions/" + + data class Version(val name: String, val hash: String) + data class Plugin(val name: String, val author: String, val description: String, val tags: List, val downloads: Long, val imageUrl: String, val versions: List) { + val latest: Version? get() = versions.firstOrNull() + } + data class Installed(val name: String, val folder: String, val author: String, val version: String) + + fun parseListing(body: String): List { + val array = JSONArray(body) + return (0 until array.length()).mapNotNull { i -> + val row = array.optJSONObject(i) ?: return@mapNotNull null + val name = row.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null + val versions = row.optJSONArray("versions")?.let { list -> + (0 until list.length()).mapNotNull { v -> + val version = list.optJSONObject(v) ?: return@mapNotNull null + val hash = version.optString("hash") + if (!hash.matches(Regex("(?i)[0-9a-f]{64}"))) null else Version(version.optString("name"), hash.lowercase()) + } + }.orEmpty() + if (versions.isEmpty()) return@mapNotNull null + val tags = row.optJSONArray("tags")?.let { list -> (0 until list.length()).map { list.optString(it) } }.orEmpty() + val downloads = row.optJSONArray("versions")?.let { list -> (0 until list.length()).sumOf { list.optJSONObject(it)?.optLong("downloads") ?: 0L } } ?: 0L + val image = row.optString("image_url").takeIf { it.startsWith("https://") }.orEmpty() + Plugin(name, row.optString("author"), row.optString("description"), tags, downloads, image, versions) + } + } + + fun fetch(): List? { + val body = Downloader.downloadString(LISTING) ?: return null + return runCatching { parseListing(body) }.onFailure { Log.w(TAG, "store listing", it) }.getOrNull() + } + + fun pluginsDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins") + + fun installed(context: Context): List = + pluginsDir(context).listFiles().orEmpty() + .filter { it.isDirectory && !it.name.startsWith(".droiddeck-") } + .mapNotNull { folder -> + runCatching { + val meta = JSONObject(File(folder, "plugin.json").readText()) + val version = runCatching { JSONObject(File(folder, "package.json").readText()).optString("version") }.getOrDefault("") + Installed(meta.getString("name"), folder.name, meta.optString("author"), version) + }.getOrNull() + } + .sortedBy { it.name.lowercase() } + + fun updateAvailable(installed: Installed, plugin: Plugin?): Boolean { + val latest = plugin?.latest?.name ?: return false + return installed.version.isNotEmpty() && latest != installed.version + } + + fun install(context: Context, plugin: Plugin, version: Version, progress: (String, Int) -> Unit): String? { + if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin) + if (DeckyManager.installed(context) == null) return context.getString(R.string.deckymgr_loader_required) + val cache = File(context.cacheDir, "decky-store").apply { mkdirs() } + val zip = File(cache, "${version.hash}.zip") + try { + val label = context.getString(R.string.decky_store_downloading, plugin.name) + progress(label, -1) + val ok = Downloader.downloadFile("$ARTIFACTS${version.hash}.zip", zip, true, version.hash) { fraction -> + progress(label, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100)) + } + if (!ok) return context.getString(R.string.decky_store_download_failed, plugin.name) + return DeckyManager.installPluginZip(context, zip, progress) + } finally { + zip.delete() + } + } + + fun remove(context: Context, plugin: Installed): String? { + if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin) + val plugins = pluginsDir(context) + val folder = File(plugins, plugin.folder) + if (folder.parentFile?.canonicalFile != plugins.canonicalFile) return context.getString(R.string.decky_store_remove_failed) + if (!folder.deleteRecursively()) return context.getString(R.string.decky_store_remove_failed) + val settings = File(plugins.parentFile, "settings/loader.json") + runCatching { + val json = JSONObject(settings.readText()) + for (key in listOf("pluginOrder", "frozenPlugins", "hiddenPlugins", "disabled_plugins")) { + val values = json.optJSONArray(key) ?: continue + json.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != plugin.name })) + } + settings.writeText(json.toString(4)) + } + return null + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt index 2db14a9d74..077ba8a2cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt @@ -117,7 +117,7 @@ private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieS } @Composable -private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { +internal fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val hot = rememberHot(src) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt new file mode 100644 index 0000000000..aaa36f8ad0 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckyIcon.kt @@ -0,0 +1,16 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.graphics.vector.addPathNodes +import androidx.compose.ui.unit.dp + +internal val DeckyIcon: ImageVector = ImageVector.Builder("Decky", 24.dp, 24.dp, 24f, 24f).apply { + for (d in listOf( + "M8,2h2v6H8Z", + "M14,2h2v6h-2Z", + "M5,8h14v3a7,7 0 0 1 -5,6.7V19h-4v-1.3A7,7 0 0 1 5,11Z", + "M11,19h2v3h-2Z", + )) addPath(addPathNodes(d), fill = SolidColor(Color.Black)) +}.build() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt new file mode 100644 index 0000000000..0535e4a8eb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DeckyPage.kt @@ -0,0 +1,245 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import coil.compose.AsyncImage +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.LinearProgressIndicator +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.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.DeckyManager +import com.droiddeck.launcher.runtime.DeckyStore + +private enum class DeckyTab { INSTALLED, STORE, ZIP } + +private const val STORE_PAGE = 30 + +internal fun deckyStoreMatches(plugins: List, query: String): List { + val words = query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() } + return plugins.filter { p -> + val haystack = (p.name + " " + p.author + " " + p.description + " " + p.tags.joinToString(" ")).lowercase() + words.all { it in haystack } + }.sortedByDescending { it.downloads } +} + +@Composable +internal fun DeckyGroups(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) { + val idle = s.deckyStage == null && !s.deckySessionRunning + SettingsGroup(stringResource(R.string.mode_decky_loader)) { + val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null && + s.deckyInstalled != s.deckyLatestRelease.tag + val status = when { + s.deckyStage != null -> s.deckyStage + s.deckyChecking -> stringResource(R.string.mode_decky_checking) + s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag) + s.deckyInstalled == null -> stringResource(R.string.mode_decky_none) + s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled) + updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag) + else -> stringResource(R.string.mode_decky_current, s.deckyInstalled) + } + SettingsRow(stringResource(R.string.decky_status), status) { + val action = when { + s.deckyStage != null -> stringResource(R.string.common_working) + s.deckyChecking -> stringResource(R.string.common_checking) + s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest) + s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update) + else -> stringResource(R.string.common_check) + } + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + SecondaryButton(action, enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning) { + if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck() + else s.deckyLatestRelease?.let(a.onDeckyInstall) + } + if (s.deckyInstalled != null) DeckyUninstall(enabled = idle, onUninstall = a.onDeckyUninstall) + } + } + if (s.deckyInstalled != null) ToggleRow( + host, "decky-enabled", stringResource(R.string.decky_enable), + null, + s.deckyEnabled, + enabled = idle, + onChange = a.onDeckyEnabled, + ) + ChoiceRow( + host, "decky-channel", stringResource(R.string.decky_release_channel), + null, + listOf( + DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable), + DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease), + ) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf( + DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing), + ) else emptyList(), + s.deckyBranch, + enabled = idle, + onPick = a.onDeckyBranch, + ) + if (s.deckyStage != null && s.deckyPercent >= 0) { + LinearProgressIndicator( + progress = { s.deckyPercent / 100f }, + modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), + ) + } + } + if (s.deckyInstalled == null) return + var tab by rememberSaveable { mutableStateOf(DeckyTab.INSTALLED) } + SettingsGroup(stringResource(R.string.mode_decky_plugins)) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) { + TabChip(stringResource(R.string.decky_tab_installed, s.deckyPlugins.size), tab == DeckyTab.INSTALLED, Modifier.weight(1f)) { tab = DeckyTab.INSTALLED } + TabChip(stringResource(R.string.decky_tab_store), tab == DeckyTab.STORE, Modifier.weight(1f)) { tab = DeckyTab.STORE } + TabChip(stringResource(R.string.decky_tab_zip), tab == DeckyTab.ZIP, Modifier.weight(1f)) { tab = DeckyTab.ZIP } + } + LaunchedEffect(tab) { if (tab != DeckyTab.ZIP && s.deckyStore == null && !s.deckyStoreFailed) a.onDeckyStoreRefresh() } + when (tab) { + DeckyTab.INSTALLED -> InstalledPlugins(s, a, idle) + DeckyTab.STORE -> PluginStore(s, a, idle) + DeckyTab.ZIP -> SettingsRow( + stringResource(R.string.decky_tab_zip), + stringResource(R.string.mode_decky_plugins_hint), + ) { + SecondaryButton( + if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip), + enabled = idle, + modifier = Modifier.testTag("decky-install-zip"), + onClick = a.onPickDeckyPluginZip, + ) + } + } + } +} + +@Composable +private fun InstalledPlugins(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) { + var removing by remember { mutableStateOf(null) } + if (s.deckyPlugins.isEmpty()) { + Text(stringResource(R.string.decky_none_installed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp)) + } + for (plugin in s.deckyPlugins) { + val listed = s.deckyStore?.firstOrNull { it.name == plugin.name } + val update = listed?.takeIf { DeckyStore.updateAvailable(plugin, it) } + PluginRow( + plugin.name, + listOf(plugin.version, plugin.author).filter { it.isNotBlank() }.joinToString(" ยท ") + + (update?.latest?.let { " ยท " + stringResource(R.string.decky_update_to, it.name) } ?: ""), + listed?.imageUrl.orEmpty(), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { + if (update != null) SecondaryButton(stringResource(R.string.common_update), enabled = idle, compact = true) { a.onDeckyStoreInstall(update) } + SecondaryButton(stringResource(R.string.decky_remove), enabled = idle, compact = true, modifier = Modifier.testTag("decky-remove-${plugin.folder}")) { removing = plugin } + } + } + } + if (s.deckyPlugins.isNotEmpty()) Text(stringResource(R.string.decky_changes_next_session), fontSize = 12.sp, + color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) + removing?.let { plugin -> + androidx.compose.material3.AlertDialog( + onDismissRequest = { removing = null }, + title = { Text(stringResource(R.string.decky_remove_confirm, plugin.name)) }, + text = { Text(stringResource(R.string.decky_remove_confirm_body)) }, + confirmButton = { androidx.compose.material3.TextButton(onClick = { removing = null; a.onDeckyRemove(plugin) }) { Text(stringResource(R.string.decky_remove)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = { removing = null }) { Text(stringResource(R.string.common_cancel)) } }, + ) + } +} + +@Composable +private fun PluginStore(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) { + var query by rememberSaveable { mutableStateOf("") } + var searching by remember { mutableStateOf(false) } + var shown by rememberSaveable { mutableIntStateOf(STORE_PAGE) } + val plugins = s.deckyStore + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + Box(Modifier.weight(1f)) { + ListRow(tall = true, onClick = { searching = true }) { + androidx.compose.material3.Icon(Icons.Filled.Search, contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp)) + Text( + query.ifEmpty { stringResource(R.string.decky_store_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground, + modifier = Modifier.weight(1f), + ) + } + } + if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; shown = STORE_PAGE } + } + when { + plugins == null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) + s.deckyStoreFailed -> Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(stringResource(R.string.decky_store_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { a.onDeckyStoreRefresh() } + } + else -> { + val matches = remember(plugins, query) { deckyStoreMatches(plugins, query) } + if (matches.isEmpty()) Text(stringResource(R.string.decky_store_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) + for (plugin in matches.take(shown)) { + val have = s.deckyPlugins.firstOrNull { it.name == plugin.name } + val current = have != null && !DeckyStore.updateAvailable(have, plugin) + PluginRow( + plugin.name, + listOf(plugin.latest?.name.orEmpty(), plugin.author, plugin.description).filter { it.isNotBlank() }.joinToString(" ยท "), + plugin.imageUrl, + ) { + SecondaryButton( + stringResource(when { current -> R.string.setup_installed; have != null -> R.string.common_update; else -> R.string.boot_movie_repo_install }), + enabled = idle && !current, compact = true, + modifier = Modifier.testTag("decky-store-${plugin.name}"), + ) { a.onDeckyStoreInstall(plugin) } + } + } + if (matches.size > shown) SecondaryButton(stringResource(R.string.decky_store_more, matches.size - shown), compact = true) { shown += STORE_PAGE } + } + } + } + if (searching) TextEntryDialog( + stringResource(R.string.decky_store_search), query, number = false, confirm = stringResource(R.string.stores_search_open), + onSubmit = { query = it; shown = STORE_PAGE; searching = false }, onDismiss = { searching = false }, id = "decky-store-entry", + ) +} + +@Composable +private fun PluginRow(name: String, detail: String, imageUrl: String, actions: @Composable () -> Unit) { + val colors = MaterialTheme.colorScheme + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) { + val shape = RoundedCornerShape(8.dp) + Box(Modifier.width(96.dp).aspectRatio(16f / 9f).clip(shape).background(Color(0xFF0E1218))) { + if (imageUrl.isNotEmpty()) AsyncImage(model = imageUrl, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + } + Column(Modifier.weight(1f)) { + Text(name, fontSize = 15.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + } + Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { actions() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 73782db2ed..bc55af594e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -263,6 +263,10 @@ private fun Content( SyncTabPage(s, modifier.padding(horizontal = padH).padding(top = padV)) return } + if (selected == "decky" || selected == "boot-movies") { + SteamTabPage(selected, a, modifier.padding(horizontal = padH).padding(top = padV)) + return + } if (selected == "updates") { UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) return diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index 65dc828be8..2322e93827 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -56,6 +56,7 @@ import androidx.compose.material.icons.filled.Terminal import androidx.compose.material.icons.filled.Apps import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.SdStorage +import androidx.compose.material.icons.filled.Movie import androidx.compose.material.icons.filled.Sync import androidx.compose.material.icons.filled.MoreHoriz import androidx.compose.material.icons.automirrored.outlined.ArrowBack @@ -206,6 +207,8 @@ internal fun railLabelIcon(key: String): Pair = when (key) { "setup" -> R.string.rail_setup to Icons.Filled.Settings "storage" -> R.string.rail_storage to Icons.Filled.SdStorage "sync" -> R.string.rail_sync to Icons.Filled.Sync + "decky" -> R.string.rail_decky to DeckyIcon + "boot-movies" -> R.string.rail_boot_movies to Icons.Filled.Movie NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz else -> R.string.rail_updates to updatesIcon(RunningBuild.kind()) } 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 920bb7f7f0..f58ee90807 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -126,6 +126,8 @@ internal object SheetTab { const val LIBRARY = "library" const val STEAM = "steam" const val FILES = "files" + const val DECKY = "decky" + const val BOOT_MOVIES = "boot-movies" } internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float = 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 fc611d6ca6..e931c7ec7a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -113,6 +113,9 @@ class ModeSettings( val deckyDownloadingBinary: Boolean = false, val deckyEnabled: Boolean = false, val deckySessionRunning: Boolean = false, + val deckyPlugins: List = emptyList(), + val deckyStore: List? = null, + val deckyStoreFailed: Boolean = false, ) class ModeSettingsActions( @@ -171,6 +174,9 @@ class ModeSettingsActions( val onDeckyEnabled: (Boolean) -> Unit = {}, val onDeckyUninstall: () -> Unit = {}, val onPickDeckyPluginZip: () -> Unit = {}, + val onDeckyStoreRefresh: () -> Unit = {}, + val onDeckyStoreInstall: (com.droiddeck.launcher.runtime.DeckyStore.Plugin) -> Unit = {}, + val onDeckyRemove: (com.droiddeck.launcher.runtime.DeckyStore.Installed) -> Unit = {}, val onDismiss: () -> Unit, ) @@ -220,6 +226,8 @@ class SheetExtras( fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) { val steam = s.mode == SessionService.MODE_STEAM val host = rememberMenuHost() + if (tab == SheetTab.DECKY) { DeckyGroups(s, a, host); return } + if (tab == SheetTab.BOOT_MOVIES) { if (s.bootMovie != null) BootMovieGroup(s, a, host); return } Text( stringResource(when (s.mode) { SessionService.MODE_STEAM -> R.string.sheet_scope_steam @@ -509,75 +517,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: } if (tab == SheetTab.STEAM && steam) { extras.account(host) - SettingsGroup(stringResource(R.string.mode_decky)) { - val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null && - s.deckyInstalled != s.deckyLatestRelease.tag - val status = when { - s.deckyStage != null -> s.deckyStage - s.deckyChecking -> stringResource(R.string.mode_decky_checking) - s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag) - s.deckyInstalled == null -> stringResource(R.string.mode_decky_none) - s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled) - updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag) - else -> stringResource(R.string.mode_decky_current, s.deckyInstalled) - } - SettingsRow(stringResource(R.string.mode_decky_loader), status) { - val action = when { - s.deckyStage != null -> stringResource(R.string.common_working) - s.deckyChecking -> stringResource(R.string.common_checking) - s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest) - s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update) - else -> stringResource(R.string.common_check) - } - Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) { - SecondaryButton( - action, - enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning, - ) { - if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck() - else s.deckyLatestRelease?.let(a.onDeckyInstall) - } - if (s.deckyInstalled != null) DeckyUninstall(enabled = s.deckyStage == null && !s.deckySessionRunning, onUninstall = a.onDeckyUninstall) - } - } - ChoiceRow( - host, "decky-channel", stringResource(R.string.decky_channel), - stringResource(R.string.decky_channel_hint), - listOf( - DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable), - DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease), - ) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf( - DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing), - ) else emptyList(), - s.deckyBranch, - enabled = s.deckyStage == null && !s.deckySessionRunning, - onPick = a.onDeckyBranch, - ) - if (s.deckyInstalled != null) ToggleRow( - host, "decky-enabled", stringResource(R.string.mode_decky), - if (s.deckyEnabled) stringResource(R.string.mode_decky_on) - else stringResource(R.string.mode_decky_off), - s.deckyEnabled, - enabled = !s.deckySessionRunning && s.deckyStage == null, - onChange = a.onDeckyEnabled, - ) - SettingsRow( - stringResource(R.string.mode_decky_plugins), - stringResource(R.string.mode_decky_plugins_hint), - ) { - SecondaryButton( - if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip), - enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning, - onClick = a.onPickDeckyPluginZip, - ) - } - if (s.deckyStage != null && s.deckyPercent >= 0) { - LinearProgressIndicator( - progress = { s.deckyPercent / 100f }, - modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp), - ) - } - } SettingsGroup(stringResource(R.string.mode_client)) { ToggleRow( host, "mangoapp", stringResource(R.string.mode_mangoapp), @@ -607,7 +546,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: onPick = a.onSteamClientArch, ) } - if (s.bootMovie != null) BootMovieGroup(s, a, host) if (s.integration != null) SteamIntegrationGroup(s.integration, onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation) } @@ -669,7 +607,7 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit) private const val DECKY_ZIP_WARNING_SECONDS = 5 @Composable -private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { +internal fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { val colors = MaterialTheme.colorScheme val label = stringResource(R.string.common_uninstall) val title = stringResource(R.string.mode_decky_remove_title) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 1a674da7f6..99785c488a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -26,10 +26,10 @@ internal object DeveloperTools { internal object NavTabs { const val MORE = "more" - val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") - val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") + val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") + val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") val DEFAULT_HIDDEN = setOf("android-apps", "agent") - private val SHELVED_WHEN_NEW = setOf("storage", "sync", "android-apps", "agent") + private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent") private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates") private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync") private const val LAYOUT_VERSION = 2 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt index d25f723651..19af4ed03b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt @@ -75,6 +75,19 @@ internal fun SyncTabPage(s: FrontEndState, modifier: Modifier) { } } +@Composable +internal fun SteamTabPage(key: String, a: FrontEndActions, modifier: Modifier) { + LaunchedEffect(Unit) { a.onSteamSettings() } + Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + PageHeader(stringResource(if (key == "decky") R.string.rail_decky else R.string.rail_boot_movies)) + a.modeSheet( + com.droiddeck.launcher.session.SessionService.MODE_STEAM, + if (key == "decky") SheetTab.DECKY else SheetTab.BOOT_MOVIES, + SheetExtras(), + ) + } +} + @Composable private fun ResetTabsRow() { val ctx = androidx.compose.ui.platform.LocalContext.current 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 cda181d501..b95dd6ae1b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -93,6 +93,8 @@ internal object SettingsIndex { s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"), SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")), SettingsEntry(SettingsPlace.TAB, R.string.rail_sync, tab = "sync", words = listOf("syncthing", "saves")), + SettingsEntry(SettingsPlace.TAB, R.string.rail_decky, tab = "decky", words = listOf("plugins", "plugin store", "homebrew", "loader")), + SettingsEntry(SettingsPlace.TAB, R.string.rail_boot_movies, tab = "boot-movies", words = listOf("startup movie", "boot video", "animation", "steamdeckrepo")), s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"), s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f8217b0fd5..018c08995c 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -332,7 +332,6 @@ ุจุฏุก ุงู„ุชุดุบูŠู„ ุงู„ูุชุญ ุนู†ุฏ ุงู„ุชุดุบูŠู„ ูŠุจุฏุฃ ู‡ุฐู‡ ุงู„ุฌู„ุณุฉ ุนู†ุฏ ุชุดุบูŠู„ DroidDeck. - Decky ุฌุงุฑู ุงู„ุจุญุซ ุนู† ุฅุตุฏุงุฑุงุชโ€ฆ ุฌุงู‡ุฒ ู„ุชุซุจูŠุช %1$s. ู„ู… ูŠุชู… ุงู„ุนุซูˆุฑ ุนู„ู‰ ุฅุตุฏุงุฑ ู…ุชูˆุงูู‚. ุญุงูˆู„ ู…ุฑุฉ ุฃุฎุฑู‰ ู„ุงุญู‚ู‹ุง. @@ -341,14 +340,10 @@ ู…ุญุฏูŽู‘ุซ ยท %1$s ุงู„ู…ูุญู…ูู‘ู„ ุชุซุจูŠุช ุฃุญุฏุซ ุฅุตุฏุงุฑ - ู‚ู†ุงุฉ ุงู„ุชุญุฏูŠุซ - ุฅุตุฏุงุฑุงุช Decky Loader ุงู„ุชูŠ ุชูุซุจูŽู‘ุช. ูŠุณุชุฎุฏู… ู…ูุญุฏูู‘ุซ Decky ู†ูุณู‡ ุงู„ู‚ู†ุงุฉ ุฐุงุชู‡ุง. ู…ุณุชู‚ุฑุฉ ุฅุตุฏุงุฑ ุชุฌุฑูŠุจูŠ ู…ุณุจู‚ ุงุฎุชุจุงุฑ ุชุนุฐู‘ุฑ ุญูุธ ู‚ู†ุงุฉ ุชุญุฏูŠุซ Decky - ูŠุจุฏุฃ ู…ุน Steam. ุฃุซู†ุงุก ุชูุนูŠู„ู‡ุŒ ู‚ุฏ ุชุชู…ูƒู† ุงู„ุชุทุจูŠู‚ุงุช ุงู„ุฃุฎุฑู‰ ุนู„ู‰ ู‡ุฐุง ุงู„ุฌู‡ุงุฒ ู…ู† ุงู„ุชุญูƒู… ููŠ Steam. - ู…ุชูˆู‚ู. ูŠุจู‚ู‰ ู…ู†ูุฐ ุชุตุญูŠุญ ุงู„ุฃุฎุทุงุก ุนู† ุจูุนุฏ ููŠ Steam ู…ุบู„ู‚ู‹ุง. ู‡ู„ ุชุฑูŠุฏ ุฅู„ุบุงุก ุชุซุจูŠุช Decky LoaderุŸ ูŠุฒูŠู„ ุงู„ู…ูุญู…ูู‘ู„. ูŠุชู… ุงู„ุงุญุชูุงุธ ุจุงู„ู…ูƒูˆู†ุงุช ุงู„ุฅุถุงููŠุฉ ูˆุงู„ุฅุนุฏุงุฏุงุช. ุงู„ุนู…ูŠู„ 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 8b0e2378e3..2f30d0ba67 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -332,7 +332,6 @@ Inicio Abrir al iniciar Inicia esta sesiรณn cuando se abre DroidDeck. - Decky Buscando versionesโ€ฆ Listo para instalar %1$s. No se encontrรณ ninguna versiรณn compatible. Intรฉntalo mรกs tarde. @@ -341,14 +340,10 @@ Al dรญa ยท %1$s Loader Instalar la รบltima - Canal de actualizaciones - Quรฉ versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal. Estable Preliminar Pruebas No se pudo guardar el canal de actualizaciones de Decky - Se inicia con Steam. Mientras estรฉ activado, otras apps de este dispositivo podrรญan controlar Steam. - Desactivado. El puerto de depuraciรณn remota de Steam permanece cerrado. ยฟDesinstalar Decky Loader? Elimina el loader. Tus plugins y ajustes se conservan. Cliente diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 8531a5dab1..3a2428fbfb 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -332,7 +332,6 @@ ะกั‚ะฐั€ั‚ะธั€ะฐะฝะต ะžั‚ะฒะฐั€ัะฝะต ะฟั€ะธ ัั‚ะฐั€ั‚ะธั€ะฐะฝะต ะกั‚ะฐั€ั‚ะธั€ะฐ ั‚ะฐะทะธ ัะตัะธั, ะบะพะณะฐั‚ะพ DroidDeck ัะต ัั‚ะฐั€ั‚ะธั€ะฐ. - Decky ะŸั€ะพะฒะตั€ะบะฐ ะทะฐ ะธะทะดะฐะฝะธัโ€ฆ ะ“ะพั‚ะพะฒะพ ะทะฐ ะธะฝัั‚ะฐะปะธั€ะฐะฝะต ะฝะฐ %1$s. ะะต ะต ะฝะฐะผะตั€ะตะฝะฐ ััŠะฒะผะตัั‚ะธะผะฐ ะฒะตั€ัะธั. ะžะฟะธั‚ะฐะนั‚ะต ะฟะพ-ะบัŠัะฝะพ. @@ -341,14 +340,10 @@ ะะบั‚ัƒะฐะปะฝะพ ยท %1$s ะ—ะฐั€ะตะถะดะฐั‡ ะ˜ะฝัั‚ะฐะปะธั€ะฐะฝะต ะฝะฐ ะฟะพัะปะตะดะฝะฐั‚ะฐ ะฒะตั€ัะธั - ะšะฐะฝะฐะป ะทะฐ ะฐะบั‚ัƒะฐะปะธะทะฐั†ะธะธ - ะšะพะธ ะธะทะดะฐะฝะธั ะฝะฐ Decky Loader ะดะฐ ัะต ะธะฝัั‚ะฐะปะธั€ะฐั‚. ะกะพะฑัั‚ะฒะตะฝะธัั‚ ะฐะบั‚ัƒะฐะปะธะทะฐั‚ะพั€ ะฝะฐ Decky ะธะทะฟะพะปะทะฒะฐ ััŠั‰ะธั ะบะฐะฝะฐะป. ะกั‚ะฐะฑะธะปะตะฝ ะŸั€ะตะดะฒะฐั€ะธั‚ะตะปะตะฝ ะขะตัั‚ะพะฒ ะšะฐะฝะฐะปัŠั‚ ะทะฐ ะฐะบั‚ัƒะฐะปะธะทะฐั†ะธะธ ะฝะฐ Decky ะฝะต ะผะพะถะฐ ะดะฐ ะฑัŠะดะต ะทะฐะฟะฐะทะตะฝ - ะกั‚ะฐั€ั‚ะธั€ะฐ ะทะฐะตะดะฝะพ ััŠั Steam. ะ”ะพะบะฐั‚ะพ ะต ะฒะบะปัŽั‡ะตะฝะพ, ะดั€ัƒะณะธ ะฟั€ะธะปะพะถะตะฝะธั ะฝะฐ ั‚ะพะฒะฐ ัƒัั‚ั€ะพะนัั‚ะฒะพ ะผะพะถะต ะดะฐ ะผะพะณะฐั‚ ะดะฐ ะบะพะฝั‚ั€ะพะปะธั€ะฐั‚ Steam. - ะ˜ะทะบะปัŽั‡ะตะฝะพ. ะŸะพั€ั‚ัŠั‚ ะทะฐ ะพั‚ะดะฐะปะตั‡ะตะฝะพ ะดะตะฑัŠะณะฒะฐะฝะต ะฝะฐ Steam ะพัั‚ะฐะฒะฐ ะทะฐั‚ะฒะพั€ะตะฝ. ะ”ะตะธะฝัั‚ะฐะปะธั€ะฐะฝะต ะฝะฐ Decky Loader? ะŸั€ะตะผะฐั…ะฒะฐ ะทะฐั€ะตะถะดะฐั‰ะธั ะผะพะดัƒะป. ะŸะปัŠะณะธะฝะธั‚ะต ะธ ะฝะฐัั‚ั€ะพะนะบะธั‚ะต ะฒะธ ัะต ะทะฐะฟะฐะทะฒะฐั‚. ะšะปะธะตะฝั‚ diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e8d2dc5c94..4c920c1cf0 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -332,7 +332,6 @@ Spouลกtฤ›nรญ Otevล™รญt pล™i spuลกtฤ›nรญ Spustรญ tuto relaci pล™i spuลกtฤ›nรญ DroidDeck. - Decky Hledรกnรญ vydรกnรญโ€ฆ Pล™ipraveno k instalaci %1$s. Nenalezeno ลพรกdnรฉ kompatibilnรญ sestavenรญ. Zkuste to pozdฤ›ji. @@ -341,14 +340,10 @@ Aktuรกlnรญ ยท %1$s Loader Nainstalovat nejnovฤ›jลกรญ - Kanรกl aktualizacรญ - Kterรก vydรกnรญ Decky Loader instalovat. Vlastnรญ aktualizรกtor Decky pouลพรญvรก stejnรฝ kanรกl. Stabilnรญ Pล™edbฤ›ลพnรฉ vydรกnรญ Testovacรญ Kanรกl aktualizacรญ Decky se nepodaล™ilo uloลพit - Spouลกtรญ se se Steamem. Kdyลพ je zapnuto, jinรฉ aplikace na tomto zaล™รญzenรญ mohou mรญt moลพnost ovlรกdat Steam. - Vypnuto. Port pro vzdรกlenรฉ ladฤ›nรญ Steamu zลฏstรกvรก zavล™enรฝ. Odinstalovat Decky Loader? Odstranรญ loader. Vaลกe pluginy a nastavenรญ zลฏstanou zachovรกny. Klient diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 043a52c4b8..c34b855e74 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -332,7 +332,6 @@ Opstart ร…bn ved start Starter denne session, nรฅr DroidDeck startes. - Decky Sรธger efter udgivelserโ€ฆ Klar til at installere %1$s. Ingen kompatibel build fundet. Prรธv igen senere. @@ -341,14 +340,10 @@ Opdateret ยท %1$s Loader Installer nyeste - Opdateringskanal - Hvilke Decky Loader-udgivelser der installeres. Deckys egen opdatering bruger samme kanal. Stabil Forhรฅndsudgivelse Test Kunne ikke gemme Decky-opdateringskanalen - Starter med Steam. Mens den er til, kan andre apps pรฅ denne enhed muligvis styre Steam. - Fra. Steams fjerndebugport forbliver lukket. Afinstaller Decky Loader? Fjerner loaderen. Dine plugins og indstillinger bevares. Klient diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 4d52b46b32..8715f4b3a3 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -332,7 +332,6 @@ Start Beim Start รถffnen Startet diese Sitzung, wenn DroidDeck startet. - Decky Suche nach Releasesโ€ฆ Bereit zur Installation von %1$s. Kein kompatibler Build gefunden. Versuch es spรคter noch einmal. @@ -341,14 +340,10 @@ Aktuell ยท %1$s Loader Neueste Version installieren - Update-Kanal - Welche Decky-Loader-Releases installiert werden. Deckys eigener Updater nutzt denselben Kanal. Stabil Vorabversion Test Decky-Update-Kanal konnte nicht gespeichert werden - Startet mit Steam. Solange aktiv, kรถnnen andere Apps auf diesem Gerรคt Steam mรถglicherweise steuern. - Aus. Der Remote-Debugging-Port von Steam bleibt geschlossen. Decky Loader deinstallieren? Entfernt den Loader. Deine Plugins und Einstellungen bleiben erhalten. Client diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 826d8680e6..93b0438ef5 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -332,7 +332,6 @@ ฮ•ฮบฮบฮฏฮฝฮทฯƒฮท ฮ†ฮฝฮฟฮนฮณฮผฮฑ ฮบฮฑฯ„ฮฌ ฯ„ฮทฮฝ ฮตฮบฮบฮฏฮฝฮทฯƒฮท ฮžฮตฮบฮนฮฝฮฌ ฮฑฯ…ฯ„ฮฎ ฯ„ฮท ฯƒฯ…ฮฝฮตฮดฯฮฏฮฑ ฯŒฯ„ฮฑฮฝ ฮฑฮฝฮฟฮฏฮณฮตฮน ฯ„ฮฟ DroidDeck. - Decky ฮˆฮปฮตฮณฯ‡ฮฟฯ‚ ฮณฮนฮฑ ฮตฮบฮดฯŒฯƒฮตฮนฯ‚โ€ฆ ฮˆฯ„ฮฟฮนฮผฮฟ ฮณฮนฮฑ ฮตฮณฮบฮฑฯ„ฮฌฯƒฯ„ฮฑฯƒฮท %1$s. ฮ”ฮตฮฝ ฮฒฯฮญฮธฮทฮบฮต ฯƒฯ…ฮผฮฒฮฑฯ„ฯŒ build. ฮ”ฮฟฮบฮนฮผฮฌฯƒฯ„ฮต ฮพฮฑฮฝฮฌ ฮฑฯฮณฯŒฯ„ฮตฯฮฑ. @@ -341,14 +340,10 @@ ฮ•ฮฝฮทฮผฮตฯฯ‰ฮผฮญฮฝฮฟ ยท %1$s ฮฆฮฟฯฯ„ฯ‰ฯ„ฮฎฯ‚ ฮ•ฮณฮบฮฑฯ„ฮฌฯƒฯ„ฮฑฯƒฮท ฯ„ฮตฮปฮตฯ…ฯ„ฮฑฮฏฮฑฯ‚ ฮญฮบฮดฮฟฯƒฮทฯ‚ - ฮšฮฑฮฝฮฌฮปฮน ฮตฮฝฮทฮผฮตฯฯŽฯƒฮตฯ‰ฮฝ - ฮ ฮฟฮนฮตฯ‚ ฮตฮบฮดฯŒฯƒฮตฮนฯ‚ ฯ„ฮฟฯ… Decky Loader ฮธฮฑ ฮตฮณฮบฮฑฯ„ฮฑฯƒฯ„ฮฑฮธฮฟฯฮฝ. ฮคฮฟ ฯ€ฯฯŒฮณฯฮฑฮผฮผฮฑ ฮตฮฝฮทฮผฮญฯฯ‰ฯƒฮทฯ‚ ฯ„ฮฟฯ… Decky ฯ‡ฯฮทฯƒฮนฮผฮฟฯ€ฮฟฮนฮตฮฏ ฯ„ฮฟ ฮฏฮดฮนฮฟ ฮบฮฑฮฝฮฌฮปฮน. ฮฃฯ„ฮฑฮธฮตฯฯŒ ฮ ฯฮฟฮญฮบฮดฮฟฯƒฮท ฮ”ฮฟฮบฮนฮผฮฑฯƒฯ„ฮนฮบฯŒ ฮ”ฮตฮฝ ฮฎฯ„ฮฑฮฝ ฮดฯ…ฮฝฮฑฯ„ฮฎ ฮท ฮฑฯ€ฮฟฮธฮฎฮบฮตฯ…ฯƒฮท ฯ„ฮฟฯ… ฮบฮฑฮฝฮฑฮปฮนฮฟฯ ฮตฮฝฮทฮผฮตฯฯŽฯƒฮตฯ‰ฮฝ ฯ„ฮฟฯ… Decky - ฮžฮตฮบฮนฮฝฮฌ ฮผฮต ฯ„ฮฟ Steam. ฮŒฯƒฮฟ ฮตฮฏฮฝฮฑฮน ฮตฮฝฮตฯฮณฯŒ, ฮฌฮปฮปฮตฯ‚ ฮตฯ†ฮฑฯฮผฮฟฮณฮญฯ‚ ฯƒฮต ฮฑฯ…ฯ„ฮฎ ฯ„ฮท ฯƒฯ…ฯƒฮบฮตฯ…ฮฎ ฮผฯ€ฮฟฯฮตฮฏ ฮฝฮฑ ฮตฮฏฮฝฮฑฮน ฯƒฮต ฮธฮญฯƒฮท ฮฝฮฑ ฮตฮปฮญฮณฮพฮฟฯ…ฮฝ ฯ„ฮฟ Steam. - ฮ‘ฮฝฮตฮฝฮตฯฮณฯŒ. ฮ— ฮธฯฯฮฑ ฮฑฯ€ฮฟฮผฮฑฮบฯฯ…ฯƒฮผฮญฮฝฮฟฯ… ฮตฮฝฯ„ฮฟฯ€ฮนฯƒฮผฮฟฯ ฯƒฯ†ฮฑฮปฮผฮฌฯ„ฯ‰ฮฝ ฯ„ฮฟฯ… Steam ฯ€ฮฑฯฮฑฮผฮญฮฝฮตฮน ฮบฮปฮตฮนฯƒฯ„ฮฎ. ฮšฮฑฯ„ฮฌฯฮณฮทฯƒฮท ฮตฮณฮบฮฑฯ„ฮฌฯƒฯ„ฮฑฯƒฮทฯ‚ ฯ„ฮฟฯ… Decky Loader; ฮšฮฑฯ„ฮฑฯฮณฮตฮฏ ฯ„ฮฟฮฝ loader. ฮคฮฑ plugins ฮบฮฑฮน ฮฟฮน ฯฯ…ฮธฮผฮฏฯƒฮตฮนฯ‚ ฯƒฮฑฯ‚ ฮดฮนฮฑฯ„ฮทฯฮฟฯฮฝฯ„ฮฑฮน. ฮ ฮตฮปฮฌฯ„ฮทฯ‚ diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 3dcc0a4d1e..a8a7525c87 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -332,7 +332,6 @@ Inicio Abrir al iniciar Inicia esta sesiรณn cuando se abre DroidDeck. - Decky Buscando versionesโ€ฆ Listo para instalar %1$s. No se encontrรณ ninguna versiรณn compatible. Intรฉntalo mรกs tarde. @@ -341,14 +340,10 @@ Al dรญa ยท %1$s Loader Instalar la รบltima - Canal de actualizaciones - Quรฉ versiones de Decky Loader se instalan. El actualizador propio de Decky usa el mismo canal. Estable Preliminar Pruebas No se ha podido guardar el canal de actualizaciones de Decky - Se inicia con Steam. Mientras estรฉ activado, otras apps de este dispositivo podrรญan controlar Steam. - Desactivado. El puerto de depuraciรณn remota de Steam permanece cerrado. ยฟDesinstalar Decky Loader? Elimina el loader. Tus plugins y ajustes se conservan. Cliente diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index ebe843786e..084d781755 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -332,7 +332,6 @@ Kรคynnistys Avaa kรคynnistyksessรค Kรคynnistรครค tรคmรคn istunnon, kun DroidDeck avataan. - Decky Tarkistetaan julkaisujaโ€ฆ Valmiina asentamaan %1$s. Yhteensopivaa versiota ei lรถytynyt. Yritรค myรถhemmin uudelleen. @@ -341,14 +340,10 @@ Ajan tasalla ยท %1$s Lataaja Asenna uusin - Pรคivityskanava - Mitkรค Decky Loader -julkaisut asennetaan. Deckyn oma pรคivitysohjelma kรคyttรครค samaa kanavaa. Vakaa Esijulkaisu Testaus Deckyn pรคivityskanavaa ei voitu tallentaa - Kรคynnistyy Steamin kanssa. Pรครคllรค ollessaan muut tรคmรคn laitteen sovellukset voivat pystyรค ohjaamaan Steamia. - Pois. Steamin etรคvianmรครคritysportti pysyy suljettuna. Poistetaanko Decky Loader? Poistaa loaderin. Laajennuksesi ja asetuksesi sรคilyvรคt. Asiakasohjelma diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index bd5525aa28..c12f0c8afe 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -332,7 +332,6 @@ Dรฉmarrage Ouvrir au dรฉmarrage Lance cette session au dรฉmarrage de DroidDeck. - Decky Vรฉrification des versionsโ€ฆ Prรชt ร  installer %1$s. Aucune version compatible trouvรฉe. Veuillez rรฉessayer plus tard. @@ -341,14 +340,10 @@ ร€ jour ยท %1$s Chargeur Installer la derniรจre version - Canal de mise ร  jour - Les versions de Decky Loader ร  installer. Le programme de mise ร  jour de Decky utilise le mรชme canal. Stable Prรฉversion Test Impossible d\'enregistrer le canal de mise ร  jour de Decky - Dรฉmarre avec Steam. Une fois activรฉ, d\'autres applications sur cet appareil peuvent contrรดler Steam. - Dรฉsactivรฉ. Le port de dรฉbogage distant de Steam reste fermรฉ. Dรฉsinstaller Decky Loader ? Supprime le chargeur. Vos plugins et paramรจtres seront conservรฉs. Client diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 7cd6bf3050..b2f2633475 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -332,7 +332,6 @@ เคธเฅเคŸเคพเคฐเฅเคŸเค…เคช เคฒเฅ‰เคจเฅเคš เคชเคฐ เค–เฅ‹เคฒเฅ‡เค‚ DroidDeck เค–เฅเคฒเคจเฅ‡ เคชเคฐ เคฏเคน เคธเฅ‡เคถเคจ เคถเฅเคฐเฅ‚ เค•เคฐเคคเคพ เคนเฅˆเฅค - Decky เคฐเคฟเคฒเฅ€เคœเคผ เคฆเฅ‡เค–เฅ€ เคœเคพ เคฐเคนเฅ€ เคนเฅˆเค‚โ€ฆ %1$s เค‡เค‚เคธเฅเคŸเฅ‰เคฒ เค•เคฐเคจเฅ‡ เค•เฅ‡ เคฒเคฟเค เคคเฅˆเคฏเคพเคฐเฅค เค•เฅ‹เคˆ เค•เคฎเฅเคชเฅˆเคŸเคฟเคฌเคฒ เคฌเคฟเคฒเฅเคก เคจเคนเฅ€เค‚ เคฎเคฟเคฒเคพเฅค เคฌเคพเคฆ เคฎเฅ‡เค‚ เคซเคฟเคฐ เค•เฅ‹เคถเคฟเคถ เค•เคฐเฅ‡เค‚เฅค @@ -341,14 +340,10 @@ เคจเคตเฅ€เคจเคคเคฎ ยท %1$s เคฒเฅ‹เคกเคฐ เคจเคตเฅ€เคจเคคเคฎ เค‡เค‚เคธเฅเคŸเฅ‰เคฒ เค•เคฐเฅ‡เค‚ - เค…เคชเคกเฅ‡เคŸ เคšเฅˆเคจเคฒ - เค•เฅŒเคจ-เคธเฅ€ Decky Loader เคฐเคฟเคฒเฅ€เคœเคผ เค‡เค‚เคธเฅเคŸเฅ‰เคฒ เค•เคฐเคจเฅ€ เคนเฅˆเค‚เฅค Decky เค•เคพ เค…เคชเคจเคพ เค…เคชเคกเฅ‡เคŸเคฐ เคญเฅ€ เคฏเคนเฅ€ เคšเฅˆเคจเคฒ เค‡เคธเฅเคคเฅ‡เคฎเคพเคฒ เค•เคฐเคคเคพ เคนเฅˆเฅค เคธเฅเคŸเฅ‡เคฌเคฒ เคชเฅเคฐเฅ€-เคฐเคฟเคฒเฅ€เคœเคผ เคŸเฅ‡เคธเฅเคŸเคฟเค‚เค— Decky เค…เคชเคกเฅ‡เคŸ เคšเฅˆเคจเคฒ เคธเฅ‡เคต เคจเคนเฅ€เค‚ เคนเฅ‹ เคธเค•เคพ - Steam เค•เฅ‡ เคธเคพเคฅ เคถเฅเคฐเฅ‚ เคนเฅ‹เคคเคพ เคนเฅˆเฅค เคšเคพเคฒเฅ‚ เคฐเคนเคคเฅ‡ เคนเฅเค, เค‡เคธ เคกเคฟเคตเคพเค‡เคธ เค•เฅ‡ เคฆเฅ‚เคธเคฐเฅ‡ เคเคช Steam เค•เฅ‹ เคจเคฟเคฏเค‚เคคเฅเคฐเคฟเคค เค•เคฐ เคธเค•เคคเฅ‡ เคนเฅˆเค‚เฅค - เคฌเค‚เคฆเฅค Steam เค•เคพ เคฐเคฟเคฎเฅ‹เคŸ เคกเคฟเคฌเค—เคฟเค‚เค— เคชเฅ‹เคฐเฅเคŸ เคฌเค‚เคฆ เคฐเคนเคคเคพ เคนเฅˆเฅค Decky Loader เค…เคจเค‡เค‚เคธเฅเคŸเฅ‰เคฒ เค•เคฐเฅ‡เค‚? เคฒเฅ‹เคกเคฐ เคนเคŸเคพเคคเคพ เคนเฅˆเฅค เค†เคชเค•เฅ‡ เคชเฅเคฒเค—เค‡เคจ เค”เคฐ เคธเฅ‡เคŸเคฟเค‚เค— เคฌเคจเฅ€ เคฐเคนเคคเฅ€ เคนเฅˆเค‚เฅค เค•เฅเคฒเคพเค‡เค‚เคŸ diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index d4c46656d6..b9d15f6725 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -332,7 +332,6 @@ Indรญtรกs Megnyitรกs indรญtรกskor A DroidDeck indulรกsakor elindรญtja ezt a munkamenetet. - Decky Kiadรกsok keresรฉseโ€ฆ Kรฉszen รกll a %1$s telepรญtรฉsรฉre. Nem talรกlhatรณ kompatibilis build. Prรณbรกlja รบjra kรฉsล‘bb. @@ -341,14 +340,10 @@ Naprakรฉsz ยท %1$s Betรถltล‘ Legรบjabb telepรญtรฉse - Frissรญtรฉsi csatorna - Mely Decky Loader-kiadรกsok telepรผljenek. A Decky sajรกt frissรญtล‘je ugyanezt a csatornรกt hasznรกlja. Stabil Elล‘zetes kiadรกs Tesztelรฉs Nem sikerรผlt menteni a Decky frissรญtรฉsi csatornรกjรกt - A Steammel egyรผtt indul. Amรญg be van kapcsolva, az eszkรถzรถn lรฉvล‘ mรกs alkalmazรกsok is irรกnyรญthatjรกk a Steamet. - Ki. A Steam tรกvoli hibakeresรฉsi portja zรกrva marad. Eltรกvolรญtja a Decky Loadert? Eltรกvolรญtja a betรถltล‘t. A bล‘vรญtmรฉnyei รฉs beรกllรญtรกsai megmaradnak. Kliens diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 53c9708ecc..56dd216a98 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -332,7 +332,6 @@ Mulai Buka saat peluncuran Memulai sesi ini saat DroidDeck diluncurkan. - Decky Memeriksa rilisโ€ฆ Siap menginstal %1$s. Tidak ditemukan build yang kompatibel. Coba lagi nanti. @@ -341,14 +340,10 @@ Terbaru ยท %1$s Loader Instal versi terbaru - Saluran Pembaruan - Rilis Decky Loader mana yang akan diinstal. Pembaru bawaan Decky menggunakan saluran yang sama. Stabil Prarilis Pengujian Tidak dapat menyimpan saluran pembaruan Decky - Dimulai bersama Steam. Saat aktif, aplikasi lain di perangkat ini mungkin dapat mengendalikan Steam. - Nonaktif. Port debugging jarak jauh Steam tetap tertutup. Hapus instalasi Decky Loader? Menghapus loader. Plugin dan setelan Anda tetap disimpan. Klien diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 78a9ae250a..9d574d4ba4 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -332,7 +332,6 @@ Avvio Apri all\'avvio Avvia questa sessione all\'avvio di DroidDeck. - Decky Ricerca di releaseโ€ฆ Pronto per installare %1$s. Nessuna build compatibile trovata. Riprova piรน tardi. @@ -341,14 +340,10 @@ Ultima versione ยท %1$s Loader Installa l\'ultima versione - Canale di aggiornamento - Quali release di Decky Loader installare. Anche l\'aggiornamento integrato di Decky usa lo stesso canale. Stabile Pre-release Test Impossibile salvare il canale di aggiornamento di Decky - Si avvia con Steam. Quando รจ attivo, altre app su questo dispositivo potrebbero controllare Steam. - Disattivato. La porta di debug remoto di Steam resta chiusa. Disinstallare Decky Loader? Rimuove il loader. I tuoi plugin e le impostazioni vengono mantenuti. Client diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index a7f1d18d19..f09bbbff7a 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -332,7 +332,6 @@ ่ตทๅ‹• ่ตทๅ‹•ๆ™‚ใซ้–‹ใ DroidDeck ใฎ่ตทๅ‹•ๆ™‚ใซใ“ใฎใ‚ปใƒƒใ‚ทใƒงใƒณใ‚’้–‹ๅง‹ใ—ใพใ™ใ€‚ - Decky ใƒชใƒชใƒผใ‚นใ‚’็ขบ่ชไธญโ€ฆ %1$sใ‚’ใ‚คใƒณใ‚นใƒˆใƒผใƒซใ™ใ‚‹ๆบ–ๅ‚™ใŒใงใใพใ—ใŸใ€‚ ไบ’ๆ›ๆ€งใฎใ‚ใ‚‹ใƒใƒผใ‚ธใƒงใƒณใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“ใ€‚ๅพŒใงใ‚‚ใ†ไธ€ๅบฆใŠ่ฉฆใ—ใใ ใ•ใ„ใ€‚ @@ -341,14 +340,10 @@ ๆœ€ๆ–ฐใงใ™ ยท %1$s ใƒญใƒผใƒ€ใƒผ ๆœ€ๆ–ฐใƒใƒผใ‚ธใƒงใƒณใ‚’ใ‚คใƒณใ‚นใƒˆใƒผใƒซ - ใ‚ขใƒƒใƒ—ใƒ‡ใƒผใƒˆใƒใƒฃใƒณใƒใƒซ - ใ‚คใƒณใ‚นใƒˆใƒผใƒซใ™ใ‚‹Decky Loaderใฎใƒชใƒชใƒผใ‚นใงใ™ใ€‚Decky่‡ช่บซใฎใ‚ขใƒƒใƒ—ใƒ‡ใƒผใ‚ฟใƒผใ‚‚ๅŒใ˜ใƒใƒฃใƒณใƒใƒซใ‚’ไฝฟ็”จใ—ใพใ™ใ€‚ ๅฎ‰ๅฎš็‰ˆ ใƒ—ใƒฌใƒชใƒชใƒผใ‚น็‰ˆ ใƒ†ใ‚นใƒˆ็‰ˆ Deckyใฎใ‚ขใƒƒใƒ—ใƒ‡ใƒผใƒˆใƒใƒฃใƒณใƒใƒซใ‚’ไฟๅญ˜ใงใใพใ›ใ‚“ใงใ—ใŸ - Steamใจๅ…ฑใซ่ตทๅ‹•ใ—ใพใ™ใ€‚ๆœ‰ๅŠนใซใ™ใ‚‹ใจใ€ใ“ใฎใƒ‡ใƒใ‚คใ‚นไธŠใฎไป–ใฎใ‚ขใƒ—ใƒชใŒSteamใ‚’ๅˆถๅพกใงใใ‚‹ๅ ดๅˆใŒใ‚ใ‚Šใพใ™ใ€‚ - ใ‚ชใƒ•ใ€‚Steamใฎใƒชใƒขใƒผใƒˆใƒ‡ใƒใƒƒใ‚ฐใƒใƒผใƒˆใฏ้–‰ใ˜ใŸใพใพใซใชใ‚Šใพใ™ใ€‚ Decky Loaderใ‚’ใ‚ขใƒณใ‚คใƒณใ‚นใƒˆใƒผใƒซใ—ใพใ™ใ‹๏ผŸ ใƒญใƒผใƒ€ใƒผใ‚’ๅ‰Š้™คใ—ใพใ™ใ€‚ใƒ—ใƒฉใ‚ฐใ‚คใƒณใจ่จญๅฎšใฏไฟๆŒใ•ใ‚Œใพใ™ใ€‚ ใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆ diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index f97db37e65..d7b6c044a1 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -332,7 +332,6 @@ ์‹œ์ž‘ ์‹คํ–‰ ์‹œ ์—ด๊ธฐ DroidDeck์„ ์‹คํ–‰ํ•  ๋•Œ ์ด ์„ธ์…˜์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. - Decky ๋ฆด๋ฆฌ์Šค ํ™•์ธ ์ค‘โ€ฆ %1$s์„(๋ฅผ) ์„ค์น˜ํ•  ์ค€๋น„๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ํ˜ธํ™˜๋˜๋Š” ๋ฒ„์ „์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋‚˜์ค‘์— ๋‹ค์‹œ ์‹œ๋„ํ•˜์„ธ์š”. @@ -341,14 +340,10 @@ ์ตœ์‹  ๋ฒ„์ „ ยท %1$s ๋กœ๋” ์ตœ์‹  ๋ฒ„์ „ ์„ค์น˜ - ์—…๋ฐ์ดํŠธ ์ฑ„๋„ - ์„ค์น˜ํ•  Decky Loader ๋ฆด๋ฆฌ์Šค์ž…๋‹ˆ๋‹ค. Decky ์ž์ฒด ์—…๋ฐ์ดํ„ฐ๋„ ๊ฐ™์€ ์ฑ„๋„์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ์•ˆ์ •ํŒ ์‚ฌ์ „ ์ถœ์‹œํŒ ํ…Œ์ŠคํŠธํŒ Decky ์—…๋ฐ์ดํŠธ ์ฑ„๋„์„ ์ €์žฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค - Steam๊ณผ ํ•จ๊ป˜ ์‹œ์ž‘๋ฉ๋‹ˆ๋‹ค. ํ™œ์„ฑํ™”ํ•˜๋ฉด ์ด ๊ธฐ๊ธฐ์˜ ๋‹ค๋ฅธ ์•ฑ์ด Steam์„ ์ œ์–ดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. - ๋”. Steam์˜ ์›๊ฒฉ ๋””๋ฒ„๊น… ํฌํŠธ๊ฐ€ ๋‹ซํžŒ ์ƒํƒœ๋กœ ์œ ์ง€๋ฉ๋‹ˆ๋‹ค. Decky Loader๋ฅผ ์ œ๊ฑฐํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ? ๋กœ๋”๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค. ํ”Œ๋Ÿฌ๊ทธ์ธ๊ณผ ์„ค์ •์€ ์œ ์ง€๋ฉ๋‹ˆ๋‹ค. ํด๋ผ์ด์–ธํŠธ diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 9d2d102625..c4c67b0b6f 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -332,7 +332,6 @@ Permulaan Buka semasa pelancaran Memulakan sesi ini apabila DroidDeck dilancarkan. - Decky Menyemak keluaranโ€ฆ Sedia untuk memasang %1$s. Tiada binaan serasi ditemui. Cuba lagi kemudian. @@ -341,14 +340,10 @@ Terkini ยท %1$s Loader Pasang yang terbaharu - Saluran Kemas Kini - Keluaran Decky Loader yang hendak dipasang. Pengemas kini Decky sendiri menggunakan saluran yang sama. Stabil Prakeluaran Pengujian Tidak dapat menyimpan saluran kemas kini Decky - Bermula bersama Steam. Semasa dihidupkan, apl lain pada peranti ini mungkin boleh mengawal Steam. - Mati. Port debug jauh Steam kekal tertutup. Nyahpasang Decky Loader? Mengalih keluar loader. Plugin dan tetapan anda dikekalkan. Klien diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index a09d35a922..633b16d02e 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -332,7 +332,6 @@ Oppstart ร…pne ved oppstart Starter denne รธkten nรฅr DroidDeck starter. - Decky Ser etter utgivelserโ€ฆ Klar til รฅ installere %1$s. Ingen kompatibel build funnet. Prรธv igjen senere. @@ -341,14 +340,10 @@ Oppdatert ยท %1$s Loader Installer nyeste - Oppdateringskanal - Hvilke Decky Loader-utgivelser som installeres. Deckys egen oppdatering bruker samme kanal. Stabil Forhรฅndsutgivelse Testing Kunne ikke lagre oppdateringskanalen for Decky - Starter med Steam. Mens pรฅ, kan andre apper pรฅ denne enheten kanskje styre Steam. - Av. Steams fjernsรธkeport for feilsรธking forblir stengt. Avinstaller Decky Loader? Fjerner loaderen. Programtilleggene og innstillingene dine beholdes. Klient diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 023fe7bb97..5f51dc1cd4 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -332,7 +332,6 @@ Opstarten Openen bij start Start deze sessie wanneer DroidDeck start. - Decky Zoeken naar releasesโ€ฆ Klaar om %1$s te installeren. Geen compatibele build gevonden. Probeer het later opnieuw. @@ -341,14 +340,10 @@ Up-to-date ยท %1$s Loader Nieuwste installeren - Updatekanaal - Welke Decky Loader-releases worden geรฏnstalleerd. De eigen updater van Decky gebruikt hetzelfde kanaal. Stabiel Voorlopige release Testversie Kan het Decky-updatekanaal niet opslaan - Start met Steam. Zolang dit aan staat, kunnen andere apps op dit apparaat Steam mogelijk bedienen. - Uit. De poort voor foutopsporing op afstand van Steam blijft dicht. Decky Loader verwijderen? Verwijdert de loader. Je plug-ins en instellingen blijven behouden. Client diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3ff4e06620..65a0f62751 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -332,7 +332,6 @@ Uruchamianie Otwรณrz przy uruchomieniu Uruchamia tฤ™ sesjฤ™ po uruchomieniu DroidDeck. - Decky Sprawdzanie wydaล„โ€ฆ Gotowe do instalacji: %1$s. Nie znaleziono zgodnej wersji. Sprรณbuj ponownie pรณลบniej. @@ -341,14 +340,10 @@ Aktualna ยท %1$s Program ล‚adujฤ…cy Zainstaluj najnowszฤ… - Kanaล‚ aktualizacji - Ktรณre wydania Decky Loader instalowaฤ‡. Wbudowany aktualizator Decky uลผywa tego samego kanaล‚u. Stabilny Przedpremierowy Testowy Nie udaล‚o siฤ™ zapisaฤ‡ kanaล‚u aktualizacji Decky - Uruchamia siฤ™ ze Steam. Gdy jest wล‚ฤ…czony, inne aplikacje na tym urzฤ…dzeniu mogฤ… sterowaฤ‡ Steam. - Wyล‚ฤ…czony. Port zdalnego debugowania Steam pozostaje zamkniฤ™ty. Odinstalowaฤ‡ Decky Loader? Usuwa program ล‚adujฤ…cy. Twoje wtyczki i ustawienia zostanฤ… zachowane. Klient diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 15c7cb206c..df9839df35 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -332,7 +332,6 @@ Arranque Abrir ao iniciar Inicia esta sessรฃo quando o DroidDeck รฉ aberto. - Decky A procurar versรตesโ€ฆ Pronto para instalar %1$s. Nenhuma versรฃo compatรญvel encontrada. Tente novamente mais tarde. @@ -341,14 +340,10 @@ Atualizado ยท %1$s Carregador Instalar a versรฃo mais recente - Canal de atualizaรงรฃo - Que versรตes do Decky Loader instalar. O atualizador do prรณprio Decky utiliza o mesmo canal. Estรกvel Prรฉ-lanรงamento Testes Nรฃo foi possรญvel guardar o canal de atualizaรงรฃo do Decky - Inicia com o Steam. Enquanto estiver ligado, outras apps neste dispositivo poderรฃo controlar o Steam. - Desligado. A porta de depuraรงรฃo remota do Steam mantรฉm-se fechada. Desinstalar o Decky Loader? Remove o carregador. Os seus plugins e definiรงรตes sรฃo mantidos. Cliente diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 1e291f316b..47b370a046 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -332,7 +332,6 @@ Inicializaรงรฃo Abrir ao iniciar Inicia esta sessรฃo quando o DroidDeck รฉ aberto. - Decky Procurando versรตesโ€ฆ Pronto para instalar %1$s. Nenhuma versรฃo compatรญvel encontrada. Tente novamente mais tarde. @@ -341,14 +340,10 @@ Atualizado ยท %1$s Loader Instalar a mais recente - Canal de atualizaรงรฃo - Quais versรตes do Decky Loader instalar. O atualizador do prรณprio Decky usa o mesmo canal. Estรกvel Prรฉ-lanรงamento Testes Nรฃo foi possรญvel salvar o canal de atualizaรงรฃo do Decky - Inicia com a Steam. Enquanto estiver ativado, outros apps neste dispositivo podem conseguir controlar a Steam. - Desativado. A porta de depuraรงรฃo remota da Steam fica fechada. Desinstalar o Decky Loader? Remove o loader. Seus plugins e configuraรงรตes sรฃo mantidos. Cliente diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index f5868d56e5..69a16f1cf2 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -332,7 +332,6 @@ Pornire Deschide la pornire Porneศ™te aceastฤƒ sesiune cรขnd se lanseazฤƒ DroidDeck. - Decky Se verificฤƒ versiunileโ€ฆ Pregฤƒtit pentru instalarea %1$s. Nu s-a gฤƒsit o versiune compatibilฤƒ. รŽncearcฤƒ din nou mai tรขrziu. @@ -341,14 +340,10 @@ Actualizat ยท %1$s Loader Instaleazฤƒ cea mai recentฤƒ versiune - Canal de actualizare - Ce versiuni Decky Loader se instaleazฤƒ. Actualizatorul propriu al Decky foloseศ™te acelaศ™i canal. Stabil Pre-lansare Testare Canalul de actualizare Decky nu a putut fi salvat - Porneศ™te odatฤƒ cu Steam. Cรขt timp este activ, alte aplicaศ›ii de pe acest dispozitiv pot fi capabile sฤƒ controleze Steam. - Dezactivat. Portul de depanare la distanศ›ฤƒ al Steam rฤƒmรขne รฎnchis. Dezinstalezi Decky Loader? Eliminฤƒ loader-ul. Pluginurile ศ™i setฤƒrile tale sunt pฤƒstrate. Client diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index da7e65b3f6..e45c8af9a0 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -332,7 +332,6 @@ ะ—ะฐะฟัƒัะบ ะžั‚ะบั€ั‹ะฒะฐั‚ัŒ ะฟั€ะธ ะทะฐะฟัƒัะบะต ะ—ะฐะฟัƒัะบะฐะตั‚ ัั‚ะพั‚ ัะตะฐะฝั ะฟั€ะธ ะทะฐะฟัƒัะบะต DroidDeck. - Decky ะŸั€ะพะฒะตั€ะบะฐ ะฒั‹ะฟัƒัะบะพะฒโ€ฆ ะ“ะพั‚ะพะฒะพ ะบ ัƒัั‚ะฐะฝะพะฒะบะต %1$s. ะกะพะฒะผะตัั‚ะธะผะฐั ะฒะตั€ัะธั ะฝะต ะฝะฐะนะดะตะฝะฐ. ะŸะพะฒั‚ะพั€ะธั‚ะต ะฟะพะฟั‹ั‚ะบัƒ ะฟะพะทะถะต. @@ -341,14 +340,10 @@ ะะบั‚ัƒะฐะปัŒะฝะพ ยท %1$s ะ—ะฐะณั€ัƒะทั‡ะธะบ ะฃัั‚ะฐะฝะพะฒะธั‚ัŒ ะฟะพัะปะตะดะฝัŽัŽ - ะšะฐะฝะฐะป ะพะฑะฝะพะฒะปะตะฝะธะน - ะšะฐะบะธะต ะฒั‹ะฟัƒัะบะธ Decky Loader ัƒัั‚ะฐะฝะฐะฒะปะธะฒะฐั‚ัŒ. ะ’ัั‚ั€ะพะตะฝะฝะพะต ัั€ะตะดัั‚ะฒะพ ะพะฑะฝะพะฒะปะตะฝะธั Decky ะธัะฟะพะปัŒะทัƒะตั‚ ั‚ะพั‚ ะถะต ะบะฐะฝะฐะป. ะกั‚ะฐะฑะธะปัŒะฝั‹ะน ะŸั€ะตะดะฒะฐั€ะธั‚ะตะปัŒะฝั‹ะน ะขะตัั‚ะพะฒั‹ะน ะะต ัƒะดะฐะปะพััŒ ัะพั…ั€ะฐะฝะธั‚ัŒ ะบะฐะฝะฐะป ะพะฑะฝะพะฒะปะตะฝะธะน Decky - ะ—ะฐะฟัƒัะบะฐะตั‚ัั ะฒะผะตัั‚ะต ัะพ Steam. ะŸะพะบะฐ ะฒะบะปัŽั‡ะตะฝะพ, ะดั€ัƒะณะธะต ะฟั€ะธะปะพะถะตะฝะธั ะฝะฐ ัั‚ะพะผ ัƒัั‚ั€ะพะนัั‚ะฒะต ะผะพะณัƒั‚ ัƒะฟั€ะฐะฒะปัั‚ัŒ Steam. - ะ’ั‹ะบะป. ะŸะพั€ั‚ ัƒะดะฐะปะตะฝะฝะพะน ะพั‚ะปะฐะดะบะธ Steam ะพัั‚ะฐะตั‚ัั ะทะฐะบั€ั‹ั‚ั‹ะผ. ะฃะดะฐะปะธั‚ัŒ Decky Loader? ะฃะดะฐะปัะตั‚ ะทะฐะณั€ัƒะทั‡ะธะบ. ะ’ะฐัˆะธ ะฟะปะฐะณะธะฝั‹ ะธ ะฝะฐัั‚ั€ะพะนะบะธ ัะพั…ั€ะฐะฝัั‚ัั. ะšะปะธะตะฝั‚ diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 58be1afa71..afa62b8e4a 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -332,7 +332,6 @@ Uppstart ร–ppna vid start Startar den hรคr sessionen nรคr DroidDeck startar. - Decky Sรถker efter utgรฅvorโ€ฆ Redo att installera %1$s. Inget kompatibelt bygge hittades. Fรถrsรถk igen senare. @@ -341,14 +340,10 @@ Senaste versionen ยท %1$s Loader Installera senaste - Uppdateringskanal - Vilka Decky Loader-utgรฅvor som installeras. Deckys egen uppdaterare anvรคnder samma kanal. Stabil Fรถrhandsversion Test Det gick inte att spara Deckys uppdateringskanal - Startar med Steam. Medan det รคr pรฅ kan andra appar pรฅ enheten eventuellt styra Steam. - Av. Steams fjรคrrfelsรถkningsport fรถrblir stรคngd. Avinstallera Decky Loader? Tar bort inlรคsaren. Dina tillรคgg och instรคllningar behรฅlls. Klient diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index d8ec6f41e1..14a813ab5b 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -332,7 +332,6 @@ เธเธฒเธฃเน€เธฃเธดเนˆเธกเธ—เธณเธ‡เธฒเธ™ เน€เธ›เธดเธ”เน€เธกเธทเนˆเธญเน€เธฃเธดเนˆเธกเธ•เน‰เธ™ เน€เธฃเธดเนˆเธกเน€เธ‹เธชเธŠเธฑเธ™เธ™เธตเน‰เน€เธกเธทเนˆเธญเน€เธ›เธดเธ” DroidDeck - Decky เธเธณเธฅเธฑเธ‡เธ„เน‰เธ™เธซเธฒเธฃเธธเนˆเธ™เธ—เธตเนˆเน€เธœเธขเนเธžเธฃเนˆโ€ฆ เธžเธฃเน‰เธญเธกเธ•เธดเธ”เธ•เธฑเน‰เธ‡ %1$s เน„เธกเนˆเธžเธšเธšเธดเธฅเธ”เนŒเธ—เธตเนˆเน€เธ‚เน‰เธฒเธเธฑเธ™เน„เธ”เน‰ เธฅเธญเธ‡เนƒเธซเธกเนˆเธญเธตเธเธ„เธฃเธฑเน‰เธ‡เนƒเธ™เธซเธฅเธฑเธ‡ @@ -341,14 +340,10 @@ เน€เธ›เน‡เธ™เธฃเธธเนˆเธ™เธฅเนˆเธฒเธชเธธเธ”เนเธฅเน‰เธง ยท %1$s เธ•เธฑเธงเน‚เธซเธฅเธ” เธ•เธดเธ”เธ•เธฑเน‰เธ‡เธฃเธธเนˆเธ™เธฅเนˆเธฒเธชเธธเธ” - เธŠเนˆเธญเธ‡เธ—เธฒเธ‡เธญเธฑเธ›เน€เธ”เธ• - เธฃเธธเนˆเธ™เธ‚เธญเธ‡ Decky Loader เธ—เธตเนˆเธˆเธฐเธ•เธดเธ”เธ•เธฑเน‰เธ‡ เธ•เธฑเธงเธญเธฑเธ›เน€เธ”เธ•เธ‚เธญเธ‡ Decky เน€เธญเธ‡เธเน‡เนƒเธŠเน‰เธŠเนˆเธญเธ‡เธ—เธฒเธ‡เน€เธ”เธตเธขเธงเธเธฑเธ™ เน€เธชเธ–เธตเธขเธฃ เธเนˆเธญเธ™เน€เธ›เธดเธ”เธ•เธฑเธง เธ—เธ”เธชเธญเธš เธšเธฑเธ™เธ—เธถเธเธŠเนˆเธญเธ‡เธ—เธฒเธ‡เธญเธฑเธ›เน€เธ”เธ•เธ‚เธญเธ‡ Decky เน„เธกเนˆเน„เธ”เน‰ - เน€เธฃเธดเนˆเธกเธžเธฃเน‰เธญเธกเธเธฑเธš Steam เน€เธกเธทเนˆเธญเน€เธ›เธดเธ”เนƒเธŠเน‰เธ‡เธฒเธ™ เนเธญเธ›เธญเธทเนˆเธ™เธšเธ™เธญเธธเธ›เธเธฃเธ“เนŒเธ™เธตเน‰เธญเธฒเธˆเธชเธฒเธกเธฒเธฃเธ–เธ„เธงเธšเธ„เธธเธก Steam เน„เธ”เน‰ - เธ›เธดเธ”เธญเธขเธนเนˆ เธžเธญเธฃเนŒเธ•เธ”เธตเธšเธฑเธเธฃเธฐเธขเธฐเน„เธเธฅเธ‚เธญเธ‡ Steam เธขเธฑเธ‡เธ„เธ‡เธ›เธดเธ”เธญเธขเธนเนˆ เธ–เธญเธ™เธเธฒเธฃเธ•เธดเธ”เธ•เธฑเน‰เธ‡ Decky Loader? เธฅเธšเธ•เธฑเธงเน‚เธซเธฅเธ”เธญเธญเธ เธžเธฅเธฑเธเธญเธดเธ™เนเธฅเธฐเธเธฒเธฃเธ•เธฑเน‰เธ‡เธ„เนˆเธฒเธ‚เธญเธ‡เธ„เธธเธ“เธˆเธฐเธขเธฑเธ‡เธ„เธ‡เธญเธขเธนเนˆ เน„เธ„เธฅเน€เธญเธ™เธ•เนŒ diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 6bec3f37b5..9e67af3366 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -332,7 +332,6 @@ BaลŸlangฤฑรง AรงฤฑlฤฑลŸta baลŸlat DroidDeck aรงฤฑldฤฑฤŸฤฑnda bu oturumu baลŸlatฤฑr. - Decky Sรผrรผmler kontrol ediliyorโ€ฆ %1$s yรผklenmeye hazฤฑr. Uyumlu derleme bulunamadฤฑ. Daha sonra tekrar deneyin. @@ -341,14 +340,10 @@ Gรผncel ยท %1$s Yรผkleyici En yenisini yรผkle - Gรผncelleme kanalฤฑ - Hangi Decky Loader sรผrรผmlerinin yรผkleneceฤŸi. Decky\'nin kendi gรผncelleyicisi de aynฤฑ kanalฤฑ kullanฤฑr. Kararlฤฑ ร–n sรผrรผm Test Decky gรผncelleme kanalฤฑ kaydedilemedi - Steam ile baลŸlar. Aรงฤฑkken bu cihazdaki diฤŸer uygulamalar Steam\'i kontrol edebilir. - Kapalฤฑ. Steam\'in uzaktan hata ayฤฑklama baฤŸlantฤฑ noktasฤฑ kapalฤฑ kalฤฑr. Decky Loader kaldฤฑrฤฑlsฤฑn mฤฑ? Yรผkleyiciyi kaldฤฑrฤฑr. Eklentileriniz ve ayarlarฤฑnฤฑz korunur. ฤฐstemci diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 472a1d8050..8609b09b5d 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -332,7 +332,6 @@ ะ—ะฐะฟัƒัะบ ะ’ั–ะดะบั€ะธะฒะฐั‚ะธ ะฟั–ะด ั‡ะฐั ะทะฐะฟัƒัะบัƒ ะ—ะฐะฟัƒัะบะฐั” ั†ะตะน ัะตะฐะฝั ะฟั–ะด ั‡ะฐั ะทะฐะฟัƒัะบัƒ DroidDeck. - Decky ะŸะพัˆัƒะบ ะฒะธะฟัƒัะบั–ะฒโ€ฆ ะœะพะถะฝะฐ ะฒัั‚ะฐะฝะพะฒะธั‚ะธ %1$s. ะกัƒะผั–ัะฝัƒ ะทะฑั–ั€ะบัƒ ะฝะต ะทะฝะฐะนะดะตะฝะพ. ะกะฟั€ะพะฑัƒะนั‚ะต ะฟั–ะทะฝั–ัˆะต. @@ -341,14 +340,10 @@ ะะบั‚ัƒะฐะปัŒะฝะฐ ะฒะตั€ัั–ั ยท %1$s ะ—ะฐะฒะฐะฝั‚ะฐะถัƒะฒะฐั‡ ะฃัั‚ะฐะฝะพะฒะธั‚ะธ ะพัั‚ะฐะฝะฝัŽ ะฒะตั€ัั–ัŽ - ะšะฐะฝะฐะป ะพะฝะพะฒะปะตะฝัŒ - ะฏะบั– ะฒะธะฟัƒัะบะธ Decky Loader ะฒัั‚ะฐะฝะพะฒะปัŽะฒะฐั‚ะธ. ะ’ะปะฐัะฝะธะน ะทะฐัั–ะฑ ะพะฝะพะฒะปะตะฝะฝั Decky ะฒะธะบะพั€ะธัั‚ะพะฒัƒั” ั‚ะพะน ัะฐะผะธะน ะบะฐะฝะฐะป. ะกั‚ะฐะฑั–ะปัŒะฝะธะน ะŸะพะฟะตั€ะตะดะฝั–ะน ะขะตัั‚ะพะฒะธะน ะะต ะฒะดะฐะปะพัั ะทะฑะตั€ะตะณั‚ะธ ะบะฐะฝะฐะป ะพะฝะพะฒะปะตะฝัŒ Decky - ะ—ะฐะฟัƒัะบะฐั”ั‚ัŒัั ั€ะฐะทะพะผ ะทั– Steam. ะŸะพะบะธ ะนะพะณะพ ะฒะฒั–ะผะบะฝะตะฝะพ, ั–ะฝัˆั– ะดะพะดะฐั‚ะบะธ ะฝะฐ ั†ัŒะพะผัƒ ะฟั€ะธัั‚ั€ะพั— ะผะพะถัƒั‚ัŒ ะบะตั€ัƒะฒะฐั‚ะธ Steam. - ะ’ะธะผะบะฝะตะฝะพ. ะŸะพั€ั‚ ะฒั–ะดะดะฐะปะตะฝะพะณะพ ะฝะฐะปะฐะณะพะดะถะตะฝะฝั Steam ะทะฐะปะธัˆะฐั”ั‚ัŒัั ะทะฐะบั€ะธั‚ะธะผ. ะ’ะธะดะฐะปะธั‚ะธ Decky Loader? ะ’ะธะดะฐะปัั” ะทะฐะฒะฐะฝั‚ะฐะถัƒะฒะฐั‡. ะ’ะฐัˆั– ะฟะปะฐะณั–ะฝะธ ะน ะฝะฐะปะฐัˆั‚ัƒะฒะฐะฝะฝั ะทะฑะตั€ั–ะณะฐัŽั‚ัŒัั. ะšะปั–ั”ะฝั‚ diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index fbf6432863..fd23d10b90 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -332,7 +332,6 @@ KhแปŸi ฤ‘แป™ng MแปŸ khi khแปŸi chแบกy Bแบฏt ฤ‘แบงu phiรชn nร y khi DroidDeck khแปŸi chแบกy. - Decky ฤang kiแปƒm tra bแบฃn phรกt hร nhโ€ฆ Sแบตn sร ng cร i %1$s. Khรดng tรฌm thแบฅy bแบฃn build tฦฐฦกng thรญch. Hรฃy thแปญ lแบกi sau. @@ -341,14 +340,10 @@ ฤรฃ mแป›i nhแบฅt ยท %1$s Loader Cร i bแบฃn mแป›i nhแบฅt - Kรชnh cแบญp nhแบญt - Cรกc bแบฃn phรกt hร nh Decky Loader sแบฝ cร i. Trรฌnh cแบญp nhแบญt riรชng cแปงa Decky dรนng cรนng kรชnh nร y. แป”n ฤ‘แป‹nh Tiแปn phรกt hร nh Thแปญ nghiแป‡m Khรดng thแปƒ lฦฐu kรชnh cแบญp nhแบญt Decky - KhแปŸi ฤ‘แป™ng cรนng Steam. Khi ฤ‘ang bแบญt, cรกc แปฉng dแปฅng khรกc trรชn thiแบฟt bแป‹ nร y cรณ thแปƒ ฤ‘iแปu khiแปƒn ฤ‘ฦฐแปฃc Steam. - Tแบฏt. Cแป•ng gแปก lแป—i tแปซ xa cแปงa Steam luรดn ฤ‘รณng. Gแปก cร i ฤ‘แบทt Decky Loader? Gแปก bแป loader. Plugin vร  thiแบฟt lแบญp cแปงa bแบกn ฤ‘ฦฐแปฃc giแปฏ lแบกi. Client diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 4446a1fb81..aa46013f4a 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -332,7 +332,6 @@ ๅฏๅŠจ ๅฏๅŠจๆ—ถๆ‰“ๅผ€ DroidDeck ๅฏๅŠจๆ—ถๅผ€ๅง‹ๆญคไผš่ฏใ€‚ - Decky ๆญฃๅœจๆฃ€ๆŸฅๅ‘ๅธƒ็‰ˆๆœฌโ€ฆ ๅทฒๅฐฑ็ปช๏ผŒๅฏๅฎ‰่ฃ… %1$sใ€‚ ๆœชๆ‰พๅˆฐๅ…ผๅฎน็š„ๆž„ๅปบใ€‚่ฏท็จๅŽ้‡่ฏ•ใ€‚ @@ -341,14 +340,10 @@ ๅทฒๆ˜ฏๆœ€ๆ–ฐ ยท %1$s ๅŠ ่ฝฝๅ™จ ๅฎ‰่ฃ…ๆœ€ๆ–ฐ็‰ˆ - ๆ›ดๆ–ฐ้€š้“ - ่ฆๅฎ‰่ฃ…ๅ“ช็ง Decky Loader ็‰ˆๆœฌใ€‚Decky ่‡ชๅธฆ็š„ๆ›ดๆ–ฐ็จ‹ๅบไนŸไฝฟ็”จ็›ธๅŒ็š„้€š้“ใ€‚ ็จณๅฎš็‰ˆ ้ข„ๅ‘ๅธƒ็‰ˆ ๆต‹่ฏ•็‰ˆ ๆ— ๆณ•ไฟๅญ˜ Decky ๆ›ดๆ–ฐ้€š้“ - ้š Steam ๅฏๅŠจใ€‚ๅผ€ๅฏๆœŸ้—ด๏ผŒๆœฌ่ฎพๅค‡ไธŠ็š„ๅ…ถไป–ๅบ”็”จๅฏ่ƒฝๅฏไปฅๆŽงๅˆถ Steamใ€‚ - ๅทฒๅ…ณ้—ญใ€‚Steam ็š„่ฟœ็จ‹่ฐƒ่ฏ•็ซฏๅฃไฟๆŒๅ…ณ้—ญใ€‚ ๅธ่ฝฝ Decky Loader๏ผŸ ็งป้™คๅŠ ่ฝฝๅ™จใ€‚ไฝ ็š„ๆ’ไปถๅ’Œ่ฎพ็ฝฎไผšไฟ็•™ใ€‚ ๅฎขๆˆท็ซฏ diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index daa483e57d..1bec44cc0a 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -332,7 +332,6 @@ ๅ•Ÿๅ‹• ๅ•Ÿๅ‹•ๆ™‚้–‹ๅ•Ÿ DroidDeck ๅ•Ÿๅ‹•ๆ™‚้–‹ๅง‹ๆญคๅทฅไฝœ้šŽๆฎตใ€‚ - Decky ๆญฃๅœจๆชขๆŸฅ็™ผไฝˆ็‰ˆๆœฌโ€ฆ ๅฏๅฎ‰่ฃ %1$sใ€‚ ๆ‰พไธๅˆฐๅ…ผๅฎน็š„็‰ˆๆœฌ๏ผŒ่ซ‹็จๅพŒๅ†่ฉฆใ€‚ @@ -341,14 +340,10 @@ ๅทฒๆ˜ฏๆœ€ๆ–ฐ ยท %1$s ่ผ‰ๅ…ฅๅ™จ ๅฎ‰่ฃๆœ€ๆ–ฐ็‰ˆๆœฌ - ๆ›ดๆ–ฐ้ ป้“ - ่ฆๅฎ‰่ฃๅ“ชไธ€็จฎ Decky Loader ็‰ˆๆœฌใ€‚Decky ๆœฌ่บซ็š„ๆ›ดๆ–ฐ็จ‹ๅผไนŸๆœƒไฝฟ็”จ็›ธๅŒ็š„้ ป้“ใ€‚ ็ฉฉๅฎš็‰ˆ ้ ็™ผไฝˆ็‰ˆ ๆธฌ่ฉฆ็‰ˆ ็„กๆณ•ๅ„ฒๅญ˜ Decky ๆ›ดๆ–ฐ้ ป้“ - ้šจ Steam ๅ•Ÿๅ‹•ใ€‚ๅ•Ÿ็”จๆ™‚๏ผŒๆญค่ฃ็ฝฎไธŠ็š„ๅ…ถไป–ๆ‡‰็”จ็จ‹ๅผๅฏ่ƒฝๅฏไปฅๆŽงๅˆถ Steamใ€‚ - ๅทฒ้—œ้–‰ใ€‚Steam ็š„้ ็ซฏๅต้Œฏ้€ฃๆŽฅๅŸ ไฟๆŒ้—œ้–‰ใ€‚ ่งฃ้™คๅฎ‰่ฃ Decky Loader๏ผŸ ็งป้™ค่ผ‰ๅ…ฅๅ™จ๏ผŒไฝ ็š„ๆ’ไปถๅ’Œ่จญๅฎšๆœƒไฟ็•™ใ€‚ ็”จๆˆถ็ซฏ diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 18805781c2..d484813b1e 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -332,7 +332,6 @@ ๅ•Ÿๅ‹• ๅ•Ÿๅ‹•ๆ™‚้–‹ๅ•Ÿ DroidDeck ๅ•Ÿๅ‹•ๆ™‚้–‹ๅง‹ๆญคๅทฅไฝœ้šŽๆฎตใ€‚ - Decky ๆญฃๅœจๆชขๆŸฅ็™ผ่กŒ็‰ˆๆœฌโ€ฆ ๅทฒๆบ–ๅ‚™ๅฅฝๅฎ‰่ฃ %1$sใ€‚ ๆœชๆ‰พๅˆฐ็›ธๅฎน็‰ˆๆœฌใ€‚่ซ‹็จๅพŒๅ†่ฉฆใ€‚ @@ -341,14 +340,10 @@ ๅทฒๆ˜ฏๆœ€ๆ–ฐ ยท %1$s ่ผ‰ๅ…ฅๅ™จ ๅฎ‰่ฃๆœ€ๆ–ฐ็‰ˆๆœฌ - ๆ›ดๆ–ฐ้ ป้“ - ่ฆๅฎ‰่ฃๅ“ชไธ€็จฎ Decky Loader ็‰ˆๆœฌใ€‚Decky ๆœฌ่บซ็š„ๆ›ดๆ–ฐ็จ‹ๅผไนŸๆœƒไฝฟ็”จ็›ธๅŒ็š„้ ป้“ใ€‚ ็ฉฉๅฎš็‰ˆ ้ ๅ…ˆ็™ผ่กŒ็‰ˆ ๆธฌ่ฉฆ็‰ˆ ็„กๆณ•ๅ„ฒๅญ˜ Decky ๆ›ดๆ–ฐ้ ป้“ - ้šจ Steam ๅ•Ÿๅ‹•ใ€‚ๅ•Ÿ็”จๅพŒ๏ผŒๆญค่ฃ็ฝฎไธŠ็š„ๅ…ถไป–ๆ‡‰็”จ็จ‹ๅผๅฏ่ƒฝๅฏไปฅๆŽงๅˆถ Steamใ€‚ - ้—œ้–‰ใ€‚Steam ็š„้ ็ซฏๅต้Œฏ้€ฃๆŽฅๅŸ ไฟๆŒ้—œ้–‰ใ€‚ ่งฃ้™คๅฎ‰่ฃ Decky Loader๏ผŸ ็งป้™ค่ผ‰ๅ…ฅๅ™จใ€‚ไฝ ็š„ๅค–ๆŽ›็จ‹ๅผๅ’Œ่จญๅฎšๆœƒไฟ็•™ใ€‚ ็”จๆˆถ็ซฏ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ad2bdfe362..3e52b58b21 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -362,7 +362,6 @@ Startup Open at launch Starts this session when DroidDeck launches. - Decky Checking for releasesโ€ฆ Ready to install %1$s. No compatible build found. Try again later. @@ -371,14 +370,10 @@ Up to date ยท %1$s Loader Install latest - Update Channel - Which Decky Loader releases to install. Decky\'s own updater uses the same channel. Stable Prerelease Testing Could not save the Decky update channel - Starts with Steam. While on, other apps on this device may be able to control Steam. - Off. Steam\'s remote debugging port stays closed. Uninstall Decky Loader? Removes the loader. Your plugins and settings are kept. Client @@ -4324,6 +4319,27 @@ In-game menu In-game menu preview ยท Back to close Tabs + Status + Enable + Release channel + Decky + Boot movies + Installed ยท %1$d + Store + From ZIP + No plugins installed. Browse the Store or install a ZIP. + Update to %1$s + Remove + Remove %1$s? + Deletes the plugin from Decky. Its settings are kept. + Plugin changes apply the next time Steam starts. + Search plugins + Could not reach the Decky plugin store + No plugins found + Show %1$d more + Downloading %1$sโ€ฆ + Could not download %1$s + Could not remove the plugin Storage Syncthing Download settings diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt new file mode 100644 index 0000000000..67bf7d8614 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/runtime/DeckyStoreTest.kt @@ -0,0 +1,47 @@ +package com.droiddeck.launcher.runtime + +import com.droiddeck.launcher.ui.deckyStoreMatches +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class) +@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class) +class DeckyStoreTest { + private val hash = "a".repeat(64) + private val listing = """[ + {"id":1,"name":"Alpha","author":"Ann","description":"Does alpha things","tags":["audio"],"image_url":"https://cdn.example/a.png", + "versions":[{"name":"2.0.0","hash":"$hash","downloads":10},{"name":"1.0.0","hash":"${"b".repeat(64)}","downloads":5}]}, + {"id":2,"name":"Beta","author":"Bob","description":"Themes","tags":["css"],"versions":[{"name":"1.0.0","hash":"${"c".repeat(64)}","downloads":100}]}, + {"id":3,"name":"NoVersions","author":"X","description":"","tags":[],"versions":[]}, + {"id":4,"name":"BadHash","author":"X","description":"","tags":[],"versions":[{"name":"1","hash":"nope","downloads":1}]} + ]""" + + @Test fun listingKeepsOnlyPluginsWithAUsableVersionAndSumsDownloads() { + val plugins = DeckyStore.parseListing(listing) + assertEquals(listOf("Alpha", "Beta"), plugins.map { it.name }) + assertEquals("2.0.0", plugins[0].latest?.name) + assertEquals(15L, plugins[0].downloads) + assertEquals("https://cdn.example/a.png", plugins[0].imageUrl) + assertEquals("", plugins[1].imageUrl) + } + + @Test fun searchMatchesNameAuthorDescriptionAndTagsAndSortsByDownloads() { + val plugins = DeckyStore.parseListing(listing) + assertEquals(listOf("Beta", "Alpha"), deckyStoreMatches(plugins, "").map { it.name }) + assertEquals(listOf("Alpha"), deckyStoreMatches(plugins, "ann audio").map { it.name }) + assertEquals(listOf("Beta"), deckyStoreMatches(plugins, "THEMES").map { it.name }) + assertTrue(deckyStoreMatches(plugins, "missing").isEmpty()) + } + + @Test fun anUpdateNeedsAKnownInstalledVersionThatDiffersFromTheLatest() { + val alpha = DeckyStore.parseListing(listing).first() + assertTrue(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "1.0.0"), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "2.0.0"), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", ""), alpha)) + assertFalse(DeckyStore.updateAvailable(DeckyStore.Installed("Alpha", "Alpha", "Ann", "1.0.0"), null)) + assertNull(DeckyStore.parseListing("[]").firstOrNull()) + } +} 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 1736382512..8e9fcad74a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -41,7 +41,7 @@ class NavTabsTest { @Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() { assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) - assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps")) assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent")) assertFalse(com.droiddeck.launcher.agent.AgentTab.shown) @@ -57,7 +57,7 @@ class NavTabsTest { @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { place("desktop", TabPlace.MORE) val s = state() - assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(s)) + assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) assertEquals(NavTabs.MORE, navigationKeys(s).last()) assertFalse("desktop" in navigationKeys(s)) } @@ -86,7 +86,7 @@ class NavTabsTest { NavTabs.load(ctx) val s = state() assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s)) - assertEquals(listOf("storage", "sync"), NavTabs.more(s)) + assertEquals(listOf("storage", "sync", "decky", "boot-movies"), NavTabs.more(s)) listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) } val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE) assertFalse(prefs.contains("gameStoresEnabled")) @@ -108,7 +108,7 @@ class NavTabsTest { assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "stores")) assertEquals(TabPlace.MORE, NavTabs.place(state(), "components")) assertEquals(TabPlace.BAR, NavTabs.place(state(), "downloads")) - assertEquals(listOf("components", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("components", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) } @Test fun movingSwapsWithTheNextVisibleTabAndPersists() { @@ -119,9 +119,9 @@ class NavTabsTest { } @Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() { - assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), + assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), NavTabs.arrange(listOf("updates", "steam"))) - assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "android-apps", "agent", "updates"), + assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent", "updates"), NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus"))) } @@ -130,7 +130,7 @@ class NavTabsTest { .putString("navTabOrder", "steam,games,soundtracks,stores,desktop,agent,components,android-apps,setup,updates") .putString("navTabShelved", "soundtracks").commit() NavTabs.load(ctx) - assertEquals(listOf("soundtracks", "storage", "sync"), NavTabs.more(state())) + assertEquals(listOf("soundtracks", "storage", "sync", "decky", "boot-movies"), NavTabs.more(state())) place("sync", TabPlace.BAR) NavTabs.load(ctx) assertTrue("sync" in navigationKeys(state())) diff --git a/docs/settings-map.md b/docs/settings-map.md index 6b13633780..bcef3a25c3 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -65,6 +65,8 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | --- | --- | --- | | Storage | Tabs โ€บ Storage | sd card, space, uninstall, disk | | Syncthing | Tabs โ€บ Syncthing | syncthing, saves | +| Decky | Tabs โ€บ Decky | plugins, plugin store, homebrew, loader | +| Boot movies | Tabs โ€บ Boot movies | startup movie, boot video, animation, steamdeckrepo | | Download speed tier | Tabs โ€บ Downloads | download, speed, bandwidth, slow | | Downloads at a time | Tabs โ€บ Downloads | download, parallel, queue, at once | | Tabs | Tabs โ€บ More | tabs, hide, reorder, agent, stores, edit tabs | From a305a91c66eb72c4b51cf65e34ea63d1e4737bd5 Mon Sep 17 00:00:00 2001 From: Dantalian Date: Mon, 23 Nov 2026 23:16:39 +0800 Subject: [PATCH 11/17] feat(files): add a plain text editor to the file manager (#2980) * feat(files): add a plain text editor to the file manager * fix(files): address CodeRabbit review on the text editor - compose the editor instead of the toolbar so EXIT can't bypass the unsaved-changes guard - read through a capped stream, keep undecodable files read-only, and preserve POSIX permissions via staging-file rename with no direct-write fallback - serialize saves, keep dirty consistent across concurrent edits, reset match index on text change, fix empty-state counter and read-only replace buttons - scroll match into view horizontally; ignore cursor-only edits for dirty - add tests for literal U+FFFD files and the capped reader * fix(files): treat rename failure as save error and follow symbolic links * test(files): assert the resolved save target without canonicalizing it --------- Co-authored-by: Dantalian --- app/src/main/AndroidManifest.xml | 1 + .../launcher/files/FileManagerItems.kt | 15 + .../launcher/files/FileManagerScreen.kt | 17 +- .../launcher/files/TextEditorScreen.kt | 726 ++++++++++++++++++ app/src/main/res/values/strings.xml | 17 + .../launcher/files/TextEditorLogicTest.kt | 143 ++++ 6 files changed, 918 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 30650081fc..55b75d36df 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -232,6 +232,7 @@ android:exported="false" android:screenOrientation="user" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" + android:windowSoftInputMode="adjustResize" android:theme="@style/AppTheme" /> Unit, onProperties: () -> Unit, onDismissMenu: () -> Unit, + onOpen: () -> Unit, ) { val isDir = file.isDirectory + if (!isDir) { + DropdownMenuItem( + text = { Text(stringResource(R.string.fm_edit_open)) }, + leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onOpen() }, + modifier = Modifier.focusGlide(), + ) + MenuItemDivider() + } DropdownMenuItem( text = { Text(stringResource(R.string.fm_select)) }, leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, @@ -180,6 +191,7 @@ internal fun FileItemRow( onCut: () -> Unit, onDelete: () -> Unit, onRename: () -> Unit, + onOpen: () -> Unit = {}, isFavorite: Boolean = false, onToggleFavorite: () -> Unit = {}, onProperties: () -> Unit = {}, @@ -291,6 +303,7 @@ internal fun FileItemRow( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, @@ -517,6 +530,7 @@ internal fun FileGridTile( isFavorite: Boolean = false, onSelect: () -> Unit = {}, onRename: () -> Unit = {}, + onOpen: () -> Unit = {}, onCopy: () -> Unit = {}, onCut: () -> Unit = {}, onDelete: () -> Unit = {}, @@ -605,6 +619,7 @@ internal fun FileGridTile( file = file, isFavorite = isFavorite, onSelect = onSelect, + onOpen = onOpen, onRename = onRename, onCopy = onCopy, onCut = onCut, diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 9945083226..7025769d87 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -191,6 +191,7 @@ fun FileManagerScreen( var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) } var showNewFolderDialog by remember { mutableStateOf(false) } var renameTarget by remember { mutableStateOf(null) } + var editingTarget by remember { mutableStateOf(null) } var propertiesTarget by remember { mutableStateOf(null) } var isOperationRunning by remember { mutableStateOf(false) } var operationLabel by remember { mutableStateOf("") } @@ -294,7 +295,7 @@ fun FileManagerScreen( if (isOperationActive()) pendingNavigation = action else navigate(action) } - BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) { + BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) { requestNavigation(FileManagerNavigation.BACK) } @@ -696,6 +697,14 @@ fun FileManagerScreen( val compactToolbar = LocalConfiguration.current.screenWidthDp < 600 Column(modifier = Modifier.fillMaxSize()) { + editingTarget?.let { target -> + TextEditorScreen( + file = target, + onExit = { editingTarget = null }, + modifier = Modifier.fillMaxSize(), + ) + return@Column + } if (pickMode && !pickerTitle.isNullOrEmpty()) { Text( text = pickerTitle, @@ -1194,6 +1203,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1205,6 +1216,7 @@ fun FileManagerScreen( selectedPaths = selectedPaths + file.absolutePath showMenuFor = null }, + onOpen = { editingTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null }, onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, @@ -1273,6 +1285,8 @@ fun FileManagerScreen( pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() onPick?.invoke(file) } + } else { + editingTarget = file } }, onMenu = { showMenuFor = file }, @@ -1286,6 +1300,7 @@ fun FileManagerScreen( onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, onDelete = { selectedEntry = file; showMenuFor = null }, + onOpen = { editingTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null }, isFavorite = isFav, onToggleFavorite = { diff --git a/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt new file mode 100644 index 0000000000..2d9c0a3fea --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/files/TextEditorScreen.kt @@ -0,0 +1,726 @@ +package com.droiddeck.launcher.files + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +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.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Save +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.rememberTextMeasurer +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 com.droiddeck.launcher.R +import com.droiddeck.launcher.ui.focusGlide +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.InputStream +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.Charset +import java.nio.charset.CodingErrorAction +import java.nio.file.Files +import kotlin.math.roundToInt + +internal const val EDITOR_FONT_SIZE_SP = 13 +internal const val EDITOR_LINE_HEIGHT_SP = 18 +internal const val EDITOR_TAB_WIDTH = 4 +internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024 +internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024 + +internal enum class EditorCharset(val label: String, private val charsetName: String) { + UTF8("UTF-8", "UTF-8"), + GB18030("GB18030", "GB18030"), + ; + + val charset: Charset get() = Charset.forName(charsetName) +} + +internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY } + +internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE } + +internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean) + +internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean { + val limit = minOf(bytes.size, sample) + for (i in 0 until limit) if (bytes[i].toInt() == 0) return true + return false +} + +private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try { + charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString() +} catch (e: CharacterCodingException) { + null +} + +internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText { + strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) } + strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) } + return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true) +} + +internal fun resolveEditorSaveTarget(file: File): File { + val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false) + if (!isLink) return file + // rename(2) replaces the link itself, so stage next to and rename onto the real target + return runCatching { file.canonicalFile }.getOrDefault(file) +} + +internal fun readCapped(input: InputStream, limit: Long): ByteArray? { + val out = ByteArrayOutputStream() + val buffer = ByteArray(64 * 1024) + var total = 0L + while (true) { + val n = input.read(buffer) + if (n < 0) return out.toByteArray() + total += n + if (total > limit) return null + out.write(buffer, 0, n) + } +} + +internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String { + if (text.indexOf('\t') < 0) return text + val out = StringBuilder(text.length) + var column = 0 + for (c in text) { + when (c) { + '\n' -> { + out.append(c) + column = 0 + } + '\t' -> { + val pad = width - (column % width) + repeat(pad) { out.append(' ') } + column += pad + } + else -> { + out.append(c) + column++ + } + } + } + return out.toString() +} + +internal fun lineCountOf(text: String): Int { + var lines = 1 + for (i in text.indices) if (text[i] == '\n') lines++ + return lines +} + +internal fun lineIndexOfOffset(text: String, offset: Int): Int { + val end = offset.coerceIn(0, text.length) + var line = 0 + var i = 0 + while (i < end) { + if (text[i] == '\n') line++ + i++ + } + return line +} + +internal fun columnOfOffset(text: String, offset: Int): Int { + val end = offset.coerceIn(0, text.length) + var start = end + while (start > 0 && text[start - 1] != '\n') start-- + return end - start + 1 +} + +internal fun findEditorMatches( + text: String, + query: String, + matchCase: Boolean = false, + limit: Int = 10000, +): List { + if (query.isEmpty()) return emptyList() + val out = ArrayList() + var at = 0 + while (out.size < limit) { + val found = text.indexOf(query, at, ignoreCase = !matchCase) + if (found < 0) break + out.add(found until found + query.length) + at = found + query.length + } + return out +} + +internal fun replaceEditorMatches(text: String, matches: List, replacement: String): String { + if (matches.isEmpty()) return text + val out = StringBuilder(text.length) + var cursor = 0 + for (m in matches) { + if (m.first < cursor || m.last >= text.length) continue + out.append(text, cursor, m.first).append(replacement) + cursor = m.last + 1 + } + out.append(text, cursor, text.length) + return out.toString() +} + +@Composable +internal fun TextEditorScreen( + file: File, + onExit: () -> Unit, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val density = LocalDensity.current + + var text by remember { mutableStateOf("") } + var selection by remember { mutableStateOf(TextRange.Zero) } + var composing by remember { mutableStateOf(null) } + var loadState by remember { mutableStateOf(EditorLoadState.LOADING) } + var lock by remember { mutableStateOf(EditorLock.NONE) } + var charset by remember { mutableStateOf(EditorCharset.UTF8) } + var dirty by remember { mutableStateOf(false) } + var saving by remember { mutableStateOf(false) } + var showDiscard by remember { mutableStateOf(false) } + var showSearch by remember { mutableStateOf(false) } + var query by remember { mutableStateOf("") } + var replacement by remember { mutableStateOf("") } + var matchCase by remember { mutableStateOf(false) } + var matchIndex by remember { mutableIntStateOf(0) } + + val scrollState = rememberScrollState() + val textHorizontalState = rememberScrollState() + var viewportHeight by remember { mutableIntStateOf(0) } + var viewportWidth by remember { mutableIntStateOf(0) } + + val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() } + val lineHeightPx = with(density) { lineHeightDp.toPx() } + val totalLines = remember(text) { lineCountOf(text) } + val cursorLine = lineIndexOfOffset(text, selection.end) + val cursorColumn = columnOfOffset(text, selection.end) + val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) } + val readOnly = lock != EditorLock.NONE + val bodyStyle = TextStyle( + fontFamily = FontFamily.Monospace, + fontSize = EDITOR_FONT_SIZE_SP.sp, + lineHeight = EDITOR_LINE_HEIGHT_SP.sp, + color = MaterialTheme.colorScheme.onBackground, + ) + val textMeasurer = rememberTextMeasurer() + val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() } + + LaunchedEffect(file) { + loadState = EditorLoadState.LOADING + val size = withContext(Dispatchers.IO) { file.length() } + if (size > EDITOR_MAX_OPEN_BYTES) { + loadState = EditorLoadState.TOO_LARGE + return@LaunchedEffect + } + val read = withContext(Dispatchers.IO) { + runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } } + } + val bytes = read.getOrNull() + if (bytes == null) { + loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE + return@LaunchedEffect + } + val decoded = decodeEditorText(bytes) + text = expandEditorTabs(decoded.text) + charset = decoded.charset + lock = when { + editorIsBinary(bytes) -> EditorLock.BINARY + decoded.lossy -> EditorLock.LOSSY + bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE + !file.canWrite() -> EditorLock.PERMISSION + else -> EditorLock.NONE + } + selection = TextRange.Zero + loadState = EditorLoadState.READY + } + + suspend fun revealLine(line: Int) { + val current = scrollState.value + val top = line * lineHeightPx + val target = when { + top < current -> top + top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight + else -> return + } + val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue) + if (clamped != current) scrollState.scrollTo(clamped) + } + + LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) { + if (loadState != EditorLoadState.READY) return@LaunchedEffect + revealLine(lineIndexOfOffset(text, selection.end)) + if (viewportWidth > 0 && charWidthPx > 0) { + val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx + val current = textHorizontalState.value + val target = when { + x < current -> x + x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth + else -> null + } + if (target != null) { + val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue) + if (clamped != current) textHorizontalState.scrollTo(clamped) + } + } + } + + LaunchedEffect(query, matchCase) { + if (query.isEmpty()) return@LaunchedEffect + matchIndex = 0 + val first = matches.firstOrNull() ?: return@LaunchedEffect + selection = TextRange(first.first, first.last + 1) + composing = TextRange.Zero + } + + LaunchedEffect(text) { matchIndex = 0 } + + fun gotoMatch(delta: Int) { + if (matches.isEmpty()) return + matchIndex = Math.floorMod(matchIndex + delta, matches.size) + val m = matches[matchIndex] + selection = TextRange(m.first, m.last + 1) + composing = TextRange.Zero + } + + fun replaceCurrent() { + if (readOnly) return + val m = matches.getOrNull(matchIndex) ?: return + text = text.replaceRange(m.first, m.last + 1, replacement) + dirty = true + matchIndex = 0 + selection = TextRange(m.first + replacement.length) + composing = TextRange.Zero + } + + fun replaceAll() { + if (readOnly || matches.isEmpty()) return + val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE) + text = replaceEditorMatches(text, all, replacement) + dirty = true + matchIndex = 0 + selection = TextRange.Zero + composing = TextRange.Zero + } + + fun save() { + if (readOnly || saving || loadState != EditorLoadState.READY) return + val snapshot = text + val bytes = snapshot.toByteArray(charset.charset) + saving = true + scope.launch { + val ok = withContext(Dispatchers.IO) { + runCatching { + val target = resolveEditorSaveTarget(file) + val parent = target.parentFile + if (parent == null) { + target.writeBytes(bytes) + } else { + val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent) + try { + tmp.writeBytes(bytes) + runCatching { + Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath())) + } + if (!tmp.renameTo(target)) error("rename to ${target.name} failed") + } finally { + tmp.delete() + } + } + }.isSuccess + } + saving = false + if (ok) { + if (text == snapshot) dirty = false + } else { + Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show() + } + } + } + + fun tryExit() { + if (saving) return + if (dirty && !readOnly) showDiscard = true else onExit() + } + + BackHandler { tryExit() } + + if (showDiscard) { + OutlinedAlertDialog( + onDismissRequest = { showDiscard = false }, + title = { Text(stringResource(R.string.fm_edit_discard_title)) }, + text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) }, + confirmButton = { + TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.fm_edit_discard)) + } + }, + dismissButton = { + TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) { + Text(stringResource(R.string.common_cancel)) + } + }, + ) + } + + Column( + modifier = modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 8.dp, vertical = 6.dp), + ) { + IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.ArrowBack, + stringResource(R.string.fm_back), + tint = MaterialTheme.colorScheme.primary, + ) + } + Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) { + Text( + text = file.name, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (dirty) { + Text( + text = "\u2022 " + stringResource(R.string.fm_edit_modified), + color = MaterialTheme.colorScheme.primary, + fontSize = 11.sp, + maxLines = 1, + ) + } + } + if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) { + Text( + text = stringResource( + if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 10.sp, + maxLines = 1, + modifier = Modifier + .background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + Spacer(Modifier.width(6.dp)) + } + IconButton( + onClick = { showSearch = !showSearch }, + enabled = loadState == EditorLoadState.READY, + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.Search, + stringResource(R.string.fm_edit_find), + tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton( + onClick = { save() }, + enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving, + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.Save, + stringResource(R.string.fm_edit_save), + tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + if (showSearch && loadState == EditorLoadState.READY) { + Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp), + ) { + OutlinedTextField( + value = query, + onValueChange = { query = it; matchIndex = 0 }, + singleLine = true, + placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) }, + textStyle = MaterialTheme.typography.bodySmall, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }), + modifier = Modifier.weight(1f).focusGlide(), + ) + Text( + text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp), + ) + IconButton( + onClick = { gotoMatch(-1) }, + enabled = matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.KeyboardArrowUp, + stringResource(R.string.fm_edit_find_previous), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + IconButton( + onClick = { gotoMatch(1) }, + enabled = matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Icon( + Icons.Filled.KeyboardArrowDown, + stringResource(R.string.fm_edit_find_next), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) { + Text( + text = "Aa", + color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 13.sp, + ) + } + IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.Close, + stringResource(R.string.common_cancel), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + } + } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp), + ) { + OutlinedTextField( + value = replacement, + onValueChange = { replacement = it }, + singleLine = true, + placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) }, + textStyle = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f).focusGlide(), + ) + TextButton( + onClick = { replaceCurrent() }, + enabled = !readOnly && matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) + } + TextButton( + onClick = { replaceAll() }, + enabled = !readOnly && matches.isNotEmpty(), + modifier = Modifier.focusGlide(CircleShape), + ) { + Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp) + } + } + } + } + + Box( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + .onSizeChanged { viewportHeight = it.height }, + ) { + when (loadState) { + EditorLoadState.LOADING -> CircularProgressIndicator( + modifier = Modifier.align(Alignment.Center), + ) + + EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.align(Alignment.Center).padding(24.dp), + ) { + Text( + text = stringResource( + if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large + else R.string.fm_edit_open_failed, + if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length()) + else file.name, + ), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 14.sp, + textAlign = TextAlign.Center, + ) + } + + EditorLoadState.READY -> Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(scrollState), + ) { + Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) { + LineNumbers( + scrollState = scrollState, + viewportHeight = viewportHeight, + lineHeightDp = lineHeightDp, + lineHeightPx = lineHeightPx, + totalLines = totalLines, + cursorLine = cursorLine, + style = bodyStyle, + mutedColor = MaterialTheme.colorScheme.onSurfaceVariant, + cursorColor = MaterialTheme.colorScheme.primary, + ) + Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) { + BasicTextField( + value = TextFieldValue(text = text, selection = selection, composition = composing), + onValueChange = { next -> + val changed = next.text != text + text = next.text + selection = next.selection + composing = next.composition + if (changed) dirty = true + }, + readOnly = readOnly, + textStyle = bodyStyle, + cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Text, + capitalization = KeyboardCapitalization.None, + ), + modifier = Modifier.fillMaxHeight().focusGlide(), + ) + } + } + } + } + } + + if (loadState == EditorLoadState.READY) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), + ) { + Text( + text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + ) + Spacer(Modifier.weight(1f)) + Text( + text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + ) + } + } + } +} + +@Composable +private fun LineNumbers( + scrollState: ScrollState, + viewportHeight: Int, + lineHeightDp: Dp, + lineHeightPx: Float, + totalLines: Int, + cursorLine: Int, + style: TextStyle, + mutedColor: Color, + cursorColor: Color, + modifier: Modifier = Modifier, +) { + val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1) + val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx) + .toInt() + .coerceIn(firstLine, totalLines - 1) + Column( + horizontalAlignment = Alignment.End, + modifier = modifier + .width(IntrinsicSize.Min) + .padding(top = lineHeightDp * firstLine.toFloat()), + ) { + for (line in firstLine..lastLine) { + Text( + text = (line + 1).toString(), + color = if (line == cursorLine) cursorColor else mutedColor, + textAlign = TextAlign.End, + maxLines = 1, + style = style, + modifier = Modifier.fillMaxWidth().height(lineHeightDp), + ) + } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e52b58b21..68940091f6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2216,6 +2216,23 @@ Removed \"%1$s\" from Favorites Empty directory Up one level + Open + Save + Read only + Binary + Modified + Ln %1$d, Col %2$d + Find + Find previous + Find next + Replace + All + Discard changes? + Changes to \"%1$s\" will be lost. + Discard + Couldn\'t save \"%1$s\" + Couldn\'t open \"%1$s\" + Too large to open (%1$s) Choose a folder Choose a file Steam blue diff --git a/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt new file mode 100644 index 0000000000..7fb3a7a68b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/TextEditorLogicTest.kt @@ -0,0 +1,143 @@ +package com.droiddeck.launcher.files + +import java.io.ByteArrayInputStream +import java.io.File +import java.nio.charset.Charset +import java.nio.file.Files +import org.junit.Assert.assertArrayEquals +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 TextEditorLogicTest { + + @Test + fun nulByteMarksBinary() { + val clean = "hello world".toByteArray() + assertFalse(editorIsBinary(clean)) + val withNul = byteArrayOf(1, 2, 0, 3) + assertTrue(editorIsBinary(withNul)) + } + + @Test + fun binaryScanStopsAtSampleLimit() { + val bytes = ByteArray(9000) { if (it == 8999) 0 else 65 } + assertFalse(editorIsBinary(bytes)) + assertTrue(editorIsBinary(bytes, sample = 9000)) + } + + @Test + fun utf8TextDecodesAsUtf8() { + val decoded = decodeEditorText("ไฝ ๅฅฝ, world".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("ไฝ ๅฅฝ, world", decoded.text) + } + + @Test + fun gbkBytesFallBackToGb18030() { + val gbk = "ไฝ ๅฅฝ".toByteArray(Charset.forName("GBK")) + val decoded = decodeEditorText(gbk) + assertEquals(EditorCharset.GB18030, decoded.charset) + assertFalse(decoded.lossy) + assertEquals("ไฝ ๅฅฝ", decoded.text) + } + + @Test + fun undecodableBytesStayLossyUtf8() { + val decoded = decodeEditorText(byteArrayOf(0xFF.toByte())) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertTrue(decoded.lossy) + } + + @Test + fun literalReplacementCharStaysCleanUtf8() { + val decoded = decodeEditorText("๏ฟฝA".toByteArray(Charsets.UTF_8)) + assertEquals(EditorCharset.UTF8, decoded.charset) + assertFalse(decoded.lossy) + } + + @Test + fun readCappedRefusesOverLimit() { + val data = ByteArray(100) { 65 } + assertArrayEquals(data, readCapped(ByteArrayInputStream(data), 100L)) + assertNull(readCapped(ByteArrayInputStream(data), 99L)) + } + + @Test + fun tabsExpandToTabStops() { + assertEquals("ab c", expandEditorTabs("ab\tc")) + assertEquals(" x", expandEditorTabs("\tx")) + assertEquals("abcd e", expandEditorTabs("abcd\te")) + assertEquals("abc def g", expandEditorTabs("abc\tdef\tg")) + assertEquals("a \n b", expandEditorTabs("a\t\n\tb")) + assertEquals("plain text", expandEditorTabs("plain text")) + } + + @Test + fun lineCountCountsTrailingEmptyLine() { + assertEquals(1, lineCountOf("")) + assertEquals(1, lineCountOf("abc")) + assertEquals(2, lineCountOf("a\nb")) + assertEquals(2, lineCountOf("a\n")) + } + + @Test + fun offsetMapsToZeroBasedLineAndOneBasedColumn() { + val text = "ab\ncd" + assertEquals(0, lineIndexOfOffset(text, 0)) + assertEquals(0, lineIndexOfOffset(text, 2)) + assertEquals(1, lineIndexOfOffset(text, 3)) + assertEquals(1, lineIndexOfOffset(text, 5)) + assertEquals(1, columnOfOffset(text, 0)) + assertEquals(3, columnOfOffset(text, 2)) + assertEquals(2, columnOfOffset(text, 4)) + assertEquals(3, columnOfOffset(text, 5)) + } + + @Test + fun findMatchesHonorsCaseAndLimit() { + val text = "abcABCabc" + val all = findEditorMatches(text, "abc", matchCase = false) + assertEquals(listOf(0..2, 3..5, 6..8), all) + val exact = findEditorMatches(text, "abc", matchCase = true) + assertEquals(listOf(0..2, 6..8), exact) + assertEquals(2, findEditorMatches(text, "abc", matchCase = false, limit = 2).size) + assertEquals(emptyList(), findEditorMatches(text, "")) + assertEquals(listOf(0..1), findEditorMatches("aaa", "aa")) + } + + @Test + fun replaceSpansEveryMatch() { + val text = "one two one" + val matches = findEditorMatches(text, "one", matchCase = true) + assertEquals("1 two 1", replaceEditorMatches(text, matches, "1")) + assertEquals(text, replaceEditorMatches(text, emptyList(), "x")) + } + + @Test + fun saveTargetResolvesSymbolicLink() { + val dir = Files.createTempDirectory("editor-link").toFile() + try { + val target = File(dir, "real.txt").apply { writeText("hi") } + val link = File(dir, "link.txt") + Files.createSymbolicLink(link.toPath(), target.toPath()) + assertEquals(target.canonicalFile, resolveEditorSaveTarget(link)) + } finally { + dir.deleteRecursively() + } + } + + @Test + fun saveTargetKeepsRegularFile() { + val dir = Files.createTempDirectory("editor-plain").toFile() + try { + val plain = File(dir, "plain.txt").apply { writeText("hi") } + assertEquals(plain, resolveEditorSaveTarget(plain)) + } finally { + dir.deleteRecursively() + } + } +} From 3b8b14b06c21c97c190a888a939848056702b51a Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 10:27:47 -0500 Subject: [PATCH 12/17] fix(session): FEX and AppImage extraction no longer hang at start-up (#3070) The clock pause preload opened its control file on the first monotonic clock read. A program whose allocator reads the clock while holding its own lock, as FEX does while it starts, re-entered that allocator through the open wrappers and deadlocked. The control file is now opened only in the preload's constructor, so a clock read never opens a file. --- tools/linuxfs/preload/clockpause.c | 16 +------ tools/tests/test_clock_pause_preload.py | 57 +++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/tools/linuxfs/preload/clockpause.c b/tools/linuxfs/preload/clockpause.c index 8fe0b7ce77..70b4179329 100644 --- a/tools/linuxfs/preload/clockpause.c +++ b/tools/linuxfs/preload/clockpause.c @@ -25,7 +25,6 @@ #define CP_FDS 65536 static const int64_t *cp_shift; -static int cp_state; static size_t cp_cond_byte; static unsigned char cp_cond_mask; static unsigned char cp_fds[CP_FDS / 8]; @@ -94,25 +93,14 @@ static void cp_init(void) { } static int64_t cp_offset(void) { - const int64_t *shift; - int state = __atomic_load_n(&cp_state, __ATOMIC_ACQUIRE); - if (state == 0) { - int expected = 0; - if (__atomic_compare_exchange_n(&cp_state, &expected, 1, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { - cp_init(); - __atomic_store_n(&cp_state, 2, __ATOMIC_RELEASE); - } - return 0; - } - if (state != 2) return 0; - shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); + const int64_t *shift = __atomic_load_n(&cp_shift, __ATOMIC_ACQUIRE); if (!shift) return 0; int64_t value = __atomic_load_n(shift, __ATOMIC_RELAXED); return value > 0 ? value : 0; } __attribute__((constructor)) static void cp_start(void) { - cp_offset(); + cp_init(); } static int cp_mono(clockid_t clock) { diff --git a/tools/tests/test_clock_pause_preload.py b/tools/tests/test_clock_pause_preload.py index 3d3f0dd76b..7b92a444bc 100644 --- a/tools/tests/test_clock_pause_preload.py +++ b/tools/tests/test_clock_pause_preload.py @@ -107,6 +107,51 @@ int main(void) { } """ +EARLY_LIBRARY = r""" +#include +#include + +pthread_mutex_t early_lock = PTHREAD_MUTEX_INITIALIZER; + +__attribute__((constructor)) static void early_start(void) { + struct timespec ts; + pthread_mutex_lock(&early_lock); + clock_gettime(CLOCK_MONOTONIC, &ts); + pthread_mutex_unlock(&early_lock); +} +""" + +EARLY_PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +extern pthread_mutex_t early_lock; + +int open(const char *path, int flags, ...) { + va_list args; + va_start(args, flags); + mode_t mode = (mode_t)va_arg(args, int); + va_end(args); + pthread_mutex_lock(&early_lock); + pthread_mutex_unlock(&early_lock); + return (int)syscall(SYS_openat, AT_FDCWD, path, flags, mode); +} + +int main(void) { + struct timespec mono, boot; + clock_gettime(CLOCK_MONOTONIC, &mono); + clock_gettime(CLOCK_BOOTTIME, &boot); + printf("gap %lld\n", (long long)(((boot.tv_sec - mono.tv_sec) * 1000000000LL + boot.tv_nsec - mono.tv_nsec) / 1000000LL)); + return 0; +} +""" + SHIFT_MS = 10000 @@ -128,6 +173,13 @@ class ClockPausePreloadTest(unittest.TestCase): subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.shell), str(build / "program.c")], check=True) cls.other = build / "kwin_wayland" shutil.copy(cls.shell, cls.other) + (build / "early.c").write_text(EARLY_LIBRARY) + (build / "early_program.c").write_text(EARLY_PROGRAM) + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-pthread", "-o", str(build / "libearly.so"), + str(build / "early.c")], check=True) + cls.early = build / "early_program" + subprocess.run(["cc", "-O2", "-pthread", "-o", str(cls.early), str(build / "early_program.c"), + "-L", str(build), "-learly", "-Wl,-rpath," + str(build)], check=True) @classmethod def tearDownClass(cls): @@ -153,6 +205,11 @@ class ClockPausePreloadTest(unittest.TestCase): self.assertGreaterEqual(paused[name], 50, name) self.assertLess(paused[name], 1000, name) + def test_clock_read_inside_a_library_constructor_does_not_reenter_the_program(self): + plain = self.run_program(self.early, 0) + paused = self.run_program(self.early, SHIFT_MS) + self.assertAlmostEqual(paused["gap"] - plain["gap"], SHIFT_MS, delta=50) + def test_program_without_preload_keeps_the_real_clock(self): plain = self.run_program(self.other, 0, preload=False) paused = self.run_program(self.other, SHIFT_MS, preload=False) From bf7f7ecda79754e8cc51f67484629b4e04801844 Mon Sep 17 00:00:00 2001 From: The412Banner <205237651+The412Banner@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:40:16 -0500 Subject: [PATCH 13/17] fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs (#3054) * fix(nativeguest): a spawned "ld.so --list PROGRAM" loads the program from the rootfs * fix(nativeguest): keep the existing ld.so start comments --------- Co-authored-by: maxjivi05 --- tools/nativeguest/hook/exec.c | 130 ++++++++++-------- tools/tests/test_native_hook_ldso_spawn.py | 147 +++++++++++++++++++++ 2 files changed, 220 insertions(+), 57 deletions(-) create mode 100644 tools/tests/test_native_hook_ldso_spawn.py diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index ce91b699b5..3f316fc3b3 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -263,6 +263,60 @@ static int is_ldconfig_name(const char *name) { return strcmp(name, "ldconfig") == 0 || strcmp(name, "ldconfig.real") == 0; } +struct ldso_direct { + char prog[PATH_MAX]; + char lib_path[PATH_MAX * 6]; +}; + +// ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads +// gets the --library-path a start of its own gets, or ldd reports its libraries as not found, +// and its path mapped into the rootfs, since ld.so opens it without the hook +static char **ldso_direct_argv(char *const argv[], char *const envp[], struct ldso_direct *buf, int *err) { + *err = 0; + int caller_lib_path = 0; + int pi = ldso_program_index(argv, &caller_lib_path); + if (pi <= 0) return NULL; + int argc = 0; + while (argv[argc]) argc++; + const char *prog = argv[pi]; + if (caller_lib_path) { + // the caller's own --library-path stays as it is; only the program is mapped (when it is + // in the rootfs: a caller can also name a file by its real path) + if (prog[0] == '/') { + const char *mapped = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; + if (fd >= 0) { + syscall(SYS_close, fd); + prog = mapped; + } + } + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); + if (!out) { + *err = ENOMEM; + return NULL; + } + for (int i = 0; i <= argc; i++) out[i] = argv[i]; + out[pi] = (char *)prog; + return out; + } + if (prog[0] == '/') prog = rewrite_path(prog, buf->prog, sizeof(buf->prog)); + struct exec_probe prog_probe; + probe_exec_file(prog, &prog_probe); + build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, + prog[0] == '/' ? prog : NULL, buf->lib_path, sizeof(buf->lib_path)); + char **out = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); + if (!out) { + *err = ENOMEM; + return NULL; + } + out[0] = argv[0]; + out[1] = (char *)"--library-path"; + out[2] = buf->lib_path; + for (int i = 1; i <= argc; i++) out[i + 2] = argv[i]; + out[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + return out; +} + static int ddnatv_execve(const char *filename, char *const argv[], char *const envp[], int depth) { orig_execve_f_type orig_execve = real_execve(); if (!orig_execve) { @@ -388,63 +442,15 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } } - // ld.so started directly (ldd, "ld.so --list PROGRAM", "ld.so PROGRAM"): the program it loads - // gets the --library-path a start of its own gets, or ldd reports its libraries as not found, - // and its path mapped into the rootfs, since ld.so opens it without the hook if (probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { - int caller_lib_path = 0; - int pi = ldso_program_index(argv, &caller_lib_path); - if (pi > 0 && caller_lib_path) { - // the caller's own --library-path stays as it is; only the program is mapped (when it is - // in the rootfs: a caller can also name a file by its real path) - char prog_buf[PATH_MAX]; - const char *prog = argv[pi]; - if (prog[0] == '/') { - const char *mapped = rewrite_path(prog, prog_buf, sizeof(prog_buf)); - int fd = mapped != prog ? (int)syscall(SYS_openat, AT_FDCWD, mapped, O_PATH | O_CLOEXEC) : -1; - if (fd >= 0) { - syscall(SYS_close, fd); - prog = mapped; - } - } - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 1)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - for (int i = 0; i <= argc; i++) new_argv[i] = argv[i]; - new_argv[pi] = (char *)prog; - prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); - int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); - int saved_errno = errno; - free_modified_env(ddnatv_env, envp); - free(new_argv); - errno = saved_errno; - return ret; + struct ldso_direct direct; + int err; + char **new_argv = ldso_direct_argv(argv, envp, &direct, &err); + if (err) { + errno = err; + return -1; } - if (pi > 0) { - char prog_buf[PATH_MAX]; - const char *prog = argv[pi][0] == '/' ? rewrite_path(argv[pi], prog_buf, sizeof(prog_buf)) : argv[pi]; - struct exec_probe prog_probe; - probe_exec_file(prog, &prog_probe); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(envp, prog_probe.runpath, prog_probe.runpath_is_rpath, - prog[0] == '/' ? prog : NULL, ld_lib_path, sizeof(ld_lib_path)); - int argc = 0; - while (argv[argc]) argc++; - char **new_argv = (char **)malloc(sizeof(char *) * (size_t)(argc + 3)); - if (!new_argv) { - errno = ENOMEM; - return -1; - } - new_argv[0] = argv[0]; - new_argv[1] = (char *)"--library-path"; - new_argv[2] = ld_lib_path; - for (int i = 1; i <= argc; i++) new_argv[i + 2] = argv[i]; - new_argv[pi + 2] = (char *)prog; // ld.so opens it itself: "ldd /usr/bin/adb" as well + if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself char **ddnatv_env = prepare_ddnatv_env(envp, target); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); @@ -968,9 +974,19 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, } } else { if (in_root && probe.is_elf && !probe.is_dynamic) prepare_static_program(elf_target); - if (orig_posix_spawn) { - ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, argv, new_envp); + char **spawn_argv = (char **)argv; + int err = 0; + struct ldso_direct direct; + if (in_root && probe.is_elf && !probe.is_dynamic && is_ld_linux(elf_target)) { + char **direct_argv = ldso_direct_argv(argv, orig_ep, &direct, &err); + if (direct_argv) spawn_argv = direct_argv; } + if (err) { + ret = err; + } else if (orig_posix_spawn) { + ret = run_spawn(orig_posix_spawn, pid, target, file_actions, attrp, spawn_argv, new_envp); + } + if (spawn_argv != argv) free(spawn_argv); } if (!orig_posix_spawn) { diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py new file mode 100644 index 0000000000..48ed15b2fb --- /dev/null +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -0,0 +1,147 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" +GUEST_LDSO = "/usr/lib/ld-linux-aarch64.so.1" +GUEST_TOOL = "/usr/local/bin/tool" + +RECORDER = r""" +#define _GNU_SOURCE +#include +#include +#include + +static void show(const char *path, char *const argv[]) { + printf("call\t%s", path); + for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); + printf("\n"); + fflush(stdout); +} + +int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + show(path, argv); + if (pid) *pid = 1; + return 0; +} + +int execve(const char *path, char *const argv[], char *const envp[]) { + show(path, argv); + _exit(0); +} +""" + +PROBE = r""" +#include +#include +#include +#include + +extern char **environ; + +int main(int argc, char **argv) { + if (argc < 3) return 2; + if (strcmp(argv[1], "spawn") == 0) { + pid_t pid; + posix_spawn_file_actions_t actions; + posix_spawn_file_actions_init(&actions); + posix_spawn_file_actions_adddup2(&actions, 1, 1); + int ret = posix_spawn(&pid, argv[2], &actions, NULL, argv + 2, environ); + posix_spawn_file_actions_destroy(&actions); + printf("ret\t%d\n", ret); + return 0; + } + execve(argv[2], argv + 2, environ); + printf("ret\t-1\n"); + return 1; +} +""" + + +def guest_loader(prefix): + roots = [Path(prefix[prefix.index("-L") + 1])] if prefix and "-L" in prefix else [Path("/")] + for root in roots: + for name in ("lib/ld-linux-aarch64.so.1", "lib64/ld-linux-aarch64.so.1", "usr/lib/ld-linux-aarch64.so.1"): + if (root / name).exists(): + return root / name + return None + + +class NativeHookLdsoSpawnTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + loader = guest_loader(cls.prefix) + if loader is None: + raise unittest.SkipTest("no aarch64 glibc loader to put in the rootfs") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "recorder.c").write_text(RECORDER) + cls.recorder = tmp / "recorder.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.recorder), str(tmp / "recorder.c")], check=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" + for guest, source in ((GUEST_LDSO, loader), (GUEST_TOOL, cls.probe)): + host = cls.root / guest.lstrip("/") + host.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(source, host) + host.chmod(0o755) + (cls.root / "usr/lib/aarch64-linux-gnu").mkdir(parents=True, exist_ok=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def call(self, how, *argv): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": f"{self.hook}:{self.recorder}"} + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_EXEC", "LD_LIBRARY_PATH")} + 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), how, *argv], env=env, capture_output=True, text=True, timeout=120) + calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.assertEqual(1, len(calls), out.stdout + out.stderr) + if how == "spawn": + self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) + return calls[0] + + def test_spawned_ldso_list_loads_the_program_from_the_rootfs(self): + call = self.call("spawn", GUEST_LDSO, "--list", GUEST_TOOL) + argv = call[1:] + self.assertEqual(str(self.root / GUEST_TOOL.lstrip("/")), argv[-1]) + self.assertEqual("--list", argv[-2]) + self.assertIn("--library-path", argv[:-2]) + + def test_spawn_and_exec_start_ldso_with_the_same_arguments(self): + for args in (("--list", GUEST_TOOL), (GUEST_TOOL, "x"), ("--library-path", "/opt/own", "--list", GUEST_TOOL)): + with self.subTest(args=args): + self.assertEqual(self.call("exec", GUEST_LDSO, *args), self.call("spawn", GUEST_LDSO, *args)) + + def test_a_callers_own_library_path_is_kept(self): + call = self.call("spawn", GUEST_LDSO, "--library-path", "/opt/own", "--list", GUEST_TOOL) + self.assertEqual([GUEST_LDSO, "--library-path", "/opt/own", "--list", str(self.root / GUEST_TOOL.lstrip("/"))], call[1:]) + + def test_ldso_without_a_program_is_spawned_unchanged(self): + call = self.call("spawn", GUEST_LDSO, "--version") + self.assertEqual([GUEST_LDSO, "--version"], call[1:]) + + def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): + self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + + +if __name__ == "__main__": + unittest.main() From 823f70320f12af555fd6e3b3b2015d5bc627834e Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 11:11:10 -0500 Subject: [PATCH 14/17] fix(nativeguest): x86-64 path calls, SIGSYS handlers and re-execs stay inside the rootfs hook (#3074) * fix(nativeguest): x86-64 path system calls and SIGSYS handlers stay inside the rootfs hook FEX passed most guest path system calls to the kernel with an inline svc, so the native path hook never mapped them, and it mirrored guest SIGSYS handlers with a raw rt_sigaction that replaced the hook's own handler, after which the next blocked system call killed the program. Path calls now go through libc's syscall(), which the hook maps (guarded until the hook is initialised so an early allocator cannot deadlock), and a SIGSYS handler set through syscall() is recorded and chained like one set through sigaction(). * fix(ddexec): a program that re-execs itself keeps the rootfs hook A re-exec through /proc/self/exe starts the program through the guest ld.so again but left out the hook, so the child saw host paths. Steam's reaper then recorded host install folders, and Battle.net games moved to a mapped drive the Library could not resolve. The re-exec now preloads the hook of the root the same way the first start does. --- app/src/main/cpp/ddexec/ddexec.c | 152 +++++++++++++--- docs/development/x86-64-steam-client.md | 12 ++ .../0013-path-syscalls-through-libc.patch | 130 ++++++++++++++ tools/nativeguest/hook/env.c | 14 +- tools/nativeguest/hook/exec.c | 28 +-- tools/nativeguest/hook/privileged.c | 126 ++++++++++++-- tools/tests/test_ddexec_reexec.py | 154 +++++++++++++++++ tools/tests/test_fex_path_syscalls.py | 49 ++++++ tools/tests/test_native_hook_ldso_spawn.py | 22 ++- tools/tests/test_native_hook_path_syscalls.py | 163 ++++++++++++++++++ tools/tests/test_native_hook_sigsys_mask.py | 144 ++++++++++++++++ 11 files changed, 942 insertions(+), 52 deletions(-) create mode 100644 tools/fex/patches/0013-path-syscalls-through-libc.patch create mode 100644 tools/tests/test_ddexec_reexec.py create mode 100644 tools/tests/test_fex_path_syscalls.py create mode 100644 tools/tests/test_native_hook_path_syscalls.py create mode 100644 tools/tests/test_native_hook_sigsys_mask.py diff --git a/app/src/main/cpp/ddexec/ddexec.c b/app/src/main/cpp/ddexec/ddexec.c index c7e4384ce3..b4a1db085d 100644 --- a/app/src/main/cpp/ddexec/ddexec.c +++ b/app/src/main/cpp/ddexec/ddexec.c @@ -21,6 +21,7 @@ #define SYS_munmap 215 #define SYS_mmap 222 #define SYS_mprotect 226 +#define SYS_getpid 172 #define AT_FDCWD_ (-100) #define O_RDONLY_ 0 @@ -52,6 +53,21 @@ static size_t slen(const char *s) { return n; } +static int seq(const char *a, const char *b) { + while (*a && *a == *b) a++, b++; + return *a == *b; +} + +static const char *env_get(char **envp, const char *name) { + size_t n = slen(name); + for (; *envp; envp++) { + size_t i = 0; + while (i < n && (*envp)[i] == name[i]) i++; + if (i == n && (*envp)[n] == '=') return *envp + n + 1; + } + return 0; +} + static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); } static void out_num(long v) { @@ -112,19 +128,43 @@ static int prot_of(uint32_t flags) { static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); } -static void load(const char *path, struct image *im, uintptr_t page) { +static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) { + interp[0] = 0; + for (int i = 0; i < phnum; i++) { + if (ph[i].p_type != PT_INTERP) continue; + if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0); + if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz) + die("truncated PT_INTERP", path, 0); + interp[ph[i].p_filesz] = 0; + } +} + +static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) { int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0); if (fd < 0) die("cannot open", path, fd); - Elf64_Ehdr eh; - if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0); - if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 || - eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 || - (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) || - eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS) + if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0); + if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 || + eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 || + (eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) || + eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS) die("not a 64-bit ARM ELF program", path, 0); + long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr); + if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0); + return fd; +} + +static void interp_of(const char *path, char *interp, size_t size) { + Elf64_Ehdr eh; Elf64_Phdr ph[MAX_PHDRS]; - long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr); - if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0); + int fd = read_headers(path, &eh, ph); + read_interp(fd, ph, eh.e_phnum, interp, size, path); + sys6(SYS_close, fd, 0, 0, 0, 0, 0); +} + +static void load(const char *path, struct image *im, uintptr_t page) { + Elf64_Ehdr eh; + Elf64_Phdr ph[MAX_PHDRS]; + int fd = read_headers(path, &eh, ph); uintptr_t lo = UINTPTR_MAX, hi = 0; for (int i = 0; i < eh.e_phnum; i++) { @@ -173,16 +213,9 @@ static void load(const char *path, struct image *im, uintptr_t page) { im->phnum = eh.e_phnum; im->phent = eh.e_phentsize; im->phdr = 0; - im->interp[0] = 0; - for (int i = 0; i < eh.e_phnum; i++) { + read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path); + for (int i = 0; i < eh.e_phnum; i++) if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr; - if (ph[i].p_type == PT_INTERP) { - if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0); - if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz) - die("truncated PT_INTERP", path, 0); - im->interp[ph[i].p_filesz] = 0; - } - } if (!im->phdr) { for (int i = 0; i < eh.e_phnum; i++) { Elf64_Phdr *p = &ph[i]; @@ -202,6 +235,36 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne return fallback; } +static int is_self_exe(const char *execfn) { + if (!execfn) return 0; + if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1; + const char *p = "/proc/"; + while (*p && *p == *execfn) p++, execfn++; + if (*p) return 0; + char num[24]; + int i = (int)sizeof(num) - 1; + num[i] = 0; + unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0); + do { + num[--i] = (char)('0' + pid % 10); + pid /= 10; + } while (pid && i > 0); + const char *d = num + i; + while (*d && *d == *execfn) d++, execfn++; + return !*d && seq(execfn, "/exe"); +} + +static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) { + const char *root = env_get(envp, "DDNATV_ROOT"); + if (!root || interp[0] != '/') return interp; + size_t a = slen(root), b = slen(interp); + if (a + b + 1 > size) return interp; + for (size_t i = 0; i < a; i++) buf[i] = root[i]; + for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i]; + if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp; + return buf; +} + __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { long argc = (long)sp[0]; char **argv = (char **)(sp + 1); @@ -211,25 +274,66 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1); long naux = 0; while (auxv[naux * 2] != AT_NULL) naux++; - if (argc < 3) die("usage: libddexec.so [args...]", 0, 0); + int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0)); + const char *path; + char **args = argv + 2; + long nargs = argc - 2; + char interp_buf[4096]; + char hook_buf[4096]; + if (reexec) { + path = env_get(envp, "DDNATV_REAL_EXE"); + if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0); + args = argv; + nargs = argc; + const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH"); + char prog_interp[256]; + interp_of(path, prog_interp, sizeof(prog_interp)); + if (prog_interp[0] && lib_path && lib_path[0]) { + const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf)); + const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf)); + long n = argc > 1 ? argc - 1 : 0; + char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *)); + long k = 0; + v[k++] = (char *)ld_so; + if (hook == (const char *)hook_buf) { + v[k++] = (char *)"--preload"; + v[k++] = (char *)hook; + } + v[k++] = (char *)"--library-path"; + v[k++] = (char *)lib_path; + v[k++] = (char *)"--argv0"; + v[k++] = argc > 0 ? argv[0] : (char *)path; + v[k++] = (char *)path; + for (long i = 0; i < n; i++) v[k++] = argv[1 + i]; + v[k] = 0; + args = v; + nargs = k; + path = ld_so; + } + } else if (argc < 3) { + die("usage: libddexec.so [args...]", 0, 0); + } else { + path = argv[1]; + } uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096); - const char *path = argv[1]; struct image prog, interp; load(path, &prog, page); int has_interp = prog.interp[0] != 0; - if (has_interp) load(prog.interp, &interp, page); + if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page); // The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one. // The strings stay where the kernel put them. static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN}; long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0])); - long new_argc = argc - 2; + long new_argc = nargs; long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2; - uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); + uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp; + uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15); uintptr_t *w = nsp; *w++ = (uintptr_t)new_argc; - for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2]; + for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i]; *w++ = 0; for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i]; *w++ = 0; diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index d4b99759d5..1a02e3420f 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -291,6 +291,18 @@ alone would then read as an installed client. spins until a `SIGALRM` handler sets a register (R12, or ESI in 32-bit `rt` and legacy frames): FEX-2611.1 with 0001 to 0011 never sees it in any of the three frame types, with this patch all three see it on the first signal, as natively. + - `0013-path-syscalls-through-libc`: FEX passes most path system calls of the guest (`mkdirat`, + `unlinkat`, `renameat`, `renameat2`, `symlinkat`, `linkat`, `mknodat`, `fchmodat`, `fchmodat2`, + `fchownat`, `utimensat`, `truncate`, `chdir`, `chroot`, `inotify_add_watch`) straight to the kernel + with an inline `svc`, which the native userland's path hook never sees, so an x86-64 program wrote + `/opt/...` or `/root/...` to the Android root instead of the rootfs, and `cd` into a rootfs folder + failed. They now go through libc's `syscall()`, which the hook maps like every other path; without + the hook it is the same system call. `tools/tests/test_native_hook_path_syscalls.py` checks the hook + side, including that an allocator which opens files before the hook has started does not hang. + FEX also mirrors each guest signal handler with `syscall(SYS_rt_sigaction, ...)`; for `SIGSYS` the + 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`). - **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/0013-path-syscalls-through-libc.patch b/tools/fex/patches/0013-path-syscalls-through-libc.patch new file mode 100644 index 0000000000..122f7654d2 --- /dev/null +++ b/tools/fex/patches/0013-path-syscalls-through-libc.patch @@ -0,0 +1,130 @@ +diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +index 11ff163..085a621 100644 +--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp ++++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp +@@ -209,6 +209,41 @@ uint64_t SyscallPassthrough7(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, + } + #endif + ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough1(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1) { ++ uint64_t Result = ::syscall(syscall_num, arg1); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough2(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough3(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough4(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4); ++ SYSCALL_ERRNO(); ++} ++ ++template ++requires (syscall_num != -1) ++uint64_t SyscallPathPassthrough5(FEXCore::Core::CpuStateFrame* Frame, uint64_t arg1, uint64_t arg2, uint64_t arg3, uint64_t arg4, uint64_t arg5) { ++ uint64_t Result = ::syscall(syscall_num, arg1, arg2, arg3, arg4, arg5); ++ SYSCALL_ERRNO(); ++} ++ + static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(read, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(write, SyscallPassthrough3); +@@ -238,9 +273,9 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(flock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(fsync, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fdatasync, SyscallPassthrough1); +- REGISTER_SYSCALL_IMPL(truncate, SyscallPassthrough2); ++ REGISTER_SYSCALL_IMPL(truncate, SyscallPathPassthrough2); + REGISTER_SYSCALL_IMPL(getcwd, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(chdir, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(chdir, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(fchdir, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(fchmod, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(fchown, SyscallPassthrough3); +@@ -280,7 +315,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(mlock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(munlock, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(pivot_root, SyscallPassthrough2); +- REGISTER_SYSCALL_IMPL(chroot, SyscallPassthrough1); ++ REGISTER_SYSCALL_IMPL(chroot, SyscallPathPassthrough1); + REGISTER_SYSCALL_IMPL(sync, SyscallPassthrough0); + REGISTER_SYSCALL_IMPL(acct, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(mount, SyscallPassthrough5); +@@ -312,17 +347,17 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(keyctl, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(ioprio_set, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(ioprio_get, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(inotify_add_watch, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(inotify_rm_watch, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(migrate_pages, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(mkdirat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(mknodat, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(fchownat, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL(unlinkat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(renameat, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(linkat, SyscallPassthrough5); +- REGISTER_SYSCALL_IMPL(symlinkat, SyscallPassthrough3); +- REGISTER_SYSCALL_IMPL(fchmodat, SyscallPassthrough3); ++ REGISTER_SYSCALL_IMPL(mkdirat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(mknodat, SyscallPathPassthrough4); ++ REGISTER_SYSCALL_IMPL(fchownat, SyscallPathPassthrough5); ++ REGISTER_SYSCALL_IMPL(unlinkat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(renameat, SyscallPathPassthrough4); ++ REGISTER_SYSCALL_IMPL(linkat, SyscallPathPassthrough5); ++ REGISTER_SYSCALL_IMPL(symlinkat, SyscallPathPassthrough3); ++ REGISTER_SYSCALL_IMPL(fchmodat, SyscallPathPassthrough3); + REGISTER_SYSCALL_IMPL(unshare, SyscallPassthrough1); + REGISTER_SYSCALL_IMPL(splice, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL(tee, SyscallPassthrough4); +@@ -343,7 +378,7 @@ static void RegisterCommon(FEX::HLE::SyscallHandler* Handler) { + REGISTER_SYSCALL_IMPL(kcmp, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL(sched_setattr, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(sched_getattr, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL(renameat2, SyscallPassthrough5); ++ REGISTER_SYSCALL_IMPL(renameat2, SyscallPathPassthrough5); + REGISTER_SYSCALL_IMPL(getrandom, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL(memfd_create, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL(membarrier, SyscallPassthrough2); +@@ -468,7 +503,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(get_robust_list, SyscallPassthrough3); + REGISTER_SYSCALL_IMPL_X64(sync_file_range, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(vmsplice, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(utimensat, SyscallPathPassthrough4); + REGISTER_SYSCALL_IMPL_X64(fallocate, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(timerfd_settime, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X64(timerfd_gettime, SyscallPassthrough2); +@@ -492,7 +527,7 @@ namespace x64 { + REGISTER_SYSCALL_IMPL_X64(cachestat, UnimplementedSyscallSafe); + } + if (Handler->IsHostKernelVersionAtLeast(6, 6, 0)) { +- REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X64(fchmodat2, SyscallPathPassthrough4); + } else { + REGISTER_SYSCALL_IMPL_X64(fchmodat2, UnimplementedSyscallSafe); + } +@@ -529,7 +564,7 @@ namespace x32 { + REGISTER_SYSCALL_IMPL_X32(timer_settime64, SyscallPassthrough4); + REGISTER_SYSCALL_IMPL_X32(timerfd_gettime64, SyscallPassthrough2); + REGISTER_SYSCALL_IMPL_X32(timerfd_settime64, SyscallPassthrough4); +- REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPassthrough4); ++ REGISTER_SYSCALL_IMPL_X32(utimensat_time64, SyscallPathPassthrough4); + REGISTER_SYSCALL_IMPL_X32(ppoll_time64, SyscallPassthrough5); + REGISTER_SYSCALL_IMPL_X32(io_pgetevents_time64, SyscallPassthrough6); + REGISTER_SYSCALL_IMPL_X32(mq_timedsend_time64, SyscallPassthrough5); diff --git a/tools/nativeguest/hook/env.c b/tools/nativeguest/hook/env.c index e881ba1f71..8f3daf8086 100644 --- a/tools/nativeguest/hook/env.c +++ b/tools/nativeguest/hook/env.c @@ -72,7 +72,7 @@ static char *map_preload_paths(const char *value) { return out; } -static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { +static char **prepare_ddnatv_env(char *const envp[], const char *real_exe, const char *lib_path) { init_ddnatv_hook(); int count = 0; int has_preload = 0; @@ -164,6 +164,9 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_REAL_EXE=", 16) == 0) { continue; } + if (chosen_real_exe && envp[i][0] == 'D' && strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) { + continue; + } new_env[dst++] = envp[i]; } @@ -178,6 +181,15 @@ static char **prepare_ddnatv_env(char *const envp[], const char *real_exe) { new_env[dst++] = str; } } + if (chosen_real_exe && lib_path && lib_path[0] != '\0') { + size_t len = strlen(lib_path); + char *str = malloc(20 + len + 1); + if (str) { + memcpy(str, "DDNATV_LIBRARY_PATH=", 20); + memcpy(str + 20, lib_path, len + 1); + new_env[dst++] = str; + } + } char hook_buf[PATH_MAX]; const char *hook = (!has_preload && g_ddnatv_root[0] != '\0') ? ddnatv_hook_library(hook_buf, sizeof(hook_buf)) : NULL; diff --git a/tools/nativeguest/hook/exec.c b/tools/nativeguest/hook/exec.c index 3f316fc3b3..664b0beedf 100644 --- a/tools/nativeguest/hook/exec.c +++ b/tools/nativeguest/hook/exec.c @@ -44,8 +44,8 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d resolve_symlinks(next_path, out, out_size, depth + 1); } -static char **ensure_hook_in_envp(char *const envp[], const char *real_exe) { - return prepare_ddnatv_env(envp, real_exe); +static char **ensure_hook_in_envp(char *const envp[], const char *real_exe, const char *lib_path) { + return prepare_ddnatv_env(envp, real_exe, lib_path); } // The file whose header decides how to start `target`: the symlink-resolved ELF (so ld.so and @@ -162,7 +162,7 @@ static int exec_interp_missing(int fd) { syscall(SYS_pread64, fd, interp, ph.p_filesz, (long)ph.p_offset) != (long)ph.p_filesz) return ENOEXEC; interp[ph.p_filesz] = 0; - int ifd = (int)syscall(SYS_openat, AT_FDCWD, interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int ifd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)interp, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (ifd < 0) return errno; syscall(SYS_close, ifd); return 0; @@ -174,7 +174,7 @@ static int exec_interp_missing(int fd) { // a shell walking $PATH moves on at ENOENT and EACCES, and runs a file without "#!" as a script at // ENOEXEC. static int exec_preflight(const char *path) { - int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + int fd = (int)call_orig_syscall(SYS_openat, AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC | O_NONBLOCK, 0, 0, 0); if (fd < 0) return errno; struct stat st; int err = 0; @@ -428,7 +428,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ENOMEM; return -1; } - char **new_env = ensure_hook_in_envp(envp, elf_target); + char **new_env = ensure_hook_in_envp(envp, elf_target, ld_lib_path); int ret = run_execve(orig_execve, ld_so, new_argv, new_env); if (errno == EACCES && chmod(ld_so, 0755) == 0) { // ld.so without its exec bit (an unusual restore): fix it once and retry @@ -452,7 +452,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (new_argv) { prepare_static_program(static_elf); // ld.so is a static program itself - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, new_argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -486,7 +486,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e errno = ELOOP; ret = -1; } else { - char **ddnatv_env = prepare_ddnatv_env(envp, NULL); + char **ddnatv_env = prepare_ddnatv_env(envp, NULL, NULL); ret = ddnatv_execve(rewritten_interp, new_argv, ddnatv_env, depth + 1); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -506,7 +506,7 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e } if (static_elf) prepare_static_program(static_elf); - char **ddnatv_env = prepare_ddnatv_env(envp, target); + char **ddnatv_env = prepare_ddnatv_env(envp, target, NULL); int ret = run_execve(orig_execve, target, argv, ddnatv_env); int saved_errno = errno; free_modified_env(ddnatv_env, envp); @@ -948,17 +948,21 @@ static int ddnatv_posix_spawn(pid_t *pid, const char *path, // Android programs get Android's environment, as execve() gives them: the glibc hook in // LD_PRELOAD crashes them. - char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target) : clean_env_for_system(orig_ep); + int via_ld_so = has_ld_so && strcmp(elf_target, ld_so) != 0; + char ld_lib_path[PATH_MAX * 6]; + ld_lib_path[0] = '\0'; + if (via_ld_so) + build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); + char **new_envp = in_root ? ensure_hook_in_envp(orig_ep, elf_target, via_ld_so ? ld_lib_path : NULL) + : clean_env_for_system(orig_ep); int ret = -1; - if (has_ld_so && strcmp(elf_target, ld_so) != 0) { + if (via_ld_so) { ensure_exec_bit(elf_target, probe.mode); if (probe.android_interp) prepare_static_program_ex(elf_target, 1); // a Go program built for Android (#42) char hook_buf[PATH_MAX]; const char *hook_so = ddnatv_hook_library(hook_buf, sizeof(hook_buf)); - char ld_lib_path[PATH_MAX * 6]; - build_ld_library_path(orig_ep, probe.runpath, probe.runpath_is_rpath, elf_target, ld_lib_path, sizeof(ld_lib_path)); char **new_argv = build_ldso_argv(ld_so, hook_so, ld_lib_path, elf_target, prog_name, argv); if (!new_argv) { ret = ENOMEM; diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 7bf0a8b692..09a1074b86 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -519,6 +519,13 @@ static int close_range_all(unsigned int first, unsigned int last, int flags) { static __thread int t_syscall_redirect = 0; +static long nested_path_syscall(long number, unsigned long dirfd, unsigned long pathname, unsigned long arg3, unsigned long arg4) { + char nested_buf[PATH_MAX]; + const char *path = (const char *)pathname; + if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); + return call_orig_syscall(number, dirfd, (unsigned long)path, arg3, arg4, 0, 0); +} + long syscall(long number, ...) { va_list ap; va_start(ap, number); @@ -563,6 +570,38 @@ long syscall(long number, ...) { } #endif +#ifdef __NR_rt_sigprocmask + if (number == __NR_rt_sigprocmask && arg2 && (arg1 == SIG_BLOCK || arg1 == SIG_SETMASK) && arg4 == sizeof(uint64_t)) { + uint64_t mask; + memcpy(&mask, (const void *)arg2, sizeof(mask)); + mask &= ~(1ULL << (SIGSYS - 1)); + return call_orig_syscall(number, arg1, (unsigned long)&mask, arg3, arg4, 0, 0); + } +#endif + +#ifdef __NR_rt_sigaction + if (number == __NR_rt_sigaction && arg1 == SIGSYS && arg4 == sizeof(uint64_t)) { + struct { void *handler; unsigned long flags; void *restorer; uint64_t mask; } kact, kold; + struct sigaction act, old; + memset(&act, 0, sizeof(act)); + if (arg2) { + memcpy(&kact, (const void *)arg2, sizeof(kact)); + act.sa_sigaction = (void (*)(int, siginfo_t *, void *))kact.handler; + act.sa_flags = (int)kact.flags; + memcpy(&act.sa_mask, &kact.mask, sizeof(kact.mask)); + } + remember_app_sigsys(arg2 ? &act : NULL, arg3 ? &old : NULL); + if (arg3) { + memset(&kold, 0, sizeof(kold)); + kold.handler = (void *)old.sa_sigaction; + kold.flags = (unsigned long)(unsigned int)old.sa_flags; + memcpy(&kold.mask, &old.sa_mask, sizeof(kold.mask)); + memcpy((void *)arg3, &kold, sizeof(kold)); + } + return 0; + } +#endif + #ifdef __NR_seccomp if (number == __NR_seccomp) { return (long)seccomp((unsigned int)arg1, (unsigned int)arg2, (void *)arg3); @@ -618,16 +657,84 @@ long syscall(long number, ...) { } #endif + if (g_initialized) { +#ifdef __NR_openat + if (number == __NR_openat) { + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); + t_syscall_redirect++; + long ret = (long)openat((int)arg1, (const char *)arg2, (int)arg3, (mode_t)arg4); + t_syscall_redirect--; + return ret; + } +#endif +#if defined(__NR_mkdirat) + if (number == __NR_mkdirat) { + return (long)mkdirat((int)arg1, (const char *)arg2, (mode_t)arg3); + } +#endif +#if defined(__NR_unlinkat) + if (number == __NR_unlinkat) { + return (long)unlinkat((int)arg1, (const char *)arg2, (int)arg3); + } +#endif +#if defined(__NR_renameat) + if (number == __NR_renameat) { + return (long)renameat((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4); + } +#endif +#if defined(__NR_renameat2) + if (number == __NR_renameat2) { + return (long)renameat2((int)arg1, (const char *)arg2, (int)arg3, (const char *)arg4, (unsigned int)arg5); + } +#endif +#if defined(__NR_symlinkat) + if (number == __NR_symlinkat) { + return (long)symlinkat((const char *)arg1, (int)arg2, (const char *)arg3); + } +#endif +#if defined(__NR_fchmodat) + if (number == __NR_fchmodat) { + return (long)fchmodat((int)arg1, (const char *)arg2, (mode_t)arg3, 0); + } +#endif +#if defined(__NR_fchownat) + if (number == __NR_fchownat) { + return (long)fchownat((int)arg1, (const char *)arg2, (uid_t)arg3, (gid_t)arg4, (int)arg5); + } +#endif +#if defined(__NR_utimensat) + if (number == __NR_utimensat) { + if (!arg2) return call_orig_syscall(number, arg1, arg2, arg3, arg4, 0, 0); + return (long)utimensat((int)arg1, (const char *)arg2, (const struct timespec *)arg3, (int)arg4); + } +#endif +#if defined(__NR_truncate) + if (number == __NR_truncate) { + return (long)truncate((const char *)arg1, (off_t)arg2); + } +#endif +#if defined(__NR_chdir) + if (number == __NR_chdir) { + return (long)chdir((const char *)arg1); + } +#endif +#if defined(__NR_chroot) + if (number == __NR_chroot) { + return (long)chroot((const char *)arg1); + } +#endif +#if defined(__NR_inotify_add_watch) + if (number == __NR_inotify_add_watch) { + return (long)inotify_add_watch((int)arg1, (const char *)arg2, (uint32_t)arg3); + } +#endif + } + #ifdef __NR_openat2 if (number == __NR_openat2) { // libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested // call maps the path and goes straight to the kernel - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, arg4, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, arg4); t_syscall_redirect++; long ret = (long)openat2((int)arg1, (const char *)arg2, (struct ddnatv_open_how *)arg3, (size_t)arg4); t_syscall_redirect--; @@ -649,12 +756,7 @@ long syscall(long number, ...) { #if defined(__NR_faccessat) if (number == __NR_faccessat) { - if (t_syscall_redirect) { - char nested_buf[PATH_MAX]; - const char *path = (const char *)arg2; - if (path && path[0] == '/') path = rewrite_path(path, nested_buf, sizeof(nested_buf)); - return call_orig_syscall(number, arg1, (unsigned long)path, arg3, 0, 0, 0); - } + if (t_syscall_redirect) return nested_path_syscall(number, arg1, arg2, arg3, 0); t_syscall_redirect++; long ret = (long)faccessat((int)arg1, (const char *)arg2, (int)arg3, 0); t_syscall_redirect--; diff --git a/tools/tests/test_ddexec_reexec.py b/tools/tests/test_ddexec_reexec.py new file mode 100644 index 0000000000..640db1706c --- /dev/null +++ b/tools/tests/test_ddexec_reexec.py @@ -0,0 +1,154 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +REPO = Path(__file__).resolve().parents[2] +SOURCE = REPO / "app/src/main/cpp/ddexec/ddexec.c" +SYSROOT = Path("/usr/aarch64-linux-gnu") + +LIBRARY = r""" +int dd_probe_value(void) { return 7; } +""" + +HOOK = r""" +#include + +__attribute__((constructor)) static void hooked(void) { write(1, "hooked\n", 7); } +""" + +PROGRAM = r""" +#include +#include +#include +#include +#include + +int dd_probe_value(void); + +int main(int argc, char **argv, char **envp) { + if (dd_probe_value() != 7) return 4; + if (argc > 1 && strcmp(argv[1], "again") == 0) { + for (int i = 0; i < argc; i++) printf("%s%s", i ? "|" : "", argv[i]); + printf("\n%s\n", (char *)getauxval(AT_EXECFN)); + return 0; + } + char *next[] = {"first", "again", "x y", NULL}; + syscall(SYS_execveat, -100, "/proc/self/exe", next, envp, 0); + return 3; +} +""" + + +def ndk_clang(): + sdk = Path(os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") or Path.home() / "Android/Sdk") + for ndk in sorted((sdk / "ndk").glob("*"), reverse=True): + clang = ndk / "toolchains/llvm/prebuilt/linux-x86_64/bin/clang" + if clang.exists(): + return str(clang) + return shutil.which("clang") + + +class DdexecReexecTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cc, prefix = runner() + clang = ndk_clang() + if cc is None or clang is None or not shutil.which("bwrap") or not SYSROOT.is_dir(): + raise unittest.SkipTest("no aarch64 toolchain, runner or bwrap") + cls.qemu = list(prefix[:3]) if prefix else [] + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.loader = tmp / "libddexec.so" + subprocess.run([clang, "--target=aarch64-linux-android29", "-shared", "-fPIC", "-O2", "-ffreestanding", + "-fno-builtin", "-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-nostdlib", + "-Wl,-e,_start", "-Wl,-z,noexecstack", "-Wl,--no-undefined", "-Wl,-Bsymbolic", + "-Wl,-z,max-page-size=16384", "-o", str(cls.loader), str(SOURCE)], check=True) + cls.libdir = tmp / "own-lib" + cls.libdir.mkdir() + (tmp / "lib.c").write_text(LIBRARY) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.libdir / "libddprobe.so"), str(tmp / "lib.c")], + check=True) + (tmp / "prog.c").write_text(PROGRAM) + cls.program = tmp / "prog" + subprocess.run([cc, "-O1", "-o", str(cls.program), str(tmp / "prog.c"), "-L", str(cls.libdir), "-lddprobe"], + check=True) + cls.root = tmp / "root" + (cls.root / "usr/lib").mkdir(parents=True) + (cls.root / "lib").mkdir() + shutil.copy2(SYSROOT / "lib/ld-linux-aarch64.so.1", cls.root / "lib/ld-linux-aarch64.so.1") + (tmp / "hook.c").write_text(HOOK) + subprocess.run([cc, "-shared", "-fPIC", "-O1", "-o", str(cls.root / "usr/lib/libddnatv-hook.so"), str(tmp / "hook.c")], + check=True) + probe = subprocess.run(["bwrap", "--dev-bind", "/", "/", "true"], capture_output=True) + if probe.returncode != 0: + raise unittest.SkipTest("bwrap cannot create a namespace here") + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def env(self, real_exe, library_path=None, root=SYSROOT): + env = {k: v for k, v in os.environ.items() if not k.startswith(("DDNATV_", "LD_", "QEMU_"))} + env["DDNATV_ROOT"] = str(root) + env["LD_LIBRARY_PATH"] = f"{SYSROOT / 'lib'}:{self.libdir}" if library_path is None else str(SYSROOT / "lib") + if real_exe: + env["DDNATV_REAL_EXE"] = str(real_exe) + if library_path: + env["DDNATV_LIBRARY_PATH"] = library_path + return env + + def reexec(self, execfn, real_exe, library_path=None, root=SYSROOT): + jail = ["bwrap", "--dev-bind", "/", "/", "--tmpfs", "/proc"] + parent = str(Path(execfn).parent) + jail += ["--dir", parent, "--ro-bind", str(self.loader), execfn] + start = self.qemu + ["-0", "first", execfn] if self.qemu else ["bash", "-c", 'exec -a first "$0" "$@"', execfn] + cmd = jail + start + ["again", "x y"] + return subprocess.run(cmd, env=self.env(real_exe, library_path, root), capture_output=True, text=True, timeout=120) + + def test_reexec_through_proc_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_thread_self_exe_runs_the_guest_program(self): + out = self.reexec("/proc/thread-self/exe", self.program) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_finds_libraries_through_the_recorded_library_path(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_through_ld_so_preloads_the_hook_of_the_root(self): + out = self.reexec("/proc/self/exe", self.program, f"{self.libdir}:{SYSROOT / 'lib'}", self.root) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(["hooked", "first|again|x y", str(self.program)], out.stdout.splitlines()) + + def test_reexec_without_a_known_program_fails_cleanly(self): + out = self.reexec("/proc/self/exe", None) + self.assertEqual(127, out.returncode) + self.assertIn("DDNATV_REAL_EXE", out.stderr) + + def test_a_started_program_keeps_its_own_arguments(self): + ldso = SYSROOT / "lib/ld-linux-aarch64.so.1" + cmd = self.qemu + [str(self.loader), str(ldso), "ld.so", "--library-path", f"{SYSROOT / 'lib'}:{self.libdir}", + str(self.program), "again", "a"] + out = subprocess.run(cmd, env=self.env(self.program), capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual([f"{self.program}|again|a", str(self.program)], out.stdout.splitlines()) + + def test_the_usage_check_still_applies_outside_a_reexec(self): + out = subprocess.run(self.qemu + [str(self.loader), str(self.program)], env=self.env(self.program), + capture_output=True, text=True, timeout=120) + self.assertEqual(127, out.returncode) + self.assertIn("usage", out.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_path_syscalls.py b/tools/tests/test_fex_path_syscalls.py new file mode 100644 index 0000000000..203f2eaac1 --- /dev/null +++ b/tools/tests/test_fex_path_syscalls.py @@ -0,0 +1,49 @@ +import re +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +PATCH = REPO / "tools/fex/patches/0013-path-syscalls-through-libc.patch" +HOOK = REPO / "tools/nativeguest/hook/privileged.c" +PASSTHROUGH = "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls/Passthrough.cpp" +REGISTER = re.compile(r"REGISTER_SYSCALL_IMPL(?:_X64|_X32)?\((\w+), (\w+?)(\d)\);") + + +def changed(): + removed, added = {}, {} + for line in PATCH.read_text().splitlines(): + found = REGISTER.search(line) + if found and line[:1] in "+-": + (added if line[0] == "+" else removed)[found.group(1)] = found.groups()[1:] + return removed, added + + +class FexPathSyscallsTest(unittest.TestCase): + def test_only_the_passthrough_table_changes(self): + self.assertEqual(re.findall(r"^diff --git a/(\S+) ", PATCH.read_text(), re.M), [PASSTHROUGH]) + + def test_each_path_syscall_keeps_its_arity_and_goes_through_libc(self): + removed, added = changed() + self.assertEqual(sorted(removed), sorted(added)) + self.assertGreater(len(added), 10) + for name, (template, arity, number) in added.items(): + with self.subTest(name=name): + self.assertEqual(("SyscallPassthrough", arity, number), removed[name]) + self.assertEqual("SyscallPathPassthrough", template) + + def test_the_new_templates_call_the_libc_syscall(self): + added = [line[1:] for line in PATCH.read_text().splitlines() if line.startswith("+") and not line.startswith("+++")] + calls = [line for line in added if "syscall(" in line and "Result" in line] + self.assertEqual(5, len(calls)) + self.assertTrue(all("::syscall(syscall_num" in line for line in calls)) + self.assertFalse([line for line in added if line.strip().startswith(("//", "/*"))]) + + def test_every_routed_syscall_is_rewritten_by_the_hook(self): + hook = HOOK.read_text() + for name, (_, _, number) in changed()[1].items(): + with self.subTest(name=name): + self.assertIn(f"number == __NR_{number})", hook) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_ldso_spawn.py b/tools/tests/test_native_hook_ldso_spawn.py index 48ed15b2fb..43b810344a 100644 --- a/tools/tests/test_native_hook_ldso_spawn.py +++ b/tools/tests/test_native_hook_ldso_spawn.py @@ -15,24 +15,27 @@ RECORDER = r""" #define _GNU_SOURCE #include #include +#include #include -static void show(const char *path, char *const argv[]) { +static void show(const char *path, char *const argv[], char *const envp[]) { printf("call\t%s", path); for (int i = 0; argv[i]; i++) printf("\t%s", argv[i]); printf("\n"); + for (int i = 0; envp && envp[i]; i++) + if (strncmp(envp[i], "DDNATV_LIBRARY_PATH=", 20) == 0) printf("libpath\t%s\n", envp[i] + 20); fflush(stdout); } int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { - show(path, argv); + show(path, argv, envp); if (pid) *pid = 1; return 0; } int execve(const char *path, char *const argv[], char *const envp[]) { - show(path, argv); + show(path, argv, envp); _exit(0); } """ @@ -114,6 +117,7 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): env.update(hook_env) out = subprocess.run(cmd + [str(self.probe), how, *argv], env=env, capture_output=True, text=True, timeout=120) calls = [line.split("\t")[1:] for line in out.stdout.splitlines() if line.startswith("call\t")] + self.library_paths = [line.split("\t", 1)[1] for line in out.stdout.splitlines() if line.startswith("libpath\t")] self.assertEqual(1, len(calls), out.stdout + out.stderr) if how == "spawn": self.assertIn("ret\t0", out.stdout.splitlines(), out.stdout + out.stderr) @@ -142,6 +146,18 @@ class NativeHookLdsoSpawnTest(unittest.TestCase): def test_spawn_and_exec_start_a_dynamic_program_the_same_way(self): self.assertEqual(self.call("exec", GUEST_TOOL, "x"), self.call("spawn", GUEST_TOOL, "x")) + def test_a_program_started_through_ldso_records_its_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + argv = self.call(how, GUEST_TOOL, "x")[1:] + self.assertEqual([argv[argv.index("--library-path") + 1]], self.library_paths) + + def test_ldso_started_by_name_records_no_library_path(self): + for how in ("exec", "spawn"): + with self.subTest(how=how): + self.call(how, GUEST_LDSO, "--list", GUEST_TOOL) + self.assertEqual([], self.library_paths) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/test_native_hook_path_syscalls.py b/tools/tests/test_native_hook_path_syscalls.py new file mode 100644 index 0000000000..ab69fc3c83 --- /dev/null +++ b/tools/tests/test_native_hook_path_syscalls.py @@ -0,0 +1,163 @@ +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""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +static void show(const char *name, long ret) { printf("%s\t%d\n", name, ret >= 0); } + +int main(int argc, char **argv) { + const char *dir = argv[1]; + char p[PATH_MAX], q[PATH_MAX], cwd[PATH_MAX]; + snprintf(p, sizeof(p), "%s/made", dir); + show("mkdirat", syscall(SYS_mkdirat, AT_FDCWD, p, 0755)); + snprintf(p, sizeof(p), "%s/made/file", dir); + long fd = syscall(SYS_openat, AT_FDCWD, p, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + show("openat", fd); + if (fd >= 0) close((int)fd); + show("truncate", syscall(SYS_truncate, p, 4)); + show("fchmodat", syscall(SYS_fchmodat, AT_FDCWD, p, 0600)); + show("utimensat", syscall(SYS_utimensat, AT_FDCWD, p, NULL, 0)); + fd = syscall(SYS_openat, AT_FDCWD, p, O_RDONLY | O_CLOEXEC); + show("futimens", fd >= 0 ? syscall(SYS_utimensat, (int)fd, NULL, NULL, 0) : -1); + if (fd >= 0) close((int)fd); + snprintf(q, sizeof(q), "%s/made/moved", dir); + show("renameat", syscall(SYS_renameat, AT_FDCWD, p, AT_FDCWD, q)); + show("renameat2", syscall(SYS_renameat2, AT_FDCWD, q, AT_FDCWD, p, 0)); + snprintf(q, sizeof(q), "%s/made/link", dir); + show("symlinkat", syscall(SYS_symlinkat, "file", AT_FDCWD, q)); + show("unlinkat", syscall(SYS_unlinkat, AT_FDCWD, q, 0)); + snprintf(q, sizeof(q), "%s/made", dir); + show("chdir", syscall(SYS_chdir, q)); + show("cwd", getcwd(cwd, sizeof(cwd)) && strstr(cwd, "/made") ? 0 : -1); + show("unlinkat-file", syscall(SYS_unlinkat, AT_FDCWD, p, 0)); + show("unlinkat-dir", syscall(SYS_unlinkat, AT_FDCWD, q, AT_REMOVEDIR)); + return 0; +} +""" + +ALLOCATOR = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +extern void *__libc_malloc(size_t); +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static int ready; + +void *malloc(size_t size) { + if (!ready) { + pthread_mutex_lock(&lock); + if (!ready) { + long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/stat", O_RDONLY | O_CLOEXEC); + if (fd >= 0) close((int)fd); + ready = 1; + } + pthread_mutex_unlock(&lock); + } + return __libc_malloc(size); +} + +int main(void) { + puts("ready"); + return 0; +} +""" + +EARLY = r""" +#include + +__attribute__((constructor)) static void early(void) { free(malloc(1)); } +""" + +CALLS = ("mkdirat", "openat", "truncate", "fchmodat", "utimensat", "futimens", "renameat", "renameat2", "symlinkat", "unlinkat", + "chdir", "cwd", "unlinkat-file", "unlinkat-dir") + + +class NativeHookPathSyscallsTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-o", str(cls.probe), str(tmp / "probe.c")], check=True) + cls.root = tmp / "root" + (cls.root / "opt").mkdir(parents=True) + (tmp / "allocator.c").write_text(ALLOCATOR) + cls.allocator = tmp / "allocator" + subprocess.run([cls.cc, "-O1", "-rdynamic", "-pthread", "-o", str(cls.allocator), str(tmp / "allocator.c")], check=True) + (tmp / "early.c").write_text(EARLY) + cls.early = tmp / "early.so" + subprocess.run([cls.cc, "-shared", "-fPIC", "-O1", "-o", str(cls.early), str(tmp / "early.c")], check=True) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def run_program(self, argv, hook_env): + 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) + return subprocess.run(cmd + argv, env=env, capture_output=True, text=True, timeout=120) + + def run_probe(self, guest_dir, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + out = self.run_program([str(self.probe), guest_dir], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: int(line.split("\t")[1]) for line in out.stdout.splitlines()} + + def test_guest_paths_through_syscall_land_in_the_root(self): + results = self.run_probe("/opt") + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + self.assertEqual([], list((self.root / "opt").iterdir())) + + def test_paths_already_in_the_root_are_kept(self): + results = self.run_probe(str(self.root / "opt")) + for call in CALLS: + with self.subTest(call=call): + self.assertEqual(1, results[call]) + + def test_without_the_hook_guest_paths_reach_the_host(self): + results = self.run_probe("/opt/droiddeck-hook-probe-missing", hook=False) + self.assertEqual(0, results["mkdirat"]) + self.assertEqual(0, results["openat"]) + self.assertEqual(0, results["chdir"]) + + def test_an_allocator_opening_files_before_the_hook_starts_does_not_hang(self): + hook_env = {"DDNATV_ROOT": str(self.root), "DDNATV_BINDS": "/proc:/proc", + "LD_PRELOAD": f"{self.hook}:{self.early}"} + out = self.run_program([str(self.allocator)], hook_env) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual("ready", out.stdout.strip()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_native_hook_sigsys_mask.py b/tools/tests/test_native_hook_sigsys_mask.py new file mode 100644 index 0000000000..2d28c2954d --- /dev/null +++ b/tools/tests/test_native_hook_sigsys_mask.py @@ -0,0 +1,144 @@ +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""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +static uint64_t current(void) { + uint64_t mask = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, NULL, &mask, sizeof(mask)); + return mask; +} + +struct kact { void *handler; unsigned long flags; void *restorer; uint64_t mask; }; + +static void own(int sig, siginfo_t *info, void *ctx) { (void)sig; (void)info; (void)ctx; } + +static long raw_sigaction(int sig, const struct kact *act, struct kact *old) { + register long x8 __asm__("x8") = SYS_rt_sigaction; + register long x0 __asm__("x0") = sig; + register long x1 __asm__("x1") = (long)act; + register long x2 __asm__("x2") = (long)old; + register long x3 __asm__("x3") = 8; + __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory"); + return x0; +} + +static void handlers(void) { + struct kact act = { (void *)own, SA_SIGINFO, NULL, 0 }, seen, kernel; + syscall(SYS_rt_sigaction, SIGSYS, &act, NULL, 8); + syscall(SYS_rt_sigaction, SIGSYS, NULL, &seen, 8); + raw_sigaction(SIGSYS, NULL, &kernel); + printf("sigaction\t%d\t%d\n", seen.handler == (void *)own, kernel.handler == (void *)own); + struct kact usr1 = { (void *)own, SA_SIGINFO, NULL, 0 }; + syscall(SYS_rt_sigaction, SIGUSR1, &usr1, NULL, 8); + raw_sigaction(SIGUSR1, NULL, &kernel); + printf("sigaction-usr1\t%d\n", kernel.handler == (void *)own); +} + +static void show(const char *how) { + uint64_t mask = current(); + printf("%s\t%d\t%d\n", how, !!(mask & (1ULL << (SIGSYS - 1))), !!(mask & (1ULL << (SIGUSR1 - 1)))); + uint64_t none = 0; + syscall(SYS_rt_sigprocmask, SIG_SETMASK, &none, NULL, sizeof(none)); +} + +int main(int argc, char **argv) { + uint64_t all = ~0ULL; + sigset_t set; + sigfillset(&set); + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "syscall-setmask") == 0) syscall(SYS_rt_sigprocmask, SIG_SETMASK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-block") == 0) syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + else if (strcmp(argv[i], "syscall-unblock") == 0) { + syscall(SYS_rt_sigprocmask, SIG_BLOCK, &all, NULL, sizeof(all)); + uint64_t usr1 = 1ULL << (SIGUSR1 - 1); + syscall(SYS_rt_sigprocmask, SIG_UNBLOCK, &usr1, NULL, sizeof(usr1)); + } + else if (strcmp(argv[i], "sigprocmask") == 0) sigprocmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "pthread_sigmask") == 0) pthread_sigmask(SIG_SETMASK, &set, NULL); + else if (strcmp(argv[i], "sigaction") == 0) { + handlers(); + continue; + } + show(argv[i]); + } + return 0; +} +""" + +WAYS = ("syscall-setmask", "syscall-block", "sigprocmask", "pthread_sigmask") + + +class NativeHookSigsysMaskTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + (tmp / "probe.c").write_text(PROBE) + cls.probe = tmp / "probe" + subprocess.run([cls.cc, "-O1", "-pthread", "-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 masks(self, *ways, hook=True): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} if hook else {} + 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), *ways], env=env, capture_output=True, text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: tuple(int(v) for v in line.split("\t")[1:]) for line in out.stdout.splitlines()} + + def test_blocking_every_signal_leaves_sigsys_open(self): + masks = self.masks(*WAYS) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((0, 1), masks[way]) + + def test_unblocking_is_unchanged(self): + self.assertEqual((0, 0), self.masks("syscall-unblock")["syscall-unblock"]) + + def test_a_sigsys_handler_set_through_syscall_keeps_the_hooks(self): + seen = self.masks("sigaction") + self.assertEqual((1, 0), seen["sigaction"]) + self.assertEqual((1,), seen["sigaction-usr1"]) + + def test_without_the_hook_a_sigsys_handler_reaches_the_kernel(self): + self.assertEqual((1, 1), self.masks("sigaction", hook=False)["sigaction"]) + + def test_without_the_hook_every_signal_is_blocked(self): + masks = self.masks(*WAYS, hook=False) + for way in WAYS: + with self.subTest(way=way): + self.assertEqual((1, 1), masks[way]) + + +if __name__ == "__main__": + unittest.main() From 2151db38834662c36e34b424f11f30d03c522605 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Mon, 23 Nov 2026 11:11:15 -0500 Subject: [PATCH 15/17] fix(battlenet): offer World of Warcraft: Forever in the store (#3075) Forever has its own launch code and installs headlessly through its product code like the other titles, but the store hid it. It is now listed and hidden once installed. --- .../main/java/com/droiddeck/launcher/runtime/BattleNet.kt | 2 +- .../java/com/droiddeck/launcher/runtime/BattleNetTest.kt | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt index 7fb5cdc04b..4362c9308c 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BattleNet.kt @@ -56,7 +56,7 @@ object BattleNet { Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"), ) - val STORE: List get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" } + val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" } // Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity. private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs") diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt index ea0c471faa..2ada13c310 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BattleNetTest.kt @@ -354,13 +354,15 @@ class BattleNetTest { assertEquals(codes.distinct(), codes) assertTrue("Fen" in codes && "OSI" in codes && "WTCG" in codes) assertFalse(BattleNet.STORE.any { it.uid == "d3cn" || it.uid == "fen" }) - assertFalse(BattleNet.STORE.any { it.code == "WoWC" || it.code == "WoWF" }) + assertFalse(BattleNet.STORE.any { it.code == "WoWC" }) + assertEquals("wow_forever", BattleNet.STORE.first { it.code == "WoWF" }.uid) assertEquals("fenris", BattleNet.STORE.first { it.code == "Fen" }.uid) assertTrue(BattleNet.STORE.all { it.uid.matches(Regex("[a-z0-9_]{1,32}")) }) val installed = listOf("fenris", "diablo3_enus", null) val offered = BattleNet.STORE.filter { BattleNet.notInstalled(it, installed) }.map { it.code } assertFalse("Fen" in offered || "D3" in offered) - assertTrue("OSI" in offered) + assertTrue("OSI" in offered && "WoWF" in offered) + assertFalse("WoWF" in BattleNet.STORE.filter { BattleNet.notInstalled(it, listOf("wow_forever")) }.map { it.code }) } @Test fun aBattleNetGameStartsWithoutSteamThroughItsShortcutUntilThatIsSwitchedOff() { From 4b8c3b158d70fdc538a0723a1e26028376f1009a Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:33:13 -0500 Subject: [PATCH 16/17] fix(ui): compact chat in the session drawer stays usable on short or narrow panels (#3078) --- .../com/droiddeck/launcher/ui/AgentPage.kt | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) 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 f447b15686..267964b052 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -11,6 +11,7 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.shrinkHorizontally +import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.expandHorizontally import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically @@ -228,8 +229,14 @@ private fun AgentPageContent( } val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) } val inlineControls: (@Composable () -> Unit)? = if (inline) ({ - ModelChip(panel, togglePanel, inputModifier, compact = true) - ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + // The open menu needs the row's width for its own buttons. + androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(), + exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) { + Row(verticalAlignment = Alignment.CenterVertically) { + ModelChip(panel, togglePanel, inputModifier, compact = true) + ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) }) + } + } menu() }) else null // A host with a title bar shows the top bar there. @@ -245,8 +252,11 @@ private fun AgentPageContent( LaunchedEffect(AgentHost.approvals.size, panel) { if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE } + androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) { + // On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page. + val panelMax = maxHeight * 0.5f Column( - modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> + Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> val k = e.nativeKeyEvent if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false if (k.action == KeyEvent.ACTION_UP) composer.open() @@ -269,8 +279,8 @@ private fun AgentPageContent( else -> { if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() } when (panel) { - AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() } - AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() } + AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() } + AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() } else -> Unit } val list = rememberLazyListState() @@ -322,11 +332,12 @@ private fun AgentPageContent( } } androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { - AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest) + AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen) } } } } + } } /** Whether the editor has the cursor; [open] puts it there. */ @@ -400,7 +411,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) - .border(1.dp, pal.line, Shape16).padding(end = 2.dp), + .border(1.dp, pal.line, Shape16).padding(top = 3.dp, bottom = 3.dp, end = 4.dp), ) { androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(), exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) { @@ -715,7 +726,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit. @Composable private fun AgentComposer( composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, - onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, + onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false, ) { val context = LocalContext.current var draft by draftState @@ -747,13 +758,13 @@ private fun AgentComposer( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), ) { AgentActivity(labOpen) { labOpen = !labOpen } } - AgentEditor(composer, draftState, visible, controls, send) + AgentEditor(composer, draftState, visible, controls, send, hideAttach) } } /** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */ @Composable -private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) { +private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -852,14 +863,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String if (stacked) Column { text(Modifier.fillMaxWidth()) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() } + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() } actions() } } else Row(verticalAlignment = Alignment.Bottom) { - if (attach) AttachButton() - if (AgentAttachments.gameFrame != null) GameFrameButton() + AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } + AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } text(Modifier.weight(1f)) if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() } actions() From 3502b43cea35f27ce298df0188b3985e25d2e077 Mon Sep 17 00:00:00 2001 From: Tushar Gandhe <19225304+2-Shar@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:37:14 +0530 Subject: [PATCH 17/17] fix(ui): the controller focus ring follows each corner of the focused shape (#3036) --- .../com/droiddeck/launcher/ui/FocusGlide.kt | 57 +++++++++++-------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt index 92a6d0b365..c45baa29f1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FocusGlide.kt @@ -33,6 +33,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.geometry.RoundRect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity @@ -109,13 +111,21 @@ internal fun VeilRing() { } } -private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float = +private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray = when (val o = shape.createOutline(size, dir, density)) { - is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x - is Outline.Rectangle -> 0f - is Outline.Generic -> minOf(size.width, size.height) / 2f + is Outline.Rounded -> o.roundRect.run { + floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x) + } + is Outline.Rectangle -> FloatArray(4) + is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f } } +private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path { + // Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does. + fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f)) + return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) } +} + @Composable internal fun Modifier.glideBorder( hot: Boolean, @@ -190,7 +200,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val density = LocalDensity.current val dir = LocalLayoutDirection.current val edges = remember { List(4) { Animatable(0f) } } - val corner = remember { Animatable(0f) } + val corners = remember { List(4) { Animatable(0f) } } val solid = remember { Animatable(0f) } val alpha = remember { Animatable(0f) } val scope = rememberCoroutineScope() @@ -259,14 +269,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { fun droplet(s: GlideSource, b: Rect) { jobs.forEach { it?.cancel() } val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size - val endCorner = cornerOf(s.shape, size, dir, density) + val endCorners = cornersOf(s.shape, size, dir, density) jobs[5] = scope.launch { val r = with(density) { 6.dp.toPx() } fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r) val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f) coroutineScope { launch { solid.animateTo(1f, Motion.tw(80)) } - launch { corner.animateTo(r, Motion.tw(90)) } + corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } } dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } } } val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density @@ -281,7 +291,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { flight.cancel() val at = glide.boundsOf(s) ?: b launch { solid.animateTo(0f, Motion.tw(150)) } - launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) } + // The droplet job is cancelled by the next move, so the shape settles on the corner job instead. + jobs[4]?.cancel() + jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } } listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v -> jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) } } @@ -289,9 +301,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { } fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) { val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size - val r = cornerOf(s.shape, size, dir, density) + val r = cornersOf(s.shape, size, dir, density) jobs[4]?.cancel() - jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) } + jobs[4] = scope.launch { + corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } } + } } snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) -> if (Motion.scale == 0f) { @@ -302,7 +316,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { else { listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) } val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size - corner.snapTo(cornerOf(src.shape, size, dir, density)) + cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) } alpha.snapTo(1f) } shown = src @@ -343,10 +357,11 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val out = with(density) { 3.dp.toPx() } val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out) jobs.forEach { it?.cancel() } + // Set before the join: a move of the target restarts this block there, after shown is already set. + cornerTo(src, b, snap = true) scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join() dirSpecs = List(4) { Edge(0.6f, 700f) } delays = LongArray(4) - cornerTo(src, b, snap = true) scope.launch { alpha.animateTo(1f, Motion.tw(140)) } } else { val dx = b.center.x - (edges[0].value + edges[2].value) / 2f @@ -394,21 +409,13 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier { val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value val sw = (r - l - w).coerceAtLeast(0f) val sh = (b - t - w).coerceAtLeast(0f) - val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f) + val radii = FloatArray(4) { corners[it].value } val f = solid.value - if (f > 0.01f) drawRoundRect( - color, topLeft = Offset(l, t), size = Size(r - l, b - t), - cornerRadius = CornerRadius(corner.value), alpha = a * f, - ) + if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f) if (f < 0.99f) { - drawRoundRect( - color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), - cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha, - ) - drawRoundRect( - color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh), - cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a, - ) + val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f) + drawPath(inner, color, alpha = a * (1f - f) * fillAlpha) + drawPath(inner, color, style = Stroke(w), alpha = a) } } }