feat(addons): add a CurseForge source to the addon browser (#3028)

* feat(addons): add a CurseForge source to the addon browser

Search and install CurseForge addons from the Download addons window by
driving the installed CurseForge app in the background: it starts minimized
on the session's X display with its inspector bound to 127.0.0.1, and the
window's own renderer services handle game detection, search, install and
shutdown. Sign-in stays inside the CurseForge app.

The Install buttons in the addon list now size to their label, so the label
is centered and the button matches the other compact buttons.

* fix(curseforge): secret inspector URL, hold mode and serialised starts

- Start CurseForge with its Node inspector on 127.0.0.1:0 and publish only
  the UUID websocket URL, kept in the 0700 state directory, so no fixed
  unauthenticated debug port is exposed.
- The agent evaluates through that URL instead of a fixed port.
- Add a hold mode that runs as a session program and stops the app on
  exit, and a lock so hold and start never launch twice.

* feat(addons): run CurseForge in a hidden session when none is running

- Opening the CurseForge source with no session starts one headlessly
  (offscreen compositor output, shared start path with SessionActivity via
  CompositorHost) running the CurseForge hold helper; leaving the dialog
  stops the app and that session. A session the user already had is
  reused and left running.
- Drop the "start a session" notice from every locale.
- Addon browser link: cleanup shares the link's lock off the UI thread,
  stops the app at once on close, refuses work after close and stops a
  launch that finishes after close.
- CurseForgeApp.start stops the app before every failed return.
- instanceFor returns no instance when the populated list has no match.

* Harden headless CurseForge session and helper lifecycle

Scope the hidden session to its id, roll back partial starts, release the
offscreen reader once the session ends, re-acquire the inspector when its
endpoint goes away, bound DevTools calls by one deadline, key the installed
snapshot by target, track the helper launch by pid start time and directory,
fail on lock errors, and update the HDR gate test to its new location.

* Map DevTools send failures and recheck the hidden session id

* fix(addons): bind the hidden session to the id it claims at launch

* Keep the CurseForge helper quiet when no launch is recorded
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-22 17:02:35 -05:00
1 parent 234e40157e
commit 210c127446
48 files changed
+1162 -67

No files matched your search

@@ -2846,17 +2846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.running) {
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
}
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 output = CompositorHost.prepare(this)
val previous = SessionState.outputSize
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
@@ -2883,15 +2873,7 @@ 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) {
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)
}
}
if (!SessionState.running) CompositorHost.logToSession(this)
val mode = hdrPrefMode()
if (probe != null) {
WaylandCompositor.nativeSetHdrDisplay(
@@ -2911,19 +2893,8 @@ 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) {
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(),
)
if (!SessionState.running) CompositorHost.applyHdr(this, mode)
CompositorHost.start(this, output, holder.surface, size, 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")
@@ -1,10 +1,216 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import com.droiddeck.launcher.agent.AgentException
import com.droiddeck.launcher.agent.AgentGuest
import org.json.JSONArray
import org.json.JSONObject
import java.time.Instant
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"
private const val READY_MS = 120_000L
private const val INSTALL_MS = 300_000L
enum class Start { READY, BUSY, NO_DISPLAY, 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}")
class Failure(message: String, val code: String? = null) : Exception(message) {
val gone get() = code == "DEVTOOLS_UNREACHABLE"
}
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
fun holdArgs(app: UserApps.App): List<String>? = dir(app)?.let { listOf("hold", it) }
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
}
internal fun sortOf(sort: WowAddonCatalog.Sort): Pair<Int, Int> = when (sort) {
WowAddonCatalog.Sort.POPULAR -> 8 to 2
WowAddonCatalog.Sort.UPDATED -> 16 to 2
WowAddonCatalog.Sort.NAME -> 1 to 1
WowAddonCatalog.Sort.DOWNLOADS -> 7 to 2
}
internal fun searchRequest(guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): JSONObject {
val (column, order) = sortOf(sort)
return JSONObject().put("gameId", WOW).put("searchText", text.trim()).put("page", page + 1)
.put("sortColumn", column).put("sortOrder", order).put("gameInstanceGuid", guid)
}
internal fun installRequest(guid: String, projectId: String): JSONObject =
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4)
private const val SERVICES = """(() => {
const seen = new Set(), out = {};
const walk = (o, d) => {
if (!o || typeof o !== 'object' || seen.has(o) || d > 4) return;
seen.add(o);
if (typeof o._nameOfService === 'string') { out[o._nameOfService] = o; return; }
let keys; try { keys = Object.keys(o); } catch (e) { return; }
for (const k of keys.slice(0, 4000)) {
let v; try { v = o[k]; } catch (e) { continue; }
if (v instanceof Map) { for (const x of v.values()) walk(x, d + 1); } else walk(v, d + 1);
}
};
walk(window, 0);
return out;
})()"""
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
"if (!w) return JSON.stringify({ missing: true }); " +
"return w.webContents.executeJavaScript(${JSONObject.quote(inner)}).then(v => JSON.stringify(v)); })()"
}
internal fun unwrap(answer: JSONObject): Any? {
if (!answer.optBoolean("ok")) {
val error = answer.optJSONObject("error")
throw Failure(error?.optString("message")?.takeIf { it.isNotBlank() } ?: answer.toString(), error?.optString("code")?.takeIf { it.isNotBlank() })
}
val text = answer.opt("value") as? String ?: throw Failure("CurseForge gave no answer")
val reply = JSONObject(text)
if (reply.optBoolean("missing")) throw Failure("CurseForge is not ready")
return reply.opt("value")
}
internal fun parseSearch(value: Any?): WowAddonCatalog.Page {
val reply = value as? JSONObject ?: throw Failure("CurseForge search failed")
if (reply.has("success") && !reply.optBoolean("success")) throw Failure("CurseForge search failed")
val mods = reply.optJSONArray("mods") ?: JSONArray()
val items = (0 until mods.length()).mapNotNull { mods.optJSONObject(it) }.mapNotNull { mod ->
val id = mod.optLong("id", 0L).takeIf { it > 0 } ?: return@mapNotNull null
val name = mod.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val author = mod.optJSONObject("primaryAuthor")?.optString("name")?.takeIf { it.isNotBlank() }
?: mod.optJSONArray("authors")?.optJSONObject(0)?.optString("name").orEmpty()
val date = mod.optJSONObject("updateVersion")?.optString("fileDate")?.takeIf { it.isNotBlank() }
?: mod.optString("projectLatestReleaseDate")
WowAddonCatalog.Addon(
id.toString(), name, author, "", mod.optLong("downloads", 0L).coerceAtLeast(0L),
runCatching { Instant.parse(date).toEpochMilli() }.getOrDefault(0L),
mod.optString("thumbnailUrl").takeIf { WowAddonCatalog.isHttps(it) },
)
}
val page = reply.optJSONObject("pagination")
val more = page != null && page.optInt("index") + page.optInt("resultCount") < page.optInt("totalCount")
return WowAddonCatalog.Page(items, more)
}
internal fun samePath(a: String, b: String) = a.trimEnd('/') == b.trimEnd('/')
internal fun instanceFor(instances: Any?, flavorDir: String, detected: String?): String? {
val list = instances as? JSONArray
val match = list?.let { all ->
(0 until all.length()).mapNotNull { all.optJSONObject(it) }
.firstOrNull { samePath(it.optString("installPath"), flavorDir) }?.optString("guid")
}
if (list != null && list.length() > 0) return match?.takeIf { it.isNotBlank() }
return detected?.takeIf { it.isNotBlank() }
}
internal fun projectIds(value: Any?): Set<String> {
val list = value as? JSONArray ?: return emptySet()
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))
}
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()
}
fun start(context: Context, app: UserApps.App): 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)
}
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)
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
Thread.sleep(1_000)
}
stop(context, app, inspector)
return Started(Start.FAILED)
}
fun stop(context: Context, app: UserApps.App, inspector: String?) {
val dir = dir(app) ?: return
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
helper(context, "stop", dir, 30_000)
}
private fun connect(context: Context, inspector: String) {
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
}
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector)
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
}
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<String> {
connect(context, inspector)
return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
}
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 || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error
if (projectId in listed.getOrDefault(emptySet())) return true
Thread.sleep(1_000)
}
return false
}
}
@@ -93,8 +93,7 @@ object WowAddonCatalog {
Client(folder, version?.let(::flavorOf) ?: folderFamily(folder))
fun client(target: WowAddons.Target): Client {
val dir = target.addOns.parentFile?.parentFile
return client(target.flavor, dir?.let(::clientVersion))
return client(target.flavor, WowAddons.flavorDir(target)?.let(::clientVersion))
}
internal fun flavorMatches(flavors: Set<String>?, family: String?): Boolean =
@@ -28,6 +28,14 @@ object WowAddons {
class TooLarge : IOException()
fun changed() {
imports++
}
fun flavorDir(target: Target): File? = target.addOns.parentFile?.parentFile
fun root(target: Target): File? = flavorDir(target)?.parentFile
class Target(val flavor: String, val addOns: File)
class Addon(val name: String, val root: String)
@@ -0,0 +1,119 @@
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>): 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>): 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
}
}
@@ -180,6 +180,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-flatpak-run" to "usr/local/bin/droiddeck-flatpak-run",
"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-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",
@@ -14,7 +14,6 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridState
@@ -28,6 +27,7 @@ import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -62,8 +62,13 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
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
@@ -81,10 +86,101 @@ private class AddonResults {
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
private enum class AddonSource { WOWI, CURSE }
private class CurseState(val notice: Int? = null) : Exception()
private class CurseLink(val app: UserApps.App) {
class Linked(val inspector: String, val guid: String)
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 inspector: String? = null
private val guids = HashMap<String, String>()
fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target) }
try {
return block(linked)
} catch (e: CurseForgeApp.Failure) {
if (e.gone) synchronized(lock) {
if (inspector == linked.inspector) {
inspector = null
guids.clear()
}
}
throw e
}
}
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)
when (done.state) {
CurseForgeApp.Start.READY -> {
started = true
inspector = done.inspector
done.inspector ?: throw CurseState()
}
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
else -> throw CurseState()
}
}
if (closed) throw CurseState()
guids[target.addOns.path]?.let { return Linked(url, it) }
val root = WowAddons.root(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val flavor = WowAddons.flavorDir(target)?.let { AddedGames.guestPath(context, it) } ?: throw CurseState()
val guid = CurseForgeApp.instance(context, url, root, flavor)
guids[target.addOns.path] = guid
return Linked(url, guid)
}
fun close(context: Context) {
closed = true
Thread {
if (launching) CurseForgeApp.stop(context, app, inspector)
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
inspector = null
}
}.start()
}
}
private const val PAGES_AHEAD = 8
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss)
@@ -93,15 +189,30 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
var text by remember { mutableStateOf("") }
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
val results = remember(text, category, sort, target) { AddonResults() }
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) }
}
var notice by remember { mutableStateOf<Int?>(null) }
var curseInstalls by remember { mutableIntStateOf(0) }
val results = remember(text, category, sort, target, curse) { AddonResults() }
val installing = remember { mutableStateMapOf<String, Int>() }
val installed = remember { mutableStateMapOf<String, Pair<String, String>>() }
val categories by produceState(emptyList<WowAddonCatalog.Category>()) {
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
}
val present by produceState(emptyMap<String, String?>(), target.addOns, WowAddons.imports) {
value = withContext(Dispatchers.IO) { WowAddons.details(target).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() }
val presentKey = curse to target.addOns
val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, 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()
}
}
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
if (addon.id !in present) return AddonStatus.INSTALL
val have = present[addon.id]
@@ -116,10 +227,16 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
val words = text
val cat = category?.id
val order = sort
val via = link?.takeIf { curse != null }
notice = null
scope.launch {
val got = withContext(Dispatchers.IO) {
runCatching { WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page) }
runCatching {
if (via != null) via.call(context, into) { CurseForgeApp.search(context, it.inspector, it.guid, words, order, page) }
else WowAddonCatalog.search(context, WowAddonCatalog.Query(words, cat, WowAddonCatalog.client(into), order), page)
}
}
if (results.items.isEmpty()) notice = (got.exceptionOrNull() as? CurseState)?.notice
got.onSuccess {
if (page == 0) results.items.clear()
results.items.addAll(it.items.filter { addon -> results.items.none { seen -> seen.id == addon.id } })
@@ -136,6 +253,27 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
fun install(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
val via = link?.takeIf { curse != null }
if (via != null) {
val into = target
installing[key] = 0
scope.launch {
val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
installing.remove(key)
val ok = done.getOrNull() == true
if (ok) {
WowAddons.changed()
curseInstalls++
}
val message = when {
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)
}
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
}
return
}
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
@@ -149,7 +287,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(R.string.addons_source_wowi)
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
val grid = rememberLazyGridState()
LaunchedEffect(results, grid) {
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
@@ -170,8 +308,14 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
}
}
}
val sourceChip: @Composable () -> Unit = {
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
}
}
val categoryChip: @Composable () -> Unit = {
if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
if (curse == null && categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() }
categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } }
}
@@ -195,6 +339,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
BoxWithConstraints(Modifier.fillMaxWidth()) {
if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
search(Modifier.weight(1f))
sourceChip()
sortChip()
categoryChip()
flavorChip()
@@ -208,6 +353,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.horizontalScroll(rememberScrollState()),
) {
sourceChip()
sortChip()
categoryChip()
flavorChip()
@@ -228,6 +374,10 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
when {
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
results.failed != null && notice != null -> {
Text(stringResource(notice!!), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(0) }
}
results.failed != null -> {
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
@@ -259,7 +409,7 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
val size = Modifier.widthIn(min = 104.dp).then(action)
val size = action
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) {}
@@ -1049,7 +1049,7 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
@Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
CurseForgeEntry(a)
targets.forEach { target ->
@@ -10,6 +10,8 @@ import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
object CompositorHost {
private const val TAG = "DroidDeck"
@Volatile
private var started = false
@@ -55,6 +57,52 @@ 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<Int, Int>, 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,
+1
View File
@@ -4177,6 +4177,7 @@
<string name="addons_sort_downloads">الأكثر تنزيلًا</string>
<string name="addons_category_all">كل الفئات</string>
<string name="addons_none_found">لم يتم العثور على إضافات</string>
<string name="addons_curse_busy">أغلق CurseForge أولاً</string>
<string name="addons_unreachable">تعذّر الوصول إلى %1$s</string>
<string name="addons_no_file">لا يوجد ملف لإصدار اللعبة هذا</string>
<string name="input_reset_positions">إعادة تعيين المواضع</string>
@@ -4057,6 +4057,7 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se encontraron complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Най-изтегляни</string>
<string name="addons_category_all">Всички категории</string>
<string name="addons_none_found">Няма намерени добавки</string>
<string name="addons_curse_busy">Първо затворете CurseForge</string>
<string name="addons_unreachable">Няма връзка с %1$s</string>
<string name="addons_no_file">Няма файл за тази версия на играта</string>
<string name="input_reset_positions">Нулиране на позициите</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Nejstahovanější</string>
<string name="addons_category_all">Všechny kategorie</string>
<string name="addons_none_found">Nenalezeny žádné doplňky</string>
<string name="addons_curse_busy">Nejprve zavřete CurseForge</string>
<string name="addons_unreachable">Nelze se připojit k %1$s</string>
<string name="addons_no_file">Pro tuto verzi hry není k dispozici soubor</string>
<string name="input_reset_positions">Obnovit pozice</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Mest downloadet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Ingen tilføjelser fundet</string>
<string name="addons_curse_busy">Luk CurseForge først</string>
<string name="addons_unreachable">Kunne ikke nå %1$s</string>
<string name="addons_no_file">Ingen fil til denne spilversion</string>
<string name="input_reset_positions">Nulstil placeringer</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Meistgeladen</string>
<string name="addons_category_all">Alle Kategorien</string>
<string name="addons_none_found">Keine Addons gefunden</string>
<string name="addons_curse_busy">Schließe zuerst CurseForge</string>
<string name="addons_unreachable">%1$s ist nicht erreichbar</string>
<string name="addons_no_file">Keine Datei für diese Spielversion</string>
<string name="input_reset_positions">Positionen zurücksetzen</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Περισσότερες λήψεις</string>
<string name="addons_category_all">Όλες οι κατηγορίες</string>
<string name="addons_none_found">Δεν βρέθηκαν πρόσθετα</string>
<string name="addons_curse_busy">Κλείστε πρώτα το CurseForge</string>
<string name="addons_unreachable">Δεν ήταν δυνατή η σύνδεση με %1$s</string>
<string name="addons_no_file">Δεν υπάρχει αρχείο για αυτή την έκδοση του παιχνιδιού</string>
<string name="input_reset_positions">Επαναφορά θέσεων</string>
+1
View File
@@ -4057,6 +4057,7 @@
<string name="addons_sort_downloads">Más descargados</string>
<string name="addons_category_all">Todas las categorías</string>
<string name="addons_none_found">No se han encontrado complementos</string>
<string name="addons_curse_busy">Cierra CurseForge primero</string>
<string name="addons_unreachable">No se pudo conectar con %1$s</string>
<string name="addons_no_file">No hay ningún archivo para esta versión del juego</string>
<string name="input_reset_positions">Restablecer posiciones</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Ladatuimmat</string>
<string name="addons_category_all">Kaikki luokat</string>
<string name="addons_none_found">Lisäosia ei löytynyt</string>
<string name="addons_curse_busy">Sulje CurseForge ensin</string>
<string name="addons_unreachable">Yhteyttä palveluun %1$s ei saatu</string>
<string name="addons_no_file">Tälle peliversiolle ei ole tiedostoa</string>
<string name="input_reset_positions">Palauta sijainnit</string>
+1
View File
@@ -4056,6 +4056,7 @@
<string name="addons_sort_downloads">Les plus téléchargés</string>
<string name="addons_category_all">Toutes les catégories</string>
<string name="addons_none_found">Aucun addon trouvé</string>
<string name="addons_curse_busy">Fermez d\'abord CurseForge</string>
<string name="addons_unreachable">Impossible de joindre %1$s</string>
<string name="addons_no_file">Aucun fichier pour cette version du jeu</string>
<string name="input_reset_positions">Réinitialiser les positions</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">सबसे ज़्यादा डाउनलोड</string>
<string name="addons_category_all">सभी श्रेणियाँ</string>
<string name="addons_none_found">कोई ऐडऑन नहीं मिला</string>
<string name="addons_curse_busy">पहले CurseForge बंद करें</string>
<string name="addons_unreachable">%1$s तक नहीं पहुँच सके</string>
<string name="addons_no_file">गेम के इस संस्करण के लिए कोई फ़ाइल नहीं है</string>
<string name="input_reset_positions">स्थितियाँ रीसेट करें</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Legtöbbet letöltött</string>
<string name="addons_category_all">Minden kategória</string>
<string name="addons_none_found">Nem található kiegészítő</string>
<string name="addons_curse_busy">Előbb zárd be a CurseForge-ot</string>
<string name="addons_unreachable">A(z) %1$s nem érhető el</string>
<string name="addons_no_file">Nincs fájl ehhez a játékverzióhoz</string>
<string name="input_reset_positions">Pozíciók visszaállítása</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">Paling banyak diunduh</string>
<string name="addons_category_all">Semua kategori</string>
<string name="addons_none_found">Tidak ada addon ditemukan</string>
<string name="addons_curse_busy">Tutup CurseForge terlebih dahulu</string>
<string name="addons_unreachable">Tidak dapat menjangkau %1$s</string>
<string name="addons_no_file">Tidak ada file untuk versi game ini</string>
<string name="input_reset_positions">Atur ulang posisi</string>
+1
View File
@@ -4056,6 +4056,7 @@
<string name="addons_sort_downloads">Più scaricati</string>
<string name="addons_category_all">Tutte le categorie</string>
<string name="addons_none_found">Nessun addon trovato</string>
<string name="addons_curse_busy">Chiudi prima CurseForge</string>
<string name="addons_unreachable">Impossibile raggiungere %1$s</string>
<string name="addons_no_file">Nessun file per questa versione del gioco</string>
<string name="input_reset_positions">Ripristina posizioni</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">ダウンロード数順</string>
<string name="addons_category_all">すべてのカテゴリ</string>
<string name="addons_none_found">アドオンが見つかりません</string>
<string name="addons_curse_busy">先に CurseForge を閉じてください</string>
<string name="addons_unreachable">%1$s に接続できませんでした</string>
<string name="addons_no_file">このゲームバージョン用のファイルがありません</string>
<string name="input_reset_positions">位置をリセット</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">다운로드 많은 순</string>
<string name="addons_category_all">모든 카테고리</string>
<string name="addons_none_found">애드온을 찾을 수 없음</string>
<string name="addons_curse_busy">먼저 CurseForge를 닫으세요</string>
<string name="addons_unreachable">%1$s에 연결할 수 없습니다</string>
<string name="addons_no_file">이 게임 버전용 파일이 없습니다</string>
<string name="input_reset_positions">위치 초기화</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">Paling banyak dimuat turun</string>
<string name="addons_category_all">Semua kategori</string>
<string name="addons_none_found">Tiada addon ditemui</string>
<string name="addons_curse_busy">Tutup CurseForge dahulu</string>
<string name="addons_unreachable">Tidak dapat mencapai %1$s</string>
<string name="addons_no_file">Tiada fail untuk versi permainan ini</string>
<string name="input_reset_positions">Tetapkan semula kedudukan</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Mest nedlastet</string>
<string name="addons_category_all">Alle kategorier</string>
<string name="addons_none_found">Fant ingen tillegg</string>
<string name="addons_curse_busy">Lukk CurseForge først</string>
<string name="addons_unreachable">Fikk ikke kontakt med %1$s</string>
<string name="addons_no_file">Ingen fil for denne spillversjonen</string>
<string name="input_reset_positions">Tilbakestill plasseringer</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Meest gedownload</string>
<string name="addons_category_all">Alle categorieën</string>
<string name="addons_none_found">Geen add-ons gevonden</string>
<string name="addons_curse_busy">Sluit eerst CurseForge</string>
<string name="addons_unreachable">Kan %1$s niet bereiken</string>
<string name="addons_no_file">Geen bestand voor deze gameversie</string>
<string name="input_reset_positions">Posities herstellen</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Najczęściej pobierane</string>
<string name="addons_category_all">Wszystkie kategorie</string>
<string name="addons_none_found">Nie znaleziono dodatków</string>
<string name="addons_curse_busy">Najpierw zamknij CurseForge</string>
<string name="addons_unreachable">Nie można połączyć się z %1$s</string>
<string name="addons_no_file">Brak pliku dla tej wersji gry</string>
<string name="input_reset_positions">Resetuj położenie</string>
@@ -4070,6 +4070,7 @@
<string name="addons_sort_downloads">Mais transferidos</string>
<string name="addons_category_all">Todas as categorias</string>
<string name="addons_none_found">Nenhum addon encontrado</string>
<string name="addons_curse_busy">Feche primeiro o CurseForge</string>
<string name="addons_unreachable">Não foi possível contactar %1$s</string>
<string name="addons_no_file">Não há ficheiro para esta versão do jogo</string>
<string name="input_reset_positions">Repor posições</string>
+1
View File
@@ -4078,6 +4078,7 @@
<string name="addons_sort_downloads">Mais baixados</string>
<string name="addons_category_all">Todas as categorias</string>
<string name="addons_none_found">Nenhum addon encontrado</string>
<string name="addons_curse_busy">Feche o CurseForge primeiro</string>
<string name="addons_unreachable">Não foi possível acessar %1$s</string>
<string name="addons_no_file">Não há arquivo para esta versão do jogo</string>
<string name="input_reset_positions">Redefinir posições</string>
+1
View File
@@ -4057,6 +4057,7 @@
<string name="addons_sort_downloads">Cele mai descărcate</string>
<string name="addons_category_all">Toate categoriile</string>
<string name="addons_none_found">Nu s-au găsit suplimente</string>
<string name="addons_curse_busy">Închide mai întâi CurseForge</string>
<string name="addons_unreachable">Nu s-a putut accesa %1$s</string>
<string name="addons_no_file">Nu există fișier pentru această versiune a jocului</string>
<string name="input_reset_positions">Resetează pozițiile</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Самые скачиваемые</string>
<string name="addons_category_all">Все категории</string>
<string name="addons_none_found">Аддоны не найдены</string>
<string name="addons_curse_busy">Сначала закройте CurseForge</string>
<string name="addons_unreachable">Не удалось подключиться к %1$s</string>
<string name="addons_no_file">Нет файла для этой версии игры</string>
<string name="input_reset_positions">Сбросить положение</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">Mest nedladdade</string>
<string name="addons_category_all">Alla kategorier</string>
<string name="addons_none_found">Inga tillägg hittades</string>
<string name="addons_curse_busy">Stäng CurseForge först</string>
<string name="addons_unreachable">Kunde inte nå %1$s</string>
<string name="addons_no_file">Ingen fil för den här spelversionen</string>
<string name="input_reset_positions">Återställ positioner</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">ดาวน์โหลดมากที่สุด</string>
<string name="addons_category_all">ทุกหมวดหมู่</string>
<string name="addons_none_found">ไม่พบแอดออน</string>
<string name="addons_curse_busy">ปิด CurseForge ก่อน</string>
<string name="addons_unreachable">ไม่สามารถเชื่อมต่อ %1$s ได้</string>
<string name="addons_no_file">ไม่มีไฟล์สำหรับเกมเวอร์ชันนี้</string>
<string name="input_reset_positions">รีเซ็ตตำแหน่ง</string>
+1
View File
@@ -4017,6 +4017,7 @@
<string name="addons_sort_downloads">En çok indirilen</string>
<string name="addons_category_all">Tüm kategoriler</string>
<string name="addons_none_found">Eklenti bulunamadı</string>
<string name="addons_curse_busy">Önce CurseForge\'u kapatın</string>
<string name="addons_unreachable">%1$s adresine ulaşılamadı</string>
<string name="addons_no_file">Bu oyun sürümü için dosya yok</string>
<string name="input_reset_positions">Konumları sıfırla</string>
+1
View File
@@ -4097,6 +4097,7 @@
<string name="addons_sort_downloads">Найбільше завантажень</string>
<string name="addons_category_all">Усі категорії</string>
<string name="addons_none_found">Аддонів не знайдено</string>
<string name="addons_curse_busy">Спочатку закрийте CurseForge</string>
<string name="addons_unreachable">Не вдалося під’єднатися до %1$s</string>
<string name="addons_no_file">Немає файлу для цієї версії гри</string>
<string name="input_reset_positions">Скинути розташування</string>
+1
View File
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">Tải nhiều nhất</string>
<string name="addons_category_all">Tất cả danh mục</string>
<string name="addons_none_found">Không tìm thấy addon</string>
<string name="addons_curse_busy">Hãy đóng CurseForge trước</string>
<string name="addons_unreachable">Không thể kết nối tới %1$s</string>
<string name="addons_no_file">Không có tệp cho phiên bản trò chơi này</string>
<string name="input_reset_positions">Đặt lại vị trí</string>
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">下载最多</string>
<string name="addons_category_all">所有类别</string>
<string name="addons_none_found">未找到插件</string>
<string name="addons_curse_busy">请先关闭 CurseForge</string>
<string name="addons_unreachable">无法连接到 %1$s</string>
<string name="addons_no_file">没有适用于此游戏版本的文件</string>
<string name="input_reset_positions">重置位置</string>
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">下載最多</string>
<string name="addons_category_all">所有類別</string>
<string name="addons_none_found">找不到插件</string>
<string name="addons_curse_busy">請先關閉 CurseForge</string>
<string name="addons_unreachable">無法連接 %1$s</string>
<string name="addons_no_file">沒有適用於此遊戲版本的檔案</string>
<string name="input_reset_positions">重設位置</string>
@@ -3987,6 +3987,7 @@
<string name="addons_sort_downloads">下載最多</string>
<string name="addons_category_all">所有類別</string>
<string name="addons_none_found">找不到插件</string>
<string name="addons_curse_busy">請先關閉 CurseForge</string>
<string name="addons_unreachable">無法連線至 %1$s</string>
<string name="addons_no_file">沒有適用於此遊戲版本的檔案</string>
<string name="input_reset_positions">重設位置</string>
+1
View File
@@ -4202,6 +4202,7 @@
<string name="addons_sort_downloads">Most downloaded</string>
<string name="addons_category_all">All categories</string>
<string name="addons_none_found">No addons found</string>
<string name="addons_curse_busy">Close CurseForge first</string>
<string name="addons_unreachable">Could not reach %1$s</string>
<string name="addons_no_file">No file for this game version</string>
<string name="addons_source_wowi" translatable="false">WoWInterface</string>
@@ -0,0 +1,161 @@
package com.droiddeck.launcher.runtime
import android.app.Application
import org.json.JSONArray
import org.json.JSONObject
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
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE, application = Application::class)
class CurseForgeAppTest {
@get:Rule val temp = TemporaryFolder()
private val search = """{"success":true,"injectedCount":0,
"pagination":{"index":0,"pageSize":20,"resultCount":20,"totalCount":150},
"mods":[
{"id":486246,"name":"RestedXP Guide","summary":"Leveling guide","downloads":12345678,
"thumbnailUrl":"https://media.forgecdn.net/avatars/rxp.png","authors":[{"name":"RestedXP"}],
"updateVersion":{"id":7,"filename":"RXPGuides.zip","fileDate":"2026-11-20T10:00:00.000Z"}},
{"id":2,"name":"Plain","downloads":5,"thumbnailUrl":"http://insecure/x.png","primaryAuthor":{"name":"Main"},
"authors":[{"name":"Other"}],"projectLatestReleaseDate":"2026-01-01T00:00:00Z"},
{"id":0,"name":"No id"},
{"id":3,"name":""}
]}"""
@Test
fun searchResultsBecomeCatalogEntries() {
val page = CurseForgeApp.parseSearch(JSONObject(search))
assertEquals(listOf("486246", "2"), page.items.map { it.id })
val rxp = page.items[0]
assertEquals("RestedXP Guide", rxp.name)
assertEquals("RestedXP", rxp.author)
assertEquals(12345678L, rxp.downloads)
assertEquals(java.time.Instant.parse("2026-11-20T10:00:00Z").toEpochMilli(), rxp.updated)
assertEquals("https://media.forgecdn.net/avatars/rxp.png", rxp.thumb)
assertEquals("Main", page.items[1].author)
assertNull(page.items[1].thumb)
assertTrue(page.more)
}
@Test
fun theLastPageHasNoMore() {
val last = JSONObject(search).put("pagination", JSONObject("""{"index":140,"resultCount":10,"totalCount":150}"""))
assertFalse(CurseForgeApp.parseSearch(last).more)
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(JSONObject("""{"success":false}""")) }
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.parseSearch(null) }
}
@Test
fun searchRequestsUseTheInstanceAndOneBasedPages() {
val request = CurseForgeApp.searchRequest("guid-1", " Rested ", WowAddonCatalog.Sort.NAME, 0)
assertEquals(1, request.getInt("gameId"))
assertEquals("Rested", request.getString("searchText"))
assertEquals(1, request.getInt("page"))
assertEquals(1, request.getInt("sortColumn"))
assertEquals(1, request.getInt("sortOrder"))
assertEquals("guid-1", request.getString("gameInstanceGuid"))
assertEquals(2, CurseForgeApp.searchRequest("g", "", WowAddonCatalog.Sort.DOWNLOADS, 1).getInt("page"))
assertEquals(WowAddonCatalog.Sort.entries.size, WowAddonCatalog.Sort.entries.map(CurseForgeApp::sortOf).toSet().size)
}
@Test
fun installRequestsInstallTheLatestFileIntoTheInstance() {
val request = CurseForgeApp.installRequest("guid-1", "486246")
assertEquals("guid-1", request.getString("instanceId"))
assertEquals(486246L, request.getLong("projectId"))
assertTrue(request.getBoolean("installLatestFile"))
}
@Test
fun theInstanceIsPickedByItsFlavorFolder() {
val instances = JSONArray("""[
{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"},
{"guid":"forever","installPath":"/root/Games/WoW/_forever_/"}
]""")
assertEquals("forever", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_forever_", "retail"))
assertEquals("retail", CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_retail_", null))
assertNull(CurseForgeApp.instanceFor(instances, "/root/Games/WoW/_classic_", "retail"))
val single = JSONArray("""[{"guid":"retail","installPath":"/root/Games/WoW/_retail_/"}]""")
assertNull(CurseForgeApp.instanceFor(single, "/root/Games/WoW/_classic_", "retail"))
assertEquals("retail", CurseForgeApp.instanceFor(single, "/root/Games/WoW/_retail_", "other"))
assertEquals("only", CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", "only"))
assertEquals("only", CurseForgeApp.instanceFor(null, "/x/_forever_", "only"))
assertNull(CurseForgeApp.instanceFor(JSONArray(), "/x/_forever_", ""))
}
@Test
fun answersAreUnwrapped() {
val ok = JSONObject().put("ok", true).put("value", """{"value":{"resultStatus":3,"gameInstanceGuid":"g"}}""")
assertEquals("g", (CurseForgeApp.unwrap(ok) as JSONObject).getString("gameInstanceGuid"))
assertEquals(true, CurseForgeApp.unwrap(JSONObject().put("ok", true).put("value", """{"value":true}""")))
val missing = JSONObject().put("ok", true).put("value", """{"missing":true}""")
assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(missing) }
val failed = JSONObject().put("ok", false).put("error", JSONObject().put("code", "NO_TARGET").put("message", "no node"))
val failure = assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(failed) }
assertEquals("no node", failure.message)
assertEquals("NO_TARGET", failure.code)
assertFalse(failure.gone)
val lost = JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "refused"))
assertTrue(assertThrows(CurseForgeApp.Failure::class.java) { CurseForgeApp.unwrap(lost) }.gone)
}
@Test
fun expressionsDriveTheHiddenDesktopWindow() {
val text = CurseForgeApp.expression("ProjectAppService", "search", JSONArray().put(JSONObject().put("searchText", "it's \"x\"")))
assertTrue(text.startsWith("(() => { const w = require('electron').BrowserWindow.getAllWindows()"))
assertTrue(text.contains("desktop.html"))
assertTrue(text.contains("executeJavaScript("))
assertFalse(text.contains("show()"))
val probe = CurseForgeApp.expression("InstalledProjectsAppService", "installAddon", null)
assertFalse(probe.contains("await s["))
val connect = CurseForgeApp.expression("CoreService", "connect", JSONArray(), "r => true")
assertTrue(connect.contains("(r => true)(await s[\\\"connect\\\"](...[]))"))
}
@Test
fun installedIdsAndExitCodes() {
assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]""")))
assertEquals(emptySet<String>(), 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(5))
}
@Test
fun onlyASecretInspectorUrlIsTaken() {
val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
assertEquals(url, CurseForgeApp.inspectorUrl("noise\n$url\n"))
assertNull(CurseForgeApp.inspectorUrl("ready\n"))
assertNull(CurseForgeApp.inspectorUrl("ws://127.0.0.1:9229/\n"))
assertNull(CurseForgeApp.inspectorUrl("ws://10.0.0.2:43117/0f8fad5b-d9cb-469f-a165-70867728950e"))
assertNull(CurseForgeApp.inspectorUrl("$url/json"))
}
@Test
fun theWowRootIsTheParentOfEveryFlavor() {
val root = temp.newFolder("World of Warcraft")
for (flavor in listOf("_classic_", "_classic_era_")) {
File(root, "$flavor/Interface/AddOns").mkdirs()
File(root, "$flavor/.flavor.info").writeText("x")
}
val title = BattleNet.TITLES.first { it.flavor == "_classic_" }
val targets = WowAddons.targets(title, File(root, "_classic_"))
assertEquals(listOf("_classic_", "_classic_era_"), targets.map { it.flavor }.sorted())
for (target in targets) {
assertEquals(root, WowAddons.root(target))
assertEquals(File(root, target.flavor), WowAddons.flavorDir(target))
}
}
}
@@ -432,7 +432,7 @@ class FocusWatcher(threading.Thread):
class WebSocket:
def __init__(self, url, timeout):
def __init__(self, url, timeout, bounded=False):
target = urllib.parse.urlsplit(url)
if (target.scheme != "ws" or target.hostname not in ("127.0.0.1", "::1", "localhost")
or target.username is not None or target.password is not None or target.fragment):
@@ -442,6 +442,7 @@ class WebSocket:
if target.query:
path += "?" + target.query
host = "127.0.0.1" if target.hostname == "localhost" else target.hostname
self.deadline = time.monotonic() + timeout if bounded else None
self.s = socket.create_connection((host, target.port or 80), timeout=timeout)
try:
self._handshake(path, hostport)
@@ -457,6 +458,7 @@ class WebSocket:
).encode())
head = b""
while b"\r\n\r\n" not in head:
self._wait()
chunk = self.s.recv(4096)
if not chunk:
raise OSError("DevTools closed the connection during the handshake")
@@ -468,8 +470,17 @@ class WebSocket:
raise OSError("DevTools refused the WebSocket: " + status.decode(errors="replace"))
self.buffer = head.split(b"\r\n\r\n", 1)[1]
def _wait(self):
if self.deadline is None:
return
left = self.deadline - time.monotonic()
if left <= 0:
raise socket.timeout("DevTools did not answer in time")
self.s.settimeout(left)
def _read(self, n):
while len(self.buffer) < n:
self._wait()
chunk = self.s.recv(65536)
if not chunk:
raise OSError("DevTools closed the connection")
@@ -547,22 +558,51 @@ def cdp_targets(agent_dir, timeout=5):
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach the client's DevTools at %s: %s" % (url, e))
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15):
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
ws = WebSocket(match[0]["webSocketDebuggerUrl"], timeout)
INSPECTOR_URL = re.compile(r"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}")
def inspector_url(url):
found = INSPECTOR_URL.fullmatch(url) if isinstance(url, str) else None
if not found or not 1024 <= int(found.group(1)) <= 65535:
raise AgentError("INVALID_REQUEST", "inspector must be a ws://127.0.0.1 inspector URL with its session id")
return url
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
command_line_api=False):
if inspector is not None:
url, name = inspector_url(inspector), "inspector"
else:
targets = [t for t in cdp_targets(agent_dir) if t.get("webSocketDebuggerUrl")]
want = target or "SharedJSContext"
match = [t for t in targets if want in (t.get("title") or "") or want in (t.get("url") or "")]
if not match:
names = ", ".join(sorted({t.get("title") or t.get("url") or "?" for t in targets}))
raise AgentError("NO_TARGET", "No DevTools target matches '%s' (have: %s)" % (want, names))
url, name = match[0]["webSocketDebuggerUrl"], match[0].get("title")
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True,
}}))
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
message = json.loads(ws.recv())
ws = WebSocket(url, timeout, bounded=True)
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "Could not reach DevTools: %s" % e)
try:
try:
ws.send(json.dumps({"id": 1, "method": "Runtime.evaluate", "params": {
"expression": expression, "returnByValue": True, "awaitPromise": await_promise,
"userGesture": True, "includeCommandLineAPI": command_line_api,
}}))
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
while True:
try:
message = json.loads(ws.recv())
except socket.timeout:
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
except OSError as e:
raise AgentError("DEVTOOLS_UNREACHABLE", "DevTools went away: %s" % e)
if message.get("id") != 1:
continue
if "error" in message:
@@ -573,9 +613,8 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
text = (details.get("exception") or {}).get("description") or details.get("text") or "exception"
raise AgentError("JS_EXCEPTION", text)
value = result.get("result", {})
return {"target": match[0].get("title"), "type": value.get("type"),
return {"target": name, "type": value.get("type"),
"value": value.get("value"), "description": value.get("description")}
raise AgentError("TIMEOUT", "No answer from DevTools in %ss" % timeout)
finally:
ws.close()
@@ -1157,7 +1196,7 @@ def handle(agent_dir, req):
if not isinstance(expression, str) or not expression:
raise AgentError("INVALID_REQUEST", "cdp eval needs an expression")
return cdp_eval(agent_dir, expression, req.get("target"), bool(req.get("awaitPromise", True)),
request_timeout(req, 15))
request_timeout(req, 15), req.get("inspector"), req.get("commandLineApi") is True)
if kind == "steam-selection":
return steam_selection(agent_dir, request_timeout(req, 5))
if kind == "quit":
+150
View File
@@ -0,0 +1,150 @@
#!/bin/bash
set -u
umask 077
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}
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 <imported AppImage directory>" >&2; exit 2 ;; esac
if [ "$cmd" != display ] && [ ! -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
tr '\0' '\n' 2>/dev/null < "$p/cmdline" | grep -qF -- "$dir/app/" && return 0
done
return 1
}
started_at() {
local stat
stat=$(cat "/proc/$1/stat" 2>/dev/null) || return 1
stat=${stat##*) }
set -- $stat
echo "${20}"
}
tracked() {
local pid at launched
read -r pid at launched 2>/dev/null < "$state/pid" || return 1
case $pid in ''|*[!0-9]*) return 1 ;; esac
kill -0 "$pid" 2>/dev/null && [ "$(started_at "$pid")" = "$at" ] || return 1
printf '%s %s\n' "$pid" "$launched"
}
ours() {
local pid launched
read -r pid launched <<<"$(tracked)"
[ -n "$pid" ] && [ "$launched" = "$dir" ] && echo "$pid"
}
lock() {
mkdir -p "$state" && chmod 700 "$state" || return 1
exec 9>"$state/lock" || return 1
flock 9
}
inspector() {
grep -aom1 'ws://127\.0\.0\.1:[0-9]*/[0-9a-f]\{8\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{4\}-[0-9a-f]\{12\}' "$state/log" 2>/dev/null
}
start() {
local shown display auth url pid
lock || { echo "droiddeck-curseforge: cannot lock $state" >&2; return 5; }
if ! ours >/dev/null; then
if tracked >/dev/null || running; then
exec 9>&-
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" </dev/null >"$state/log" 2>&1 9>&- &
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"
return 0
fi
ours >/dev/null || break
sleep 0.5
done
tail -n 20 "$state/log" >&2
return 5
}
stop() {
local pid p
lock || return 1
pid=$(ours) || { tracked >/dev/null || rm -f "$state/pid"; exec 9>&-; return 0; }
kill -TERM -- "-$pid" 2>/dev/null
for _ in $(seq 1 20); do
kill -0 -- "-$pid" 2>/dev/null || break
sleep 0.5
done
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
rm -f "$state/pid"
exec 9>&-
return 0
}
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
;;
esac
+173
View File
@@ -0,0 +1,173 @@
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"
URL = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
class CurseForgeHelperTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.proc = self.tmp / "proc"
self.proc.mkdir()
self.dir = self.tmp / "curseforge"
(self.dir / "app").mkdir(parents=True)
self.state = self.tmp / "state"
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"
"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"
% (shlex.quote(str(self.seen)), shlex.quote(str(self.proc)), shlex.quote(str(self.proc)), URL))
self.runner.chmod(0o755)
def fake(self, pid, *argv):
d = self.proc / str(pid)
d.mkdir()
(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.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 stop(self):
self.run_helper("stop", str(self.dir))
def pid(self):
return int((self.state / "pid").read_text().split()[0])
def gone(self, pid):
for _ in range(50):
try:
os.kill(pid, 0)
except ProcessLookupError:
return True
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"})
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))
self.addCleanup(self.stop)
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual(URL, out.stdout.strip())
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(0o700, self.state.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()
self.stop()
self.assertFalse((self.state / "pid").exists())
self.assertTrue(self.gone(pid), "the started instance 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):
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(3, out.returncode)
self.assertEqual("busy", out.stdout.strip())
pid = self.pid()
self.run_helper("stop", str(other))
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_stop_without_a_launch_is_quiet(self):
out = self.run_helper("stop", str(self.dir))
self.assertEqual(0, out.returncode)
self.assertEqual("", out.stderr)
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)
if __name__ == "__main__":
unittest.main()
+33
View File
@@ -348,6 +348,23 @@ class AgentTest(unittest.TestCase):
self.assertEqual("INVALID_TARGET", caught.exception.code)
connect.assert_not_called()
def test_a_devtools_endpoint_lost_while_sending_is_reported_as_gone(self):
class Lost:
def __init__(self, *args, **kwargs):
pass
def send(self, text):
raise BrokenPipeError("closed")
def close(self):
pass
with patch.object(agent, "WebSocket", Lost), patch.object(
agent, "cdp_targets", return_value=[{"title": "SharedJSContext", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]):
with self.assertRaises(agent.AgentError) as caught:
agent.cdp_eval(str(self.dir), "1")
self.assertEqual("DEVTOOLS_UNREACHABLE", caught.exception.code)
def test_cdp_without_a_port(self):
os.environ.pop("DD_CDP_PORT", None)
self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"])
@@ -368,6 +385,22 @@ class AgentTest(unittest.TestCase):
missing = self.ask({"kind": "cdp", "expression": "1", "target": "Nope"})
self.assertEqual("NO_TARGET", missing["error"]["code"])
def test_cdp_eval_on_a_secret_inspector_url(self):
server = FakeDevTools({"result": {"result": {"type": "string", "value": "ok"}}})
server.start()
self.addCleanup(server.server.close)
os.environ.pop("DD_CDP_PORT", None)
url = "ws://127.0.0.1:%d/0f8fad5b-d9cb-469f-a165-70867728950e" % server.port
answer = self.ask({"kind": "cdp", "expression": "require('electron')", "inspector": url, "commandLineApi": True})
self.assertTrue(answer["ok"], answer)
self.assertEqual("inspector", answer["target"])
self.assertTrue(server.seen[0]["params"]["includeCommandLineAPI"])
def test_cdp_refuses_inspector_urls_without_a_session_id(self):
for url in ("ws://127.0.0.1:9229/", "ws://127.0.0.1:9229/json/list", "ws://10.0.0.2:9229/0f8fad5b-d9cb-469f-a165-70867728950e",
"ws://127.0.0.1:80/0f8fad5b-d9cb-469f-a165-70867728950e", "ws://127.0.0.1:9229/0f8fad5b-d9cb-469f-a165-70867728950e/x", 9229):
self.assertEqual("INVALID_REQUEST", self.ask({"kind": "cdp", "expression": "1", "inspector": url})["error"]["code"])
def test_steam_selection(self):
with patch.object(agent, "cdp_eval", return_value={"value": "3180310"}) as evaluate:
answer = self.ask({"kind": "steam-selection"})
+7 -3
View File
@@ -43,11 +43,15 @@ 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("DriverSetupLog.write", start)]
block = text[start:text.index("CompositorHost.start(", start)]
request = block[block.index("nativeSetHdrRequest("):block.index("Log.i", block.index("nativeSetHdrRequest("))]
self.assertNotIn("SessionPrefs.hdr", block[:block.index("if (!SessionState.running)")])
self.assertNotIn("SessionPrefs.hdr", block)
self.assertIn("capable, false", request)
self.assertIn("SessionState.hdrCapable && SessionPrefs.hdr(this, mode)", block)
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)
def test_both_switches_apply_to_the_running_session(self):
helper = (APP / "session/SessionHdr.kt").read_text()