Compare commits

..
98 changed files with 269 additions and 1610 deletions

No files matched your search

-1
View File
@@ -955,7 +955,6 @@ jobs:
with:
artifact: droiddeck-signed
variant: standard
fail_on_detection: true
secrets: inherit
packs:
@@ -191,6 +191,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var gamescopeRealtime by mutableStateOf(false)
private var paceCores by mutableStateOf(true)
private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var desktopAsUser by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
@@ -3122,7 +3125,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
nativeDesktopAvailable = com.droiddeck.launcher.runtime.NativeGuest.nextSession(this), desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, nativeUserland = nativeUserland, desktopAsUser = desktopAsUser, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
onPaceCores = { on -> SessionPrefs.setPaceCores(this, on); paceCores = on },
@@ -3136,6 +3139,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onNativeUserland = { on -> SessionPrefs.setNativeUserland(this, on); nativeUserland = on },
onDesktopAsUser = { on -> SessionPrefs.setDesktopAsUser(this, on); desktopAsUser = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) },
@@ -3458,6 +3464,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
paceCores = SessionPrefs.paceCores(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
nativeUserland = SessionPrefs.nativeUserland(this)
desktopAsUser = SessionPrefs.desktopAsUser(this)
cursorComposite = SessionPrefs.cursorComposite(this)
guestHostname = SessionPrefs.guestHostname(this)
@@ -3862,6 +3862,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
presentationFaultHint()?.let { return it }
if (log == null || !log.isFile) return null
return try {
var enosys = 0
var fexMissing = false
val size = log.length()
val text = java.io.RandomAccessFile(log, "r").use { f ->
@@ -3872,6 +3873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
String(bytes, Charsets.ISO_8859_1)
}
text.lineSequence().forEach { line ->
if (line.contains("Function not implemented")) enosys++
if (line.contains(FEX_MISSING)) fexMissing = true
}
val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence())
@@ -3893,6 +3895,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (fexMissing) {
val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program)
EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true)
} else if (enosys >= 8) {
EndHint(resources.getQuantityString(R.plurals.session_hint_enosys, enosys, enosys,
getString(R.string.perf_title), getString(R.string.perf_seccomp), getString(R.string.perf_xalia)))
} else null
} catch (e: Exception) {
null
@@ -571,6 +571,7 @@ object AgentHost {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -14,6 +14,8 @@ object AgentNative {
fun run(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.session.SessionFiles.stage(context, root)
// with the setting off, staging leaves the rootfs as proot wants it
if (!com.droiddeck.launcher.session.SessionPrefs.nativeUserland(context)) NativeGuest.prepare(context, root)
if (!NativeGuest.available(root)) throw AgentException("NATIVE_UNAVAILABLE", "The rootfs has no native hook or glibc loader yet; start a session once")
val argvJson = request.optJSONArray("argv") ?: throw AgentException("INVALID_REQUEST", "argv is required")
val argv = (0 until argvJson.length()).map { argvJson.getString(it) }
@@ -291,12 +291,9 @@ object DeviceReport {
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("pace cores", SessionPrefs.paceCores(context))
k("guest runtime policy", "native preferred with PRoot fallback")
k("guest runtime", when (com.droiddeck.launcher.runtime.NativeGuest.sessionMode) {
true -> "native"
false -> "PRoot"
null -> if (com.droiddeck.launcher.runtime.NativeGuest.enabled(context)) "native available" else "native unavailable"
})
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("native userland (no proot)", SessionPrefs.nativeUserland(context))
k("proot fast path", SessionPrefs.prootFastPath(context))
k("proot binary", LinuxRuntime.prootSource(context) + " " + LinuxRuntime.prootBinary(context).path)
k("proot fast path (eligible)", com.droiddeck.launcher.runtime.ProotFastPath.enabled(context))
k("Guest host name", SessionPrefs.guestHostname(context))
@@ -28,8 +28,7 @@ object AutoComponents {
else -> game.appId.takeIf { it > 0 }?.toString()
}
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>,
user: Map<String, Boolean> = emptyMap()): Map<String, WinComponents.AutoReason> {
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
val out = LinkedHashMap<String, WinComponents.AutoReason>()
for (f in findings) {
if (!f.auto || f.component == null) continue
@@ -38,13 +37,6 @@ object AutoComponents {
if (WinComponents.support(c, catalog) != WinComponents.Support.READY) continue
if (id !in out) out[id] = WinComponents.AutoReason(f.origin.name, listOf(f.original) + f.args)
}
if (user["d3dx9"] != false && (user["d3dx9"] == true || "d3dx9" in out)) {
val reason = out["d3dx9"] ?: WinComponents.AutoReason(WinCompSources.Origin.FOLDER.name, listOf("d3dx9"))
for (id in listOf("d3dcompiler_42", "d3dcompiler_43")) {
val c = catalog[id] ?: continue
if (WinComponents.support(c, catalog) == WinComponents.Support.READY) out.putIfAbsent(id, reason)
}
}
return out
}
@@ -236,8 +228,8 @@ object AutoComponents {
val findings = findings(context, game)
val refreshed = if (knownCatalog == null && asked && online(context)) catalogOf(context, true) else null
val catalog = knownCatalog ?: (refreshed ?: catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val wanted = autoPicks(findings, catalog)
val user = WinComponents.selection(context, key).user
val wanted = autoPicks(findings, catalog, user)
val before = WinComponents.selection(context, key).auto
val installed = installedOf(context)
val kept = LinkedHashMap<String, WinComponents.AutoReason>()
@@ -381,7 +373,7 @@ object AutoComponents {
private const val FINDINGS = "wincomp-findings.json"
private const val DETECTORS = "d4"
private const val DETECTORS = "d3"
internal fun signature(context: Context, game: Library.SteamGame): String {
val folder = game.gameFiles
@@ -460,9 +452,9 @@ object AutoComponents {
}
return pendingSaved && pending.isEmpty()
}
val wanted = autoPicks(findings, catalog)
val selection = WinComponents.selection(context, key)
val user = selection.user
val wanted = autoPicks(findings, catalog, user)
val installed = installedOf(context)
val roots = selection.effective + wanted.keys.filter { user[it] != false }
val required = withParts(roots.filter { WinComponents.validId(it) }, catalog)
@@ -42,7 +42,6 @@ object DependencyDetector {
"dotnet45" to ".NET Framework 4.5", "dotnet452" to ".NET Framework 4.5.2",
"dotnet46" to ".NET Framework 4.6", "dotnet472" to ".NET Framework 4.7.2",
"dotnet48" to ".NET Framework 4.8", "dotnet35" to ".NET Framework 3.5",
"dotnetcoredesktop3" to ".NET Desktop 3", "dotnet50" to ".NET 5",
"dotnetcoredesktop6" to ".NET Desktop 6", "dotnetcoredesktop7" to ".NET Desktop 7",
"dotnetcoredesktop8" to ".NET Desktop 8",
)
@@ -51,7 +50,7 @@ object DependencyDetector {
"vcredist2005", "vcredist2008", "vcredist2010", "vcredist2012", "vcredist2013",
"vcredist2015", "vcredist2019", "vcredist2022",
"dotnet35", "dotnet40", "dotnet45", "dotnet452", "dotnet46", "dotnet472", "dotnet48",
"dotnetcoredesktop3", "dotnet50", "dotnetcoredesktop6", "dotnetcoredesktop7", "dotnetcoredesktop8",
"dotnetcoredesktop6", "dotnetcoredesktop7", "dotnetcoredesktop8",
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
)
@@ -149,7 +148,7 @@ object DependencyDetector {
val comp = dotnetComponent("$path $name")
return when {
comp != null -> listOf(comp)
isDir || CORE_RUNTIME.containsMatchIn(path) -> emptyList()
isDir -> emptyList()
else -> listOf("dotnet48")
}
}
@@ -173,20 +172,10 @@ object DependencyDetector {
private val D3DX11_RE = Regex("""d3dx11_\d+\.dll""")
private val D3DCOMPILER_RE = Regex("""d3dcompiler_\d+\.dll""")
private val CORE_RUNTIME = Regex("""(?:windowsdesktop|dotnet)-runtime-(\d+)\.""")
private val CORE_RUNTIMES = mapOf(
"3" to "dotnetcoredesktop3", "5" to "dotnet50", "6" to "dotnetcoredesktop6", "7" to "dotnetcoredesktop7", "8" to "dotnetcoredesktop8",
)
private fun dotnetComponent(s: String): String? {
CORE_RUNTIME.find(s)?.let { return CORE_RUNTIMES[it.groupValues[1]] }
return byVersion(s)
}
private fun byVersion(s: String): String? = when {
s.contains("desktop-runtime-8") || Regex("""(?<![\d.])8\.\d""").containsMatchIn(s) -> "dotnetcoredesktop8"
s.contains("desktop-runtime-7") || Regex("""(?<![\d.])7\.\d""").containsMatchIn(s) -> "dotnetcoredesktop7"
s.contains("desktop-runtime-6") || Regex("""(?<![\d.])6\.\d""").containsMatchIn(s) -> "dotnetcoredesktop6"
private fun dotnetComponent(s: String): String? = when {
s.contains("desktop-runtime-8") || Regex("""\b8\.\d""").containsMatchIn(s) -> "dotnetcoredesktop8"
s.contains("desktop-runtime-7") || Regex("""\b7\.\d""").containsMatchIn(s) -> "dotnetcoredesktop7"
s.contains("desktop-runtime-6") || Regex("""\b6\.\d""").containsMatchIn(s) -> "dotnetcoredesktop6"
s.contains("ndp48") || s.contains("fx48") || s.contains("4.8") -> "dotnet48"
s.contains("ndp472") || s.contains("4.7.2") -> "dotnet472"
s.contains("ndp46") || s.contains("4.6") -> "dotnet46"
@@ -40,8 +40,7 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
PILL("pill", "Pill"),
MINIMAL("minimal", "Minimal"),
MEGA("mega", "Mega"),
STRIP("strip", "Strip"),
SIDE_STRIP("side_strip", "Side strip");
STRIP("strip", "Strip");
fun next(): DroidDeckHudSize {
val all = values()
@@ -97,11 +96,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
"showCPUUsage", "showTemp", "showVram", "showRAM", "showBattery", "showBatteryTemp", "showBatteryTime",
"showPower", "showDisplay", "showHdr", "showGpuModel",
),
SIDE_STRIP to listOf(
"showFPS", "showFPSGraph", "showAvg", "showLow1",
"showGPULoad", "showGpuTemp", "showCPUUsage", "showTemp", "showRAM", "showVram",
"showPower", "showBattery", "showBatteryTemp", "showBatteryTime",
),
)
@@ -116,7 +110,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
MEGA to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.62f, pad = 10f, lineGap = 3.5f, labelGap = 7f,
band = 9.5f, gutter = 16f),
STRIP to DroidDeckHudStyle(row = 11.5f, unit = 11.5f * 0.8f, pad = 10f, lineGap = 0f, labelGap = 13f),
SIDE_STRIP to DroidDeckHudStyle(row = 11.5f, unit = 9f, pad = 8f, lineGap = 4f, labelGap = 4f, key = 9f),
)
fun rowsFor(size: DroidDeckHudSize, values: Map<String, String>): List<String> =
@@ -573,7 +573,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (s == null) { contentW = 0f; contentH = 0f; return }
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
if (size == DroidDeckHudSize.STRIP) { buildStrip(s); return }
if (size == DroidDeckHudSize.SIDE_STRIP) { buildSideStrip(s); return }
buildRows(s)
if (contentW <= 0f || contentH <= 0f) return
if (size == DroidDeckHudSize.PILL) addSubtleClock(sp(10f), leftAligned = true)
@@ -685,8 +684,8 @@ class DroidDeckHudView(context: Context) : View(context) {
finishPanel(panel, halfRound = halfRound)
}
private fun finishPanel(panel: RectF, halfRound: Boolean, maxRadius: Float = sp(56f), inset: Float = panelInset()) {
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, maxRadius)
private fun finishPanel(panel: RectF, halfRound: Boolean) {
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, sp(56f))
val margin = outlineWidth() + sp(4f)
fun curveIn(top: Float, bottom: Float): Float {
val d = max(max(panel.top + r - top, bottom - (panel.bottom - r)), 0f)
@@ -704,8 +703,8 @@ class DroidDeckHudView(context: Context) : View(context) {
for (t in tileRects) right = max(right, t.right + curveIn(t.top, t.bottom) + margin)
panel.right = max(right, panel.left + sp(6f) + r)
dPanel = panel; dRadius = r
contentW = panel.right + inset
contentH = panel.bottom + inset
contentW = panel.right + panelInset()
contentH = panel.bottom + panelInset()
}
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
@@ -937,58 +936,6 @@ class DroidDeckHudView(context: Context) : View(context) {
}
}
private fun buildSideStrip(s: HudMetrics.Snapshot) {
val style = size.style
val inset = sp(5f)
val panelWidth = sp(86f)
val pad = sp(style.pad)
val left = inset + pad
val right = inset + panelWidth - pad
val markHeight = sp(12f)
val markTop = inset + sp(6f)
val markLeft = left - DroidDeckMark.inkLeftFor(markHeight)
headerMark = RectF(markLeft, markTop, markLeft + DroidDeckMark.widthFor(markHeight), markTop + markHeight)
dDividerTop = markTop + markHeight + sp(6f)
if (showClockTime) {
val clock = clockTimeString()
val clockPx = sp(8.5f)
val clockWidth = measure(clock, clockPx)
if (right - clockWidth >= markLeft + DroidDeckMark.inkRightFor(markHeight) + sp(4f)) {
val baseline = markTop + (markHeight + capHeight(clockPx)) / 2f
glyphs.add(Glyph(right - clockWidth, baseline, clock, blend(colDim), clockPx))
}
}
val labelPx = sp(style.key)
val rowPx = sp(style.row)
val unitPx = sp(style.unit)
val lineGap = sp(style.lineGap)
var y = dDividerTop + sp(6f)
for (key in size.rowsIn(storedOrder)) {
if (!switchOn(key)) continue
if (key == "showFPSGraph") {
val height = sp(15f)
graphRect = RectF(left, y, right, y + height)
y += height + lineGap
continue
}
val valuePx = if (key == "showFPS") sp(16f) else rowPx
val row = reading(key, s, labelPx, valuePx, unitPx)
val available = right - left - measure(row.label.text, labelPx) - sp(style.labelGap)
val fit = (available / runWidth(row.vals)).coerceIn(0f, 1f)
val values = row.vals.map { Span(it.text, it.color, it.sizePx * fit, it.glow) }
val baseline = y - ascent(valuePx)
placeRun(left, baseline, listOf(row.label))
placeRun(right - runWidth(values), baseline, values)
y += lineH(valuePx) + lineGap
}
val panel = RectF(inset, inset, inset + panelWidth, y + sp(7f))
finishPanel(panel, halfRound = false, maxRadius = sp(11f), inset = inset)
}
private fun buildStrip(s: HudMetrics.Snapshot) {
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
val padX = sp(10f); val groupGap = sp(13f)
@@ -156,13 +156,7 @@ object InputLibraries {
update(context) { library ->
library.copy(layouts = library.layouts.map { layout ->
if (layout.id != layoutId || !layout.editable) layout
else {
fun updateSticks(elements: List<InputSurfaceElement>) = elements.map {
if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = it.hideStickAtRest, adaptiveCapture = on)
else it
}
layout.copy(elements = updateSticks(layout.elements), rotated = updateSticks(layout.rotated))
}
else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it })
})
}
}.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
@@ -334,8 +328,7 @@ object InputLibraries {
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown)
.put("adaptiveCapture", e.adaptiveCapture))
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
}
private fun decodeElements(array: JSONArray) = array.objects(64).map { e ->
@@ -343,8 +336,7 @@ object InputLibraries {
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false),
if (e.isNull("adaptiveCapture")) null else e.optBoolean("adaptiveCapture", false))
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
internal fun encode(library: InputLibrary): String {
@@ -32,7 +32,7 @@ data class SavedInputLayout(
fun withQuickButton(button: InputCommand, shown: Boolean) =
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
fun derived(id: String, name: String) = copy(id = id, name = name, origin = origin ?: this.id)
val adaptiveSticks get() = elements.filter { it.kind == InputElementKind.STICK }.takeIf { editable && it.isNotEmpty() }?.all { it.adaptiveStick }
val adaptiveSticks get() = elements.filter { it.kind == InputElementKind.STICK }.takeIf { editable && it.isNotEmpty() }?.all { it.floating && it.hideWhenIdle }
fun supports(role: InputRole) = screen.supports(role) && when (template) {
InputLayoutTemplate.OVERLAY -> role == InputRole.PRIMARY
InputLayoutTemplate.DECK, InputLayoutTemplate.TRACKPAD -> role == InputRole.SECONDARY
@@ -37,12 +37,7 @@ data class InputSurfaceElement(
val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
val showLabel: Boolean = true,
val alwaysShown: Boolean = false,
val adaptiveCapture: Boolean? = null,
) {
// Old layouts encoded Adaptive sticks as Floating + Hide when idle.
val adaptiveStick get() = kind == InputElementKind.STICK && floating && (adaptiveCapture ?: hideWhenIdle)
val hideStickAtRest get() = hideWhenIdle && (adaptiveCapture != null || !adaptiveStick)
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
@@ -188,7 +188,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
}.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, adaptiveCapture = if (c.stick >= 0) settings.adaptiveSticks else null,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
}.toMutableList()
if (settings.keyboardButton) result += keyboard()
@@ -37,10 +37,8 @@ object OnScreenLayout {
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val placed = placeElements(context, saved, width, height, safe, buttonsOnly, dock, rearButtons, trackpads)
// Docked sticks stay visible and only pick up touches inside their own bounds.
return if (dock == null) placed else placed.map {
if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false, adaptiveCapture = false) else it
}
// Below the game a stick covers nothing, so it keeps its base in view instead of appearing only under the thumb.
return if (dock == null) placed else placed.map { if (it.kind == InputElementKind.STICK) it.copy(hideWhenIdle = false) else it }
}
private fun placeElements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
@@ -577,15 +577,12 @@ object BwrapSpawner {
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
val nativeSession = NativeGuest.forSession(context)
val native = if (nativeSession) nativeLaunch(context, plan) else null
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
val builder = if (native != null) {
ProcessBuilder(native.first).redirectErrorStream(true)
.directory(File(hostPath(plan.binds, plan.root.path, plan.cwd)).takeIf { it.isDirectory } ?: plan.root)
.also { b -> b.environment().apply { clear(); putAll(native.second) } }
} else {
val reason = if (nativeSession) "sandbox native launch unavailable" else "parent guest uses PRoot"
Log.i(TAG, "Flatpak: using PRoot ($reason)")
val cmd = LinuxRuntime.prootPrefix(context, plan.root, plan.cwd)
if (verbose != null) { cmd.add("-v"); cmd.add(verbose.toString()) }
plan.binds.forEach { cmd.add("-b"); cmd.add(it.spec) }
@@ -602,6 +599,7 @@ object BwrapSpawner {
putAll(prootEnvironment(plan, envTool))
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -6,6 +6,7 @@ import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionFiles
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -66,6 +67,7 @@ object GuestCommand {
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (linkDir != null) put("PROOT_L2S_DIR", linkDir.path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -22,15 +22,15 @@ object NativeGuest {
}
fun enabled(context: Context): Boolean =
available(LinuxRuntime.rootDir(context))
SessionPrefs.nativeUserland(context) && available(LinuxRuntime.rootDir(context))
/**
* Whether the next session will start natively. The session stages the hook from the APK before
* it starts, so the rootfs's loader decides, and a runtime still to be
* it starts, so only the setting and the rootfs's loader decide, and a runtime still to be
* installed will have one.
*/
fun nextSession(context: Context): Boolean =
willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
SessionPrefs.nativeUserland(context) && willRun(LinuxRuntime.rootDir(context), LinuxRuntime.isInstalled(context))
internal fun willRun(root: File, installed: Boolean): Boolean = !installed || loader(root) != null
@@ -39,7 +39,7 @@ object NativeGuest {
/**
* Whether a session's helpers (root commands, Flatpak sandboxes, installers) run natively: the
* session's own mode while one runs, as the rootfs is only
* session's own mode while one runs, as the setting can change under it and the rootfs is only
* prepared for native programs at a session's start.
*/
fun forSession(context: Context): Boolean = sessionMode ?: enabled(context)
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.runtime
import android.content.Context
import android.os.Build
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.security.MessageDigest
@@ -11,14 +12,17 @@ object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libddfastpath.so"
const val MAX_BINDS = 256
internal fun allows(source: String, native: Boolean): Boolean =
!native && source == LinuxRuntime.PROOT_PACK
fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean =
preference && !noSeccomp && !nativeUserland && source == LinuxRuntime.PROOT_PACK
fun enabled(context: Context, native: Boolean = NativeGuest.forSession(context)): Boolean {
if (native) return false
fun enabled(context: Context): Boolean {
val preference = SessionPrefs.prootFastPath(context)
val noSeccomp = SessionPrefs.prootNoSeccomp(context)
val nativeUserland = SessionPrefs.nativeUserland(context)
val source = LinuxRuntime.prootSource(context)
val on = allows(source, native)
if (!on) Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
val on = allows(preference, noSeccomp, source, nativeUserland)
if (preference && !noSeccomp && !nativeUserland && !on)
Log.i(TAG, "proot: fast path off - binary is $source, not the patched proot")
return on
}
@@ -8,6 +8,7 @@ import android.os.Process
import android.util.Log
import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.DataInputStream
import java.io.DataOutputStream
@@ -127,6 +128,7 @@ object RootSpawner {
clear()
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -5,7 +5,6 @@ import android.os.ParcelFileDescriptor
import android.system.Os
import android.system.OsConstants
import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONArray
@@ -26,7 +25,6 @@ import java.nio.channels.SeekableByteChannel
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardOpenOption
@@ -223,7 +221,7 @@ internal object EnhancedSessionLogShare {
Category.values().map { category ->
val budget = budgets.getValue(category)
val records = ArrayList<Record>()
val selected = candidates.filter { it.category == category }.sortedBy(::sharePriority)
val selected = candidates.filter { it.category == category }
val zip = File(out, "DroidDeck-${folder.name}-${category.suffix}.zip")
ZipOutputStream(zip.outputStream().buffered()).use { archive ->
val names = HashSet<String>()
@@ -618,8 +616,7 @@ internal object EnhancedSessionLogShare {
redactionLearningComplete: Boolean,
) {
val entries = JSONArray()
val (discovery, rest) = records.partition { it.origin == "discovery" }
(discovery + rest).take(MAX_MANIFEST_RECORDS).forEach { record ->
records.take(MAX_MANIFEST_RECORDS).forEach { record ->
entries.put(JSONObject().apply {
put("entry", record.entry)
put("origin", record.origin)
@@ -683,15 +680,6 @@ internal object EnhancedSessionLogShare {
categoryCounts[category] = (categoryCounts[category] ?: 0) + 1
}
}
fun addRecentLogs(root: File, entryPrefix: String, origin: String) {
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
val base = root.toPath().toAbsolutePath().normalize()
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }.forEach { file ->
add(file, root, "$entryPrefix/${base.relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")}", origin)
}
}
CRITICAL_SESSION_FILES.forEach { name ->
File(folder, name).takeIf { it.exists() }?.let { add(it, folder, "${folder.name}/$name", "session-critical") }
}
@@ -725,7 +713,16 @@ internal object EnhancedSessionLogShare {
add(source.file, source.root, source.entry, "battlenet")
}
} else {
battleNetRoots(context).forEach { (prefix, root) -> addRecentLogs(root, "battlenet/$prefix", "battlenet") }
battleNetRoots(context).forEach { (prefix, root) ->
val scan = walk(root, remaining(maxFiles, out.size))
truncated = truncated || scan.truncated
partial = partial || scan.partial
scan.files.asSequence().filter { recent(it) && it.name.endsWith(".log", true) }
.forEach { file ->
val relative = root.toPath().toAbsolutePath().normalize().relativize(file.toPath().toAbsolutePath().normalize()).joinToString("/")
add(file, root, "battlenet/$prefix/$relative", "battlenet")
}
}
}
val sessionScan = walk(folder, remaining(maxFiles, out.size))
truncated = truncated || sessionScan.truncated
@@ -736,9 +733,6 @@ internal object EnhancedSessionLogShare {
if (relative == EnhancedDiagnostics.MANIFEST_FILE) return@forEach
add(file, folder, "${folder.name}/$relative", "session")
}
val antiCheat = antiCheatRoots(context)
partial = partial || antiCheat.partial
antiCheat.roots.forEach { (appId, root) -> addRecentLogs(root, "anticheat/$appId", "anticheat") }
if (SessionPaths.current()?.canonicalFile == folder.canonicalFile && !File(folder, "steam").exists()) {
val steam = File(SessionPrefs.activeSteamRoot(context), "logs")
val scan = directFiles(steam, remaining(maxFiles, out.size))
@@ -754,8 +748,7 @@ internal object EnhancedSessionLogShare {
private fun sharePriority(candidate: Candidate): Int = when {
candidate.origin == "session-critical" -> 0
candidate.origin == "session" && candidate.category == Category.GAMES -> 1
candidate.origin == "anticheat" -> 2
else -> 3
else -> 2
}
private fun remaining(maxFiles: Int, found: Int): Int = (maxFiles - found + 1).coerceAtLeast(0)
@@ -829,39 +822,6 @@ internal object EnhancedSessionLogShare {
return ScanResult(files, truncated, partial)
}
private class AntiCheatRoots(val roots: List<Pair<String, File>>, val partial: Boolean)
private fun antiCheatRoots(context: Context): AntiCheatRoots {
var partial = false
val seen = HashSet<String>()
val dirs = runCatching { Library.compatdataDirs(context) }.getOrElse { partial = true; emptyList() }
val roots = dirs.flatMapIndexed { library, compatdata ->
val prefixes = compatdata.listFiles() ?: run { partial = true; emptyArray() }
prefixes.filter { !Files.isSymbolicLink(it.toPath()) }.mapNotNull { prefix ->
val appId = steamAppId(prefix.name) ?: return@mapNotNull null
val root = File(prefix, EAC_LOG_DIR)
val directory = try {
Files.readAttributes(root.toPath(), BasicFileAttributes::class.java, LinkOption.NOFOLLOW_LINKS).isDirectory
} catch (_: NoSuchFileException) {
false
} catch (_: Exception) {
partial = true
false
}
if (!directory) return@mapNotNull null
val base = "$appId/library${library + 1}"
val key = base.takeIf { seen.add(it) } ?: "$base-${prefix.name}".takeIf { seen.add(it) }
if (key != null) key to root else { partial = true; null }
}
}
return AntiCheatRoots(roots, partial)
}
private fun steamAppId(name: String): String? =
name.takeIf { SIGNED_APP_ID.matches(it) }?.toLongOrNull()
?.takeIf { it in Int.MIN_VALUE.toLong()..0xffffffffL }
?.let { (it and 0xffffffffL).toString() }
private fun battleNetRoots(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
@@ -968,9 +928,7 @@ internal object EnhancedSessionLogShare {
val normalized = name.replace('\\', '/').trimStart('/')
val parts = normalized.split('/')
if (normalized.isEmpty() || parts.any { it.isEmpty() || it == "." || it == ".." }) return null
return parts.mapIndexed { index, part ->
if (index == 1 && parts[0] == "anticheat" && APP_ID.matches(part)) part else safeComponent(part)
}.joinToString("/")
return parts.joinToString("/") { safeComponent(it) }
}
private fun safeComponent(value: String): String {
@@ -983,7 +941,7 @@ internal object EnhancedSessionLogShare {
private fun category(entry: String): Category {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("anticheat/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
@@ -992,7 +950,7 @@ internal object EnhancedSessionLogShare {
private val GAME_LOG = Regex("steam-[0-9]+\\.(log|txt)")
private val KNOWN_COMPONENTS = setOf(
"steam", "graphics", "games", "battlenet", "anticheat", "anticheatlauncher.log", "client", "agent", "setup", "stores", "tools",
"steam", "graphics", "games", "battlenet", "client", "agent", "setup", "stores", "tools",
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
@@ -1003,15 +961,11 @@ internal object EnhancedSessionLogShare {
private val KNOWN_COMPONENT_PATTERNS = listOf(
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
Regex("steam-[0-9]+\\.(?:log|txt)"),
Regex("library[0-9]+(?:--?[0-9]{1,10})?"),
Regex("(?:battle\\.net-[0-9]+|battle\\.net-setup-[0-9]+|Agent-[0-9]+)\\.log"),
Regex("(?:Agent\\.[0-9]+|bna_[0-9]+)"),
Regex("stores-[0-9]{4}-[0-9]{2}-[0-9]{2}\\.log"),
Regex("library[0-9]{1,3}"),
Regex("entry-[0-9a-f]{16}(?:\\.[a-z0-9]{1,8})?"),
)
private val APP_ID = Regex("[0-9]{1,10}")
private val SIGNED_APP_ID = Regex("-?[0-9]{1,10}")
private val SAFE_SUFFIX = Regex("\\.[A-Za-z0-9]{1,8}$")
private val CRITICAL_SESSION_FILES = listOf(
"session.log", "app.log", "wayland.log", "audio.log", "device.txt", "network.txt",
@@ -1019,7 +973,6 @@ internal object EnhancedSessionLogShare {
)
private const val RECENT_MILLIS = 7L * 24 * 60 * 60 * 1000
private const val STORE_LOG_SCAN = 512
private const val EAC_LOG_DIR = "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat"
private const val COPY_BUFFER_BYTES = 64 * 1024
private const val TRACE_SCAN_BYTES = 16L * 1024 * 1024
private const val LEGACY_LOG_MAX_BYTES = 8L * 1024 * 1024
@@ -2,16 +2,10 @@ package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
import java.io.IOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
internal const val MIN_FILE_BYTES = 8L shl 20
private const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
@@ -43,7 +37,7 @@ internal object PageCacheTrim {
if (mem != null && shouldTrim(mem, baseline)) {
val now = System.currentTimeMillis()
if (now - scanned > RESCAN_MS) {
files = roots().flatMap { root -> bigFiles(root) }
files = roots().flatMap { root -> root.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }.filter { it.isFile && it.length() >= MIN_FILE_BYTES }.toList() }
scanned = now
}
val began = System.nanoTime()
@@ -62,34 +56,6 @@ internal object PageCacheTrim {
}, "page-cache-trim").apply { isDaemon = true }.start()
}
// java.io's directory listing hands raw entry names to JNI NewStringUTF, which aborts the
// process on names that are not valid UTF-8; NIO decodes them with replacement instead.
// Without FOLLOW_LINKS, symlinked directories are never descended into, like the old onEnter,
// except that a starting directory that is itself a link has to be resolved first; a link
// whose target has vanished yields an empty result instead of an error.
internal fun bigFiles(root: File): List<File> {
val out = ArrayList<File>()
val start = root.toPath()
val real = if (Files.isSymbolicLink(start)) {
try {
start.toRealPath()
} catch (_: IOException) {
return out
}
} else start
Files.walkFileTree(real, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
if (attrs.isRegularFile && attrs.size() >= MIN_FILE_BYTES) out.add(file.toFile())
return FileVisitResult.CONTINUE
}
override fun visitFileFailed(file: Path, error: IOException): FileVisitResult = FileVisitResult.CONTINUE
override fun postVisitDirectory(dir: Path, error: IOException?): FileVisitResult = FileVisitResult.CONTINUE
})
return out
}
private fun drop(file: File) {
PageCacheNative.fadviseDontNeed(file.path)
}
@@ -367,17 +367,16 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n")
}
com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
val native = com.droiddeck.launcher.runtime.NativeGuest.available(root)
val nativePreload = preload.toString()
if (ProotFastPath.enabled(context, native)) {
val nativeUserland = SessionPrefs.nativeUserland(context)
if (nativeUserland) com.droiddeck.launcher.runtime.NativeGuest.prepare(context, root)
if (ProotFastPath.enabled(context)) {
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() }
File(etc, "droiddeck").mkdirs()
FileUtils.writeString(File(etc, "droiddeck/native-preload"), nativePreload)
FileUtils.writeString(File(etc, "droiddeck/native-preload"), preload.toString())
val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString())
|| !staged.renameTo(File(etc, "ld.so.preload"))) {
@@ -10,7 +10,6 @@ import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.ScreenEffects
import com.droiddeck.launcher.gpu.SystemVulkanDriver
import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
@@ -318,14 +317,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
}
fun settingsSearches(context: Context): List<String> = runCatching {
JSONArray(prefs(context).getString("settingsSearches", null) ?: "[]").let { a -> List(a.length()) { a.getString(it) } }
}.getOrDefault(emptyList())
fun setSettingsSearches(context: Context, searches: List<String>) {
prefs(context).edit().putString("settingsSearches", JSONArray(searches).toString()).apply()
}
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
fun setTelemetryOff(context: Context, keys: Set<String>) {
@@ -1190,9 +1181,21 @@ object SessionPrefs {
prefs(context).edit().putBoolean("mountSharedStorage", on).apply()
}
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
fun setProotNoSeccomp(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
}
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true)
/** The session's long-lived programs run in worker processes Android does not count (GuestWorkers). */
fun childProcessHandoff(context: Context): Boolean = prefs(context).getBoolean("childProcessHandoff", true)
fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply()
}
/** Whether the Plasma desktop, and so its apps and shells, runs as an ordinary user instead of root (native userland only). */
fun desktopAsUser(context: Context): Boolean = prefs(context).getBoolean("desktopAsUser", false)
@@ -1200,6 +1203,12 @@ object SessionPrefs {
prefs(context).edit().putBoolean("desktopAsUser", on).apply()
}
fun prootFastPath(context: Context): Boolean = prefs(context).getBoolean("prootFastPath", true)
fun setProotFastPath(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
fun setCursorComposite(context: Context, on: Boolean) {
@@ -47,7 +47,6 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.runtime.BwrapSpawner
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -785,13 +784,12 @@ class SessionService : Service() {
SessionEvents.step("shm-clear") { FileUtils.clear(File(LinuxRuntime.liveDir(this), "shm")) }
val sharedStorage = LinuxRuntime.sharedStorage(this)
val nativeUserland = NativeGuest.enabled(this)
val fastPath = ProotFastPath.enabled(this, nativeUserland)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage, fastPath)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir, sharedStorage)
val nativeUserland = com.droiddeck.launcher.runtime.NativeGuest.enabled(this)
synchronized(stopLock) {
if (gen == sessionGen && SessionState.running) com.droiddeck.launcher.runtime.NativeGuest.sessionMode = nativeUserland
}
val fastPathKey = if (fastPath) {
val fastPathKey = if (ProotFastPath.enabled(this)) {
val prootBinds = LinuxRuntime.binds(
this, sessionRoot, runtimeDir, sharedStorage, binds,
)
@@ -812,14 +810,16 @@ class SessionService : Service() {
LinuxRuntime.rememberSessionBinds(sessionBindSpecs)
com.droiddeck.launcher.runtime.NativeGuest.command(root, guest.first(), guest.drop(1))
} else {
val reason = if (NativeGuest.loader(root) == null) "missing glibc loader" else "missing native hook"
Log.i(TAG, "guest runtime: using PRoot ($reason)")
LinuxRuntime.command(this, sessionRoot, runtimeDir, sharedStorage, binds, guest)
}
val prootEnv = HostEnvironment()
prootEnv["PROOT_LOADER"] = LinuxRuntime.prootLoader(this).path
prootEnv["PROOT_TMP_DIR"] = LinuxRuntime.prootTempDir(this).path
if (SessionPrefs.prootNoSeccomp(this)) {
prootEnv["PROOT_NO_SECCOMP"] = "1"
if (!nativeUserland) Log.i(TAG, "proot: seccomp acceleration off by request")
}
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> prootEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { prootEnv[key] = it }
@@ -1313,7 +1313,6 @@ class SessionService : Service() {
sessionRoot: File,
runtimeDir: File,
sharedStorage: File?,
fastPath: Boolean,
): ArrayList<String> {
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
@@ -1447,7 +1446,7 @@ class SessionService : Service() {
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
if (gamesLibraries.isNotEmpty()) {
var room = if (fastPath) {
var room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (games in gamesLibraries) {
@@ -1489,7 +1488,7 @@ class SessionService : Service() {
continue
}
try {
val room = if (fastPath) {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val content = SecondaryLibrary.contentPath(entry.host)
@@ -1518,7 +1517,7 @@ class SessionService : Service() {
if (problem != null) {
Log.w(TAG, "x86-64 steam library: $problem")
} else try {
val room = if (fastPath) {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, x64, listOf(GameStorage.X64_CARD_GUEST)).drop(1)
@@ -1540,7 +1539,7 @@ class SessionService : Service() {
continue
}
try {
val room = if (fastPath) {
val room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
val extra = SecondaryLibrary.binds(filesDir, entry.x64Host, listOf(entry.x64Guest)).drop(1)
@@ -1576,7 +1575,7 @@ class SessionService : Service() {
try {
val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() }
val volumes = org.json.JSONArray()
var room = if (fastPath) {
var room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, sharedStorage, binds).size
} else Int.MAX_VALUE
for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) {
@@ -8,6 +8,7 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.AchievementNotifications
@@ -148,6 +149,7 @@ object GogComet {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
}
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.core.AddonPack
import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import org.json.JSONObject
import java.io.Closeable
@@ -106,6 +107,7 @@ internal object Xodus {
remove("LD_PRELOAD"); remove("LD_AUDIT"); remove("LD_LIBRARY_PATH")
put("PROOT_LOADER", LinuxRuntime.prootLoader(app).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(app).path)
if (SessionPrefs.prootNoSeccomp(app)) put("PROOT_NO_SECCOMP", "1")
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (key, value) -> put(key, value) } }
LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
}
@@ -39,8 +39,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
}
if (!a.hudOn) return@SettingsGroup
val size = DroidDeckHudSize.from(cfg["hudSize"])
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size),
stringResource(if (size == DroidDeckHudSize.SIDE_STRIP) R.string.hud_size_side_strip_hint else R.string.hud_size_hint),
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
listOf(
DroidDeckHudSize.FULL to stringResource(R.string.hud_size_full),
DroidDeckHudSize.TILES to stringResource(R.string.hud_size_tiles),
@@ -48,7 +47,6 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
DroidDeckHudSize.STRIP to stringResource(R.string.hud_size_strip),
DroidDeckHudSize.SIDE_STRIP to stringResource(R.string.hud_size_side_strip),
),
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
ChoiceRow(host, "hud-hold", stringResource(R.string.hud_hold), null,
@@ -231,10 +231,7 @@ internal fun SetupPanel(
}
val chipFocus = remember { List(tabs.size) { FocusRequester() } }
var tabTurned by remember { mutableStateOf(false) }
remember { SettingsSearchHistory.load(ctx) }
var fromHistory by remember { mutableStateOf(false) }
val keepSearch = { if (searching && SettingsIndex.search(ctx, query, frostRow).isNotEmpty()) SettingsSearchHistory.add(ctx, query) }
val pick: (Int) -> Unit = { i -> keepSearch(); tab = i; tabTurned = true; searching = false; query = ""; if (i == DEVELOPER_TAB) logsRefresh++ }
val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true; searching = false; query = ""; if (i == DEVELOPER_TAB) logsRefresh++ }
val inputModeManager = LocalInputModeManager.current
LaunchedEffect(Unit) {
while (true) {
@@ -261,9 +258,8 @@ internal fun SetupPanel(
) {
val sectionBar: @Composable (Modifier) -> Unit = { m ->
SettingsPillSearch(
m, searching, query, { query = it; fromHistory = false },
onOpen = { searching = true }, onClose = { keepSearch(); searching = false; query = "" },
keepOpen = SettingsSearchHistory.items.isNotEmpty(), onSearch = keepSearch,
m, searching, query, { query = it },
onOpen = { searching = true }, onClose = { searching = false; query = "" },
) { SheetChips(tabs, tab, chipFocus, onPick = pick) }
}
val portrait = androidx.compose.ui.platform.LocalConfiguration.current.orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT
@@ -272,11 +268,9 @@ internal fun SetupPanel(
Row(Modifier.fillMaxWidth().padding(bottom = 10.dp)) { sectionBar(Modifier.weight(1f)) }
} else PageHeader(stringResource(R.string.setup_title)) { sectionBar(Modifier.weight(1f)) }
val listing = searching && query.isNotBlank()
val history = searching && query.isBlank() && SettingsSearchHistory.items.isNotEmpty()
val fixed = tab == CONTROLLER_TAB && !listing && !history
val fixed = tab == CONTROLLER_TAB && !listing
Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (fixed) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (fixed) 0.dp else 24.dp)) {
if (listing) SettingsSearchResults(query, frostRow, focusFirst = fromHistory, onSearched = keepSearch) { section -> pick(section.ordinal) }
else if (history) SettingsSearchHistoryList(onPick = { fromHistory = true; query = it }) { SettingsSearchHistory.clear(ctx) }
if (listing) SettingsSearchResults(query, frostRow) { section -> pick(section.ordinal) }
else when (tab) {
OVERVIEW_TAB -> {
OnboardingCard(limitBlocks, a.onShowPhantomGate)
@@ -67,18 +67,8 @@ internal fun InputElementProperties(element: InputSurfaceElement, action: InputA
}
if (element.kind == InputElementKind.STICK) {
val host = rememberMenuHost()
val adaptive = element.adaptiveCapture ?: element.adaptiveStick
ToggleRow(host, "element-floating", stringResource(R.string.input_floating_stick), null, element.floating) {
onChange(element.copy(floating = it, hideWhenIdle = element.hideStickAtRest, adaptiveCapture = adaptive))
}
if (element.floating) {
ToggleRow(host, "element-adaptive-capture", stringResource(R.string.input_adaptive_capture), null, element.adaptiveStick) {
onChange(element.copy(hideWhenIdle = element.hideStickAtRest, adaptiveCapture = it))
}
}
ToggleRow(host, "element-hide-idle", stringResource(R.string.input_hide_idle), null, element.hideStickAtRest) {
onChange(element.copy(hideWhenIdle = it, adaptiveCapture = adaptive))
}
ToggleRow(host, "element-floating", stringResource(R.string.input_floating_stick), null, element.floating) { onChange(element.copy(floating = it)) }
ToggleRow(host, "element-hide-idle", stringResource(R.string.input_hide_idle), null, element.hideWhenIdle) { onChange(element.copy(hideWhenIdle = it)) }
}
val host = rememberMenuHost()
if ((element.kind == InputElementKind.BUTTON || element.kind == InputElementKind.TRIGGER) && element.icon == 0 && element.image.isEmpty() ||
@@ -236,11 +236,11 @@ class InputSurfaceView(
super.dispatchDraw(canvas)
}
}
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || it.adaptiveStick) }
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) }
for (element in customLayout) {
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideStickAtRest && pad != null)
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel,
stock = element.id == "legacy:${element.control.id}", source = source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
@@ -641,7 +641,7 @@ class InputSurfaceView(
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
val adaptive get() = element.adaptiveStick
val adaptive get() = adaptive(element)
fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH
@@ -859,6 +859,8 @@ class InputSurfaceView(
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating && element.hideWhenIdle
private fun classic(element: InputSurfaceElement) = (element.id == "legacy:${element.control.id}" || element.id == "builtin:keyboard") &&
(element.buttonShape == InputButtonShape.CIRCLE || element.buttonShape == InputButtonShape.PILL)
@@ -46,7 +46,9 @@ fun PerformancePage(
fsyncFirst: Boolean,
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
nativeDesktopAvailable: Boolean,
prootNoSeccomp: Boolean,
prootFastPath: Boolean,
nativeUserland: Boolean,
desktopAsUser: Boolean,
cursorComposite: Boolean,
guestHostname: String,
@@ -63,6 +65,9 @@ fun PerformancePage(
onFsyncFirst: (Boolean) -> Unit,
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
onProotNoSeccomp: (Boolean) -> Unit,
onProotFastPath: (Boolean) -> Unit,
onNativeUserland: (Boolean) -> Unit,
onDesktopAsUser: (Boolean) -> Unit,
onCursorComposite: (Boolean) -> Unit,
onGuestHostname: (String) -> Unit,
@@ -147,6 +152,26 @@ fun PerformancePage(
stringResource(R.string.perf_fastsync_hint),
fastSync, onChange = onFastSync,
)
ToggleRow(
host, "seccomp", stringResource(R.string.perf_seccomp),
stringResource(R.string.perf_seccomp_hint),
prootNoSeccomp, onChange = onProotNoSeccomp,
)
ToggleRow(
host, "fastpath", stringResource(R.string.perf_fastpath),
when {
nativeUserland -> stringResource(R.string.perf_fastpath_needs_proot)
prootNoSeccomp -> stringResource(R.string.perf_fastpath_needs_seccomp)
else -> stringResource(R.string.perf_fastpath_hint)
},
prootFastPath && !prootNoSeccomp && !nativeUserland, enabled = !prootNoSeccomp && !nativeUserland,
onChange = onProotFastPath,
)
ToggleRow(
host, "nativeuserland", stringResource(R.string.perf_native_userland),
stringResource(R.string.perf_native_userland_hint),
nativeUserland, onChange = onNativeUserland,
)
ToggleRow(
host, "cursorcomposite", stringResource(R.string.perf_cursor_composite),
stringResource(R.string.perf_cursor_composite_hint),
@@ -173,8 +198,8 @@ fun PerformancePage(
}
ToggleRow(
host, "desktopasuser", stringResource(R.string.perf_desktop_as_user),
stringResource(R.string.perf_desktop_as_user_hint),
desktopAsUser && nativeDesktopAvailable, enabled = nativeDesktopAvailable,
stringResource(if (nativeUserland) R.string.perf_desktop_as_user_hint else R.string.perf_desktop_as_user_needs_native),
desktopAsUser && nativeUserland, enabled = nativeUserland,
onChange = onDesktopAsUser,
)
}
@@ -85,6 +85,9 @@ internal object SettingsIndex {
s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fsync, "fsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "sync", "wine"),
s(SettingsSection.PERFORMANCE, R.string.perf_seccomp, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_fastpath, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"),
s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"),
s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"),
s(SettingsSection.PERFORMANCE, R.string.perf_desktop_as_user, "root", "user", "sudo", "fakeroot"),
@@ -16,10 +16,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onPlaced
/** The row a settings search result opens, so the page it lands on can scroll to it and flash it. */
internal object SettingsJump {
@@ -35,32 +31,12 @@ private const val JUMP_WINDOW_MS = 5_000L
/** False in the search results, whose rows carry the same labels as the rows they open. */
internal val LocalSearchTargets = staticCompositionLocalOf { true }
/** How far a page has to be scrolled to show a row in its middle, or as near to it as the page's ends allow. */
internal fun centeredScroll(rowTop: Float, rowHeight: Float, page: Float, content: Float): Float =
(rowTop + rowHeight / 2f - page / 2f).coerceIn(0f, (content - page).coerceAtLeast(0f))
/** The part of the page to show around a row to have it in the middle, relative to the row. Null when nothing around it scrolls. */
private fun pageAround(row: LayoutCoordinates): Rect? {
var content = row
while (true) {
val page = content.parentCoordinates ?: return null
if (content.size.height > page.size.height) {
val top = content.localPositionOf(row, Offset.Zero).y
val height = page.size.height.toFloat()
val from = centeredScroll(top, row.size.height.toFloat(), height, content.size.height.toFloat()) - top
return Rect(0f, from, row.size.width.toFloat(), from + height)
}
content = page
}
}
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
internal fun Modifier.searchTarget(label: String): Modifier {
val pal = LocalPalette.current
val flash = remember { Animatable(0f) }
val reveal = remember { BringIntoViewRequester() }
val row = remember { arrayOfNulls<LayoutCoordinates>(1) }
var claimed by remember { mutableStateOf<SettingsJump.Target?>(null) }
val target = SettingsJump.target.takeIf { LocalSearchTargets.current }
if (target != null && target.label == label) SideEffect {
@@ -72,7 +48,7 @@ internal fun Modifier.searchTarget(label: String): Modifier {
claimed?.let { mine ->
LaunchedEffect(mine) {
withFrameNanos { }
reveal.bringIntoView(row[0]?.takeIf { it.isAttached }?.let(::pageAround))
reveal.bringIntoView()
repeat(2) {
flash.animateTo(1f, tween(220))
flash.animateTo(0f, tween(420))
@@ -80,7 +56,7 @@ internal fun Modifier.searchTarget(label: String): Modifier {
claimed = null
}
}
return bringIntoViewRequester(reveal).onPlaced { row[0] = it }.drawBehind {
return bringIntoViewRequester(reveal).drawBehind {
if (flash.value > 0f) drawRect(pal.signal.copy(alpha = 0.28f * flash.value))
}
}
@@ -42,7 +42,7 @@ import androidx.compose.ui.semantics.clearAndSetSemantics
@Composable
internal fun SettingsPillSearch(
modifier: Modifier, searching: Boolean, query: String, onQuery: (String) -> Unit,
onOpen: () -> Unit, onClose: () -> Unit, keepOpen: Boolean = false, onSearch: () -> Unit = {}, pills: @Composable () -> Unit,
onOpen: () -> Unit, onClose: () -> Unit, pills: @Composable () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "settingsSearch")
@@ -53,11 +53,10 @@ internal fun SettingsPillSearch(
var fieldFocused by remember { mutableStateOf(false) }
CancelPendingFocus(focusOnOpen, focusTap, fieldFocused) {
focusOnOpen = false
if (query.isEmpty() && !keepOpen) onClose()
if (query.isEmpty()) onClose()
}
val close = { toIcon = true; focusOnOpen = false; onClose() }
BackHandler(enabled = searching) { close() }
LaunchedEffect(keepOpen) { if (!keepOpen && searching && !fieldFocused && !focusOnOpen && query.isEmpty()) close() }
LaunchedEffect(toIcon, searching, open <= 0.01f) {
if (searching) toIcon = false
else if (toIcon && open <= 0.01f) { focusSoon { icon }; toIcon = false }
@@ -81,13 +80,10 @@ internal fun SettingsPillSearch(
AdbTextField(
value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, focusAtTap = focusTap,
clearFocus = !searching, onDone = onSearch,
clearFocus = !searching,
onFocusChange = { focused ->
fieldFocused = focused
if (!focused && query.isEmpty() && searching) {
focusOnOpen = false
if (!keepOpen) onClose()
}
if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() }
},
)
}
@@ -100,19 +96,13 @@ internal fun SettingsPillSearch(
}
@Composable
internal fun SettingsSearchResults(query: String, frost: Boolean, focusFirst: Boolean = false, onSearched: () -> Unit = {}, onOpen: (SettingsSection) -> Unit) {
internal fun SettingsSearchResults(query: String, frost: Boolean, onOpen: (SettingsSection) -> Unit) {
val ctx = LocalContext.current
val found = remember(query, frost) { SettingsIndex.search(ctx, query, frost) }
if (found.isEmpty()) {
Note(stringResource(R.string.settings_search_none, query.trim()))
return
}
val first = remember { FocusRequester() }
val firstToOpen = found.groupBy { it.place }.values.flatten().firstOrNull { it.section != null || it.tab != null }
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
LaunchedEffect(Unit) {
if (focusFirst && firstToOpen != null && inputMode.inputMode == androidx.compose.ui.input.InputMode.Keyboard) focusSoon { first }
}
androidx.compose.runtime.CompositionLocalProvider(LocalSearchTargets provides false) { Column {
found.groupBy { it.place }.forEach { (place, entries) ->
SettingsGroup(stringResource(place.title)) {
@@ -121,12 +111,10 @@ internal fun SettingsSearchResults(query: String, frost: Boolean, focusFirst: Bo
val title = stringResource(entry.title)
val section = entry.section
val tab = entry.tab
val button = if (entry === firstToOpen) Modifier.focusRequester(first) else Modifier
if (section != null) {
ActionRow(title, within, stringResource(R.string.store_open), modifier = button, onClick = { onSearched(); SettingsJump.to(title); onOpen(section) })
ActionRow(title, within, stringResource(R.string.store_open), onClick = { SettingsJump.to(title); onOpen(section) })
} else if (tab != null) {
ActionRow(title, within, stringResource(R.string.store_open), modifier = button, onClick = {
onSearched()
ActionRow(title, within, stringResource(R.string.store_open), onClick = {
SettingsJump.to(title)
if (tab == NavTabs.MORE) MoreTabs.editing = true
if (tab == "downloads") DownloadsNav.showSettings = true
@@ -1,101 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** What was searched for in Settings, newest first. */
internal object SettingsSearchHistory {
const val MAX = 8
var items by mutableStateOf<List<String>>(emptyList())
private set
fun load(context: Context) { items = SessionPrefs.settingsSearches(context) }
fun add(context: Context, query: String) {
val next = withSearch(items, query)
if (next == items) return
items = next
SessionPrefs.setSettingsSearches(context, next)
}
fun clear(context: Context) {
items = emptyList()
SessionPrefs.setSettingsSearches(context, emptyList())
}
fun withSearch(items: List<String>, query: String): List<String> {
val text = query.trim().replace(Regex("\\s+"), " ")
if (text.isEmpty()) return items
return (listOf(text) + items.filterNot { it.equals(text, ignoreCase = true) }).take(MAX)
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun SettingsSearchHistoryList(onPick: (String) -> Unit, onClear: () -> Unit) {
val colors = MaterialTheme.colorScheme
Column(Modifier.fillMaxWidth()) {
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 12.dp, bottom = 8.dp)) {
Text(
stringResource(R.string.settings_search_history), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
modifier = Modifier.weight(1f).padding(start = 4.dp),
)
SmallIconButton(Icons.Outlined.Delete, stringResource(R.string.settings_search_history_clear), tint = colors.onSurfaceVariant, onClick = onClear)
}
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
SettingsSearchHistory.items.forEach { HistoryChip(it) { onPick(it) } }
}
}
}
@Composable
private fun HistoryChip(text: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.heightIn(min = 40.dp).widthIn(min = 56.dp, max = 260.dp).clip(CircleShape)
.background(colors.surface).glideBorder(hot, CircleShape, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 8.dp),
) { Text(text, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) }
}
@@ -14,7 +14,6 @@ import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.key
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.CompositionLocalProvider
@@ -89,7 +88,7 @@ object Themes {
var rgbSpeed by mutableStateOf(DEFAULT_RGB_SPEED)
private set
@Volatile var rgbHue = 0f
var rgbHue by mutableStateOf(0f)
private set
fun moveRgbHue(hue: Float) {
@@ -238,36 +237,8 @@ fun DroidDeckTheme(theme: String? = null, appScale: Int = AppUiPrefs.DEFAULT_SCA
val context = LocalContext.current
remember(context) { Themes.loadGradient(context) }
val id = theme ?: SessionPrefs.theme(context)
val solid = if (id == Themes.INNER_GAMER) {
rememberInnerGamerPalette(Themes.rgbSpeed)
} else {
Themes.byId(id)
}
DroidDeckThemePalette(solid, appScale, frost, content)
}
@Composable
private fun rememberInnerGamerPalette(speed: Int): Palette = key(speed) {
val start = remember { Themes.rgbHue }
val animatedHue by rememberInfiniteTransition(label = "innerGamer").animateFloat(
start, start + 360f,
infiniteRepeatable(
tween(Themes.rgbCycleMillis(speed).coerceAtLeast(1), easing = LinearEasing),
RepeatMode.Restart,
),
label = "hue",
)
val steppedHue by remember {
derivedStateOf {
((animatedHue % 360f) / Themes.RGB_HUE_STEP).toInt() * Themes.RGB_HUE_STEP
}
}
SideEffect { Themes.moveRgbHue(steppedHue) }
Themes.innerGamer(steppedHue)
}
@Composable
private fun DroidDeckThemePalette(solid: Palette, appScale: Int, frost: FrostChoice?, content: @Composable () -> Unit) {
if (id == Themes.INNER_GAMER) InnerGamerHue(Themes.rgbSpeed)
val solid = Themes.byId(id)
val look = frost?.let { frostLook(solid, it) }
val p = if (look == null) solid else solid.frosted(look)
val baseDensity = LocalDensity.current
@@ -315,3 +286,17 @@ private val ContentDirected = Typography().run {
)
}
@Composable
private fun InnerGamerHue(speed: Int) {
key(speed) { InnerGamerCycle(speed) }
}
@Composable
private fun InnerGamerCycle(speed: Int) {
val start = remember { Themes.rgbHue }
val hue by rememberInfiniteTransition(label = "innerGamer").animateFloat(
start, start + 360f, infiniteRepeatable(tween(Themes.rgbCycleMillis(speed).coerceAtLeast(1), easing = LinearEasing), RepeatMode.Restart), label = "hue",
)
val stepped = ((hue % 360f) / Themes.RGB_HUE_STEP).toInt() * Themes.RGB_HUE_STEP
SideEffect { Themes.moveRgbHue(stepped) }
}
-2
View File
@@ -4356,6 +4356,4 @@
<string name="glasses_show_shortcut_hint">إظهار زر النظارات الذكية العائم فوق اللعبة.</string>
<string name="display_filter_game_profile">استخدام ملف تعريف %1$s: %2$s</string>
<string name="display_filter_default_profile">استخدام الملف التعريفي الافتراضي: %1$s</string>
<string name="settings_search_history">سجل البحث</string>
<string name="settings_search_history_clear">مسح سجل البحث</string>
</resources>
@@ -4234,6 +4234,4 @@
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
<string name="settings_search_history">Historial de búsqueda</string>
<string name="settings_search_history_clear">Borrar historial de búsqueda</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Показва плаващия бутон за Smart Glasses върху играта.</string>
<string name="display_filter_game_profile">Използва се профил %1$s: %2$s</string>
<string name="display_filter_default_profile">Използва се профилът по подразбиране: %1$s</string>
<string name="settings_search_history">История на търсенето</string>
<string name="settings_search_history_clear">Изчистване на историята на търсенето</string>
</resources>
-2
View File
@@ -4276,6 +4276,4 @@
<string name="glasses_show_shortcut_hint">Zobrazit plovoucí tlačítko Smart Glasses nad hrou.</string>
<string name="display_filter_game_profile">Používá se profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Používá se výchozí profil: %1$s</string>
<string name="settings_search_history">Historie hledání</string>
<string name="settings_search_history_clear">Vymazat historii hledání</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Vis den flydende Smart Glasses-knap oven på spillet.</string>
<string name="display_filter_game_profile">Bruger profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Bruger standardprofilen: %1$s</string>
<string name="settings_search_history">Søgehistorik</string>
<string name="settings_search_history_clear">Ryd søgehistorik</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Die schwebende Smart-Glasses-Schaltfläche über dem Spiel anzeigen.</string>
<string name="display_filter_game_profile">Profil %1$s wird verwendet: %2$s</string>
<string name="display_filter_default_profile">Standardprofil wird verwendet: %1$s</string>
<string name="settings_search_history">Suchverlauf</string>
<string name="settings_search_history_clear">Suchverlauf löschen</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Εμφάνιση του αιωρούμενου κουμπιού Smart Glasses πάνω από το παιχνίδι.</string>
<string name="display_filter_game_profile">Χρήση προφίλ %1$s: %2$s</string>
<string name="display_filter_default_profile">Χρήση προεπιλεγμένου προφίλ: %1$s</string>
<string name="settings_search_history">Ιστορικό αναζήτησης</string>
<string name="settings_search_history_clear">Εκκαθάριση ιστορικού αναζήτησης</string>
</resources>
-2
View File
@@ -4236,6 +4236,4 @@
<string name="glasses_show_shortcut_hint">Mostrar el botón flotante de Smart Glasses sobre el juego.</string>
<string name="display_filter_game_profile">Usando el perfil %1$s: %2$s</string>
<string name="display_filter_default_profile">Usando el perfil predeterminado: %1$s</string>
<string name="settings_search_history">Historial de búsqueda</string>
<string name="settings_search_history_clear">Borrar historial de búsqueda</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Näytä pelin päällä kelluva Smart Glasses -painike.</string>
<string name="display_filter_game_profile">Käytössä profiili %1$s: %2$s</string>
<string name="display_filter_default_profile">Käytössä oletusprofiili: %1$s</string>
<string name="settings_search_history">Hakuhistoria</string>
<string name="settings_search_history_clear">Tyhjennä hakuhistoria</string>
</resources>
-2
View File
@@ -4235,6 +4235,4 @@
<string name="glasses_show_shortcut_hint">Afficher le bouton flottant Smart Glasses par-dessus le jeu.</string>
<string name="display_filter_game_profile">Profil %1$s utilisé : %2$s</string>
<string name="display_filter_default_profile">Profil par défaut utilisé : %1$s</string>
<string name="settings_search_history">Historique de recherche</string>
<string name="settings_search_history_clear">Effacer l\'historique de recherche</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">गेम के ऊपर तैरता हुआ Smart Glasses बटन दिखाएँ।</string>
<string name="display_filter_game_profile">%1$s प्रोफ़ाइल का उपयोग: %2$s</string>
<string name="display_filter_default_profile">डिफ़ॉल्ट प्रोफ़ाइल का उपयोग: %1$s</string>
<string name="settings_search_history">खोज इतिहास</string>
<string name="settings_search_history_clear">खोज इतिहास मिटाएं</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">A játék fölött lebegő Smart Glasses gomb megjelenítése.</string>
<string name="display_filter_game_profile">Használt profil: %1$s – %2$s</string>
<string name="display_filter_default_profile">Alapértelmezett profil használata: %1$s</string>
<string name="settings_search_history">Keresési előzmények</string>
<string name="settings_search_history_clear">Keresési előzmények törlése</string>
</resources>
-2
View File
@@ -4166,6 +4166,4 @@
<string name="glasses_show_shortcut_hint">Tampilkan tombol Smart Glasses mengambang di atas game.</string>
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Menggunakan profil default: %1$s</string>
<string name="settings_search_history">Riwayat pencarian</string>
<string name="settings_search_history_clear">Hapus riwayat pencarian</string>
</resources>
-2
View File
@@ -4235,6 +4235,4 @@
<string name="glasses_show_shortcut_hint">Mostra il pulsante mobile Smart Glasses sopra il gioco.</string>
<string name="display_filter_game_profile">Profilo %1$s in uso: %2$s</string>
<string name="display_filter_default_profile">Profilo predefinito in uso: %1$s</string>
<string name="settings_search_history">Cronologia ricerche</string>
<string name="settings_search_history_clear">Cancella cronologia ricerche</string>
</resources>
-2
View File
@@ -4166,6 +4166,4 @@
<string name="glasses_show_shortcut_hint">ゲーム画面上に Smart Glasses のフローティングボタンを表示します。</string>
<string name="display_filter_game_profile">%1$s プロファイルを使用中: %2$s</string>
<string name="display_filter_default_profile">デフォルトプロファイルを使用中: %1$s</string>
<string name="settings_search_history">検索履歴</string>
<string name="settings_search_history_clear">検索履歴を消去</string>
</resources>
-2
View File
@@ -4166,6 +4166,4 @@
<string name="glasses_show_shortcut_hint">게임 위에 떠 있는 Smart Glasses 버튼을 표시합니다.</string>
<string name="display_filter_game_profile">%1$s 프로필 사용 중: %2$s</string>
<string name="display_filter_default_profile">기본 프로필 사용 중: %1$s</string>
<string name="settings_search_history">검색 기록</string>
<string name="settings_search_history_clear">검색 기록 지우기</string>
</resources>
-2
View File
@@ -4166,6 +4166,4 @@
<string name="glasses_show_shortcut_hint">Tunjukkan butang Smart Glasses terapung di atas permainan.</string>
<string name="display_filter_game_profile">Menggunakan profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Menggunakan profil lalai: %1$s</string>
<string name="settings_search_history">Sejarah carian</string>
<string name="settings_search_history_clear">Kosongkan sejarah carian</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Vis den flytende Smart Glasses-knappen over spillet.</string>
<string name="display_filter_game_profile">Bruker profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Bruker standardprofilen: %1$s</string>
<string name="settings_search_history">Søkelogg</string>
<string name="settings_search_history_clear">Tøm søkeloggen</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Toon de zwevende Smart Glasses-knop boven het spel.</string>
<string name="display_filter_game_profile">Profiel %1$s in gebruik: %2$s</string>
<string name="display_filter_default_profile">Standaardprofiel in gebruik: %1$s</string>
<string name="settings_search_history">Zoekgeschiedenis</string>
<string name="settings_search_history_clear">Zoekgeschiedenis wissen</string>
</resources>
-2
View File
@@ -4276,6 +4276,4 @@
<string name="glasses_show_shortcut_hint">Pokaż pływający przycisk Smart Glasses nad grą.</string>
<string name="display_filter_game_profile">Używany profil %1$s: %2$s</string>
<string name="display_filter_default_profile">Używany profil domyślny: %1$s</string>
<string name="settings_search_history">Historia wyszukiwania</string>
<string name="settings_search_history_clear">Wyczyść historię wyszukiwania</string>
</resources>
@@ -4235,6 +4235,4 @@
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
<string name="display_filter_game_profile">Perfil %1$s em utilização: %2$s</string>
<string name="display_filter_default_profile">Perfil predefinido em utilização: %1$s</string>
<string name="settings_search_history">Histórico de pesquisa</string>
<string name="settings_search_history_clear">Limpar histórico de pesquisa</string>
</resources>
-2
View File
@@ -4243,6 +4243,4 @@
<string name="glasses_show_shortcut_hint">Mostrar o botão flutuante do Smart Glasses sobre o jogo.</string>
<string name="display_filter_game_profile">Perfil %1$s em uso: %2$s</string>
<string name="display_filter_default_profile">Perfil predefinido em uso: %1$s</string>
<string name="settings_search_history">Histórico de pesquisa</string>
<string name="settings_search_history_clear">Limpar histórico de pesquisa</string>
</resources>
-2
View File
@@ -4236,6 +4236,4 @@
<string name="glasses_show_shortcut_hint">Afișează butonul plutitor Smart Glasses peste joc.</string>
<string name="display_filter_game_profile">Se folosește profilul %1$s: %2$s</string>
<string name="display_filter_default_profile">Se folosește profilul implicit: %1$s</string>
<string name="settings_search_history">Istoricul căutărilor</string>
<string name="settings_search_history_clear">Șterge istoricul căutărilor</string>
</resources>
-2
View File
@@ -4277,6 +4277,4 @@
<string name="glasses_show_shortcut_hint">Показывать плавающую кнопку Smart Glasses поверх игры.</string>
<string name="display_filter_game_profile">Используется профиль %1$s: %2$s</string>
<string name="display_filter_default_profile">Используется профиль по умолчанию: %1$s</string>
<string name="settings_search_history">История поиска</string>
<string name="settings_search_history_clear">Очистить историю поиска</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Visa den flytande Smart Glasses-knappen ovanpå spelet.</string>
<string name="display_filter_game_profile">Använder profilen %1$s: %2$s</string>
<string name="display_filter_default_profile">Använder standardprofilen: %1$s</string>
<string name="settings_search_history">Sökhistorik</string>
<string name="settings_search_history_clear">Rensa sökhistorik</string>
</resources>
-2
View File
@@ -4166,6 +4166,4 @@
<string name="glasses_show_shortcut_hint">แสดงปุ่ม Smart Glasses แบบลอยทับบนเกม</string>
<string name="display_filter_game_profile">ใช้โปรไฟล์ %1$s: %2$s</string>
<string name="display_filter_default_profile">ใช้โปรไฟล์เริ่มต้น: %1$s</string>
<string name="settings_search_history">ประวัติการค้นหา</string>
<string name="settings_search_history_clear">ล้างประวัติการค้นหา</string>
</resources>
-2
View File
@@ -4196,6 +4196,4 @@
<string name="glasses_show_shortcut_hint">Oyun üzerinde yüzen Smart Glasses düğmesini göster.</string>
<string name="display_filter_game_profile">%1$s profili kullanılıyor: %2$s</string>
<string name="display_filter_default_profile">Varsayılan profil kullanılıyor: %1$s</string>
<string name="settings_search_history">Arama geçmişi</string>
<string name="settings_search_history_clear">Arama geçmişini temizle</string>
</resources>
-2
View File
@@ -4276,6 +4276,4 @@
<string name="glasses_show_shortcut_hint">Показувати плаваючу кнопку Smart Glasses поверх гри.</string>
<string name="display_filter_game_profile">Використовується профіль %1$s: %2$s</string>
<string name="display_filter_default_profile">Використовується профіль за замовчуванням: %1$s</string>
<string name="settings_search_history">Історія пошуку</string>
<string name="settings_search_history_clear">Очистити історію пошуку</string>
</resources>
-2
View File
@@ -4166,6 +4166,4 @@
<string name="glasses_show_shortcut_hint">Hiển thị nút Smart Glasses nổi phía trên trò chơi.</string>
<string name="display_filter_game_profile">Đang dùng hồ sơ %1$s: %2$s</string>
<string name="display_filter_default_profile">Đang dùng hồ sơ mặc định: %1$s</string>
<string name="settings_search_history">Lịch sử tìm kiếm</string>
<string name="settings_search_history_clear">Xóa lịch sử tìm kiếm</string>
</resources>
@@ -4164,6 +4164,4 @@
<string name="glasses_show_shortcut_hint">在游戏画面上显示悬浮的 Smart Glasses 按钮。</string>
<string name="display_filter_game_profile">正在使用 %1$s 配置:%2$s</string>
<string name="display_filter_default_profile">正在使用默认配置:%1$s</string>
<string name="settings_search_history">搜索历史</string>
<string name="settings_search_history_clear">清除搜索历史</string>
</resources>
@@ -4164,6 +4164,4 @@
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
<string name="settings_search_history">搜尋記錄</string>
<string name="settings_search_history_clear">清除搜尋記錄</string>
</resources>
@@ -4164,6 +4164,4 @@
<string name="glasses_show_shortcut_hint">在遊戲畫面上顯示浮動的 Smart Glasses 按鈕。</string>
<string name="display_filter_game_profile">正在使用 %1$s 設定檔:%2$s</string>
<string name="display_filter_default_profile">正在使用預設設定檔:%1$s</string>
<string name="settings_search_history">搜尋記錄</string>
<string name="settings_search_history_clear">清除搜尋記錄</string>
</resources>
@@ -74,7 +74,6 @@
<string name="input_keep_shared">Keep shared</string>
<string name="input_independent_copy">Independent copy</string>
<string name="input_floating_stick">Start stick at touch position</string>
<string name="input_adaptive_capture">Adaptive touch area</string>
<string name="input_hide_idle">Hide stick when not in use</string>
<string name="input_tools">Tools</string>
<string name="input_quick_auto">Auto (%1$s)</string>
-4
View File
@@ -737,8 +737,6 @@
<string name="hud_size_minimal">Minimal</string>
<string name="hud_size_mega">Mega</string>
<string name="hud_size_strip">Strip</string>
<string name="hud_size_side_strip">Side strip</string>
<string name="hud_size_side_strip_hint">Drag the column to either side of the game. Tap the HUD to cycle sizes.</string>
<string name="hud_locked">Lock in place</string>
<string name="hud_locked_hint">Drag the HUD to move it. While it is locked, on-screen controls under it still work.</string>
<string name="hud_hold">Long press</string>
@@ -4459,8 +4457,6 @@
<string name="settings_search">Search settings</string>
<string name="settings_search_none">No setting matches \"%1$s\"</string>
<string name="settings_search_clear">Clear search</string>
<string name="settings_search_history">Search history</string>
<string name="settings_search_history_clear">Clear search history</string>
<string name="settings_place_settings">Settings</string>
<string name="settings_place_drawer">In-game menu</string>
<string name="settings_place_sheet">Steam or Desktop options (swipe up)</string>
-2
View File
@@ -3,8 +3,6 @@
<style name="AppTheme" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:colorBackground">#FF101418</item>
<item name="android:navigationBarColor">@android:color/black</item>
<item name="android:statusBarColor">@android:color/black</item>
<item name="android:windowLightStatusBar">false</item>
</style>
<style name="SessionTheme" parent="@android:style/Theme.Material.NoActionBar.Fullscreen">
<item name="android:windowBackground">@android:color/black</item>
@@ -15,29 +15,4 @@ class DependencyDetectorTest {
File(folder, "_CommonRedist/vcredist/2013/vcredist_x64.exe").writeText("x")
assertEquals(listOf("vcredist2013"), DependencyDetector.detect(folder).map { it.componentName })
}
@Test fun dotNetRuntimeInstallersMapToTheirOwnRuntime() {
assertEquals(listOf("dotnetcoredesktop3"), DependencyDetector.componentsFor("%INSTALLDIR%\\DotNetCore\\windowsdesktop-runtime-3.1.8-win-x64.exe"))
assertEquals(listOf("dotnetcoredesktop3"), DependencyDetector.componentsFor("_CommonRedist/DotNet/dotnet-runtime-3.1.32-win-x64.exe"))
assertEquals(listOf("dotnet50"), DependencyDetector.componentsFor("_CommonRedist/windowsdesktop-runtime-5.0.17-win-x64.exe"))
assertEquals(listOf("dotnetcoredesktop6"), DependencyDetector.componentsFor("_CommonRedist/windowsdesktop-runtime-6.0.16-win-x64.exe"))
assertEquals(listOf("dotnetcoredesktop8"), DependencyDetector.componentsFor("_CommonRedist/windowsdesktop-runtime-8.0.4-win-x64.exe"))
assertEquals(emptyList<String>(), DependencyDetector.componentsFor("_CommonRedist/windowsdesktop-runtime-9.0.0-win-x64.exe"))
}
@Test fun dotNetFrameworkInstallersKeepTheirMapping() {
assertEquals(listOf("dotnet48"), DependencyDetector.componentsFor("_CommonRedist/DotNet/4.8/ndp48-x86-x64-allos-enu.exe"))
assertEquals(listOf("dotnet472"), DependencyDetector.componentsFor("_CommonRedist/DotNet/4.7.2/NDP472-KB4054530-x86-x64-AllOS-ENU.exe"))
assertEquals(listOf("dotnet46"), DependencyDetector.componentsFor("_CommonRedist/DotNet/4.6.2/NDP462-KB3151800-x86-x64-AllOS-ENU.exe"))
assertEquals(listOf("dotnet40"), DependencyDetector.componentsFor("_CommonRedist/DotNet/dotNetFx40_Full_x86_x64.exe"))
assertEquals(listOf("dotnetcoredesktop6"), DependencyDetector.componentsFor("_CommonRedist/DotNet/6.0/setup_dotnet.exe"))
assertEquals(listOf("dotnet48"), DependencyDetector.componentsFor("_CommonRedist/DotNet/setup_dotnet.exe"))
}
@Test fun aBundledDesktopRuntimeFolderIsNotTakenForTheFramework() {
val folder = tmp.newFolder("Game")
File(folder, "DotNetCore").mkdirs()
File(folder, "DotNetCore/windowsdesktop-runtime-3.1.8-win-x64.exe").writeText("x")
assertEquals(listOf("dotnetcoredesktop3"), DependencyDetector.detect(folder).map { it.componentName })
}
}
@@ -205,36 +205,6 @@ class WinCompSourcesTest {
assertEquals("GOG", picks.getValue("vcredist2015_dll").kind)
}
@Test fun nativeD3dxSelectsItsEffectCompilersForEveryAutomaticSource() {
val catalog = listOf(ready("d3dx9"), ready("d3dcompiler_42"), ready("d3dcompiler_43")).associateBy { it.name }
for (origin in WinCompSources.Origin.values()) {
val finding = WinCompSources.Finding("d3dx9", "DirectX", origin, true)
val picks = AutoComponents.autoPicks(listOf(finding), catalog)
assertEquals(setOf("d3dx9", "d3dcompiler_42", "d3dcompiler_43"), picks.keys)
assertEquals(origin.name, picks.getValue("d3dcompiler_43").kind)
assertEquals(picks.getValue("d3dx9").args, picks.getValue("d3dcompiler_43").args)
assertEquals(setOf("d3dx9"), AutoComponents.autoPicks(listOf(finding), catalog, mapOf("d3dx9" to false)).keys)
assertTrue(AutoComponents.autoPicks(listOf(finding.copy(auto = false)), catalog).isEmpty())
}
assertEquals(setOf("d3dcompiler_42", "d3dcompiler_43"),
AutoComponents.autoPicks(emptyList(), catalog, mapOf("d3dx9" to true)).keys)
assertTrue(AutoComponents.autoPicks(emptyList(), catalog, mapOf("xact" to true)).isEmpty())
}
@Test fun effectCompilerSelectionKeepsIndependentFindingsAndSkipsUnavailableComponents() {
val catalog = listOf(ready("d3dx9"), ready("d3dcompiler_43"),
WinComponents.Component("d3dcompiler_42", "", "", "broken", emptyList(), emptyList())).associateBy { it.name }
val findings = listOf(
WinCompSources.Finding("d3dx9", "DirectX", WinCompSources.Origin.GOG, true),
WinCompSources.Finding("d3dcompiler_43", "Compiler", WinCompSources.Origin.STEAM, true),
)
val picks = AutoComponents.autoPicks(findings, catalog)
assertEquals(setOf("d3dx9", "d3dcompiler_43"), picks.keys)
assertEquals("STEAM", picks.getValue("d3dcompiler_43").kind)
assertEquals(picks.keys, AutoComponents.autoPicks(findings, catalog, mapOf("d3dx9" to false)).keys)
assertEquals(setOf("d3dx9"), AutoComponents.autoPicks(findings.take(1), catalog - "d3dcompiler_43").keys)
}
@Test fun theUsersSwitchWinsOverAnAutoPickEitherWay() {
val key = "12345"
WinComponents.setAuto(app, key, mapOf("d3dx9" to WinComponents.AutoReason("GOG", listOf("DirectX")), "xact" to WinComponents.AutoReason("GOG", listOf("XACT"))))
@@ -309,42 +279,6 @@ class WinCompSourcesTest {
}
}
@Test fun installedD3dxGainsCompilersWithoutReplacingUserChoices() = withFakeWorker {
AutoComponents.catalogOf = { _, _ -> catalog3 + ready("d3dcompiler_42") + ready("d3dcompiler_43") }
installedNow.addAll(catalog3.map { it.name })
val game = payback()
WinComponents.setUser(app, "1262580", "d3dcompiler_42", false)
AutoComponents.queueGame(app, game, asked = true)
assertEquals(listOf("d3dcompiler_43"), downloaded)
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll", "d3dcompiler_43"), WinComponents.picks(app, "1262580").toSet())
assertEquals(mapOf("d3dcompiler_42" to false), WinComponents.selection(app, "1262580").user)
assertTrue(AutoComponents.Pending.ids(app, "1262580").isEmpty())
AutoComponents.queueGame(app, game, asked = true)
assertEquals(listOf("d3dcompiler_43"), downloaded)
WinComponents.setUser(app, "1262580", "d3dx9", false)
AutoComponents.queueGame(app, game, asked = true)
assertEquals(setOf("vcredist2013_dll", "vcredist2019_dll"), WinComponents.picks(app, "1262580").toSet())
}
@Test fun manuallySelectedD3dxQueuesCompilersBeforeLaunch() = withFakeWorker {
AutoComponents.catalogOf = { _, _ -> catalog3 + ready("d3dcompiler_42") + ready("d3dcompiler_43") }
installedNow.add("d3dx9")
val game = game(tmp.newFolder("ManualEffects"), Library.ADDED)
val key = AutoComponents.appKey(game)!!
WinComponents.setUser(app, key, "d3dx9", true)
WinComponents.setUser(app, key, "d3dcompiler_42", false)
session = true
gameUp = true
assertTrue(AutoComponents.prepareLaunch(app, game))
assertEquals(listOf("d3dcompiler_43"), AutoComponents.Pending.ids(app, key))
assertTrue(downloaded.isEmpty())
gameUp = false
AutoComponents.drain(app)
assertEquals(listOf("d3dcompiler_43"), downloaded)
assertEquals(setOf("d3dx9", "d3dcompiler_43"), WinComponents.picks(app, key).toSet())
assertTrue(AutoComponents.Pending.ids(app, key).isEmpty())
}
@Test fun anExplicitCheckRefreshesTheCatalogAndAnOfflineCheckUsesTheCache() = withFakeWorker {
installedNow.addAll(catalog3.map { it.name })
val requests = ArrayList<Boolean>()
@@ -97,32 +97,6 @@ class WinComponentDetectorsTest {
assertEquals(emptyList<Pair<String, String>>(), SteamRedists.installScript(File(steamapps, "missing")))
}
@Test fun aDesktopRuntimeTheInstallScriptRunsIsInstalledInsteadOfTheFramework() {
val steamapps = tmp.newFolder("steamapps")
val game = File(steamapps, "common/Launcher Game").apply { mkdirs() }
File(steamapps, "appmanifest_435150.acf").writeText("\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228988\"\t\t\"228980\"\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n")
File(game, "installscript.vdf").writeText(
"""
"InstallScript"
{
"Run Process"
{
"DotNetCore"
{
"HasRunKey" "HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\435150"
"process 1" "%INSTALLDIR%\\DotNetCore\\windowsdesktop-runtime-3.1.8-win-x64.exe"
"command 1" "/install /quiet /norestart"
}
}
}
""".trimIndent(),
)
val context = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
val found = WinCompSources.steamList(context, game, 435150, "Launcher Game", auto = true)
assertEquals(listOf("vcredist2019_dll", "d3dx9", "dotnetcoredesktop3"), found.map { it.component })
assertTrue(found.all { it.auto && it.origin == WinCompSources.Origin.STEAM })
}
@Test fun thePrefixCountsOnlyWhatDroidDeckDidNotPutThere() {
val compat = tmp.newFolder("compatdata", "409710")
val pfx = File(compat, "pfx")
@@ -133,38 +133,6 @@ class DroidDeckHudPanelTest {
}
}
@Test fun sideStripOffersOnlyTheOnePercentLow() {
val readings = DroidDeckHudSize.SIDE_STRIP.rows
assertEquals(listOf("showLow1"), readings.filter { it.startsWith("showLow") })
}
@Test fun sideStripFitsOneSideOfAWideScreenAndUsesItsOwnReadingOrder() {
val app = RuntimeEnvironment.getApplication()
val view = DroidDeckHudView(app)
val config = DroidDeckHudConfig.DEFAULTS + mapOf(
"hudSize" to "side_strip",
"hudOrder" to "strip:showCPUUsage|showRAM;side_strip:showRAM|showFPS|showFPSGraph",
"showClock" to "0",
)
view.applyConfig(DroidDeckHudConfig.encode(config))
view.showForTest(SNAPSHOT, "DXVK", 0L)
val density = app.resources.displayMetrics.density
val height = (360 * density).toInt()
val width = height * 21 / 9
val sideMargin = (width - height * 16 / 9) / 2
view.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST),
)
assertTrue("HUD fits in one side margin", view.measuredWidth <= sideMargin)
assertTrue("HUD is taller than it is wide", view.measuredHeight > view.measuredWidth)
assertTrue("RAM is first", view.linesForTest().first().startsWith("RAM"))
assertTrue("FPS is second", view.linesForTest()[1].startsWith("FPS"))
assertTrue("The graph is inside the column", view.graphForTest()!!.right < view.measuredWidth)
}
@Test fun everySizeDrawsTheDPanelWithEverythingInsideIt() {
val stats = FrameStats()
var now = 1_000_000_000L
@@ -467,7 +467,6 @@ class InputLibraryTest {
val enabled = InputLibraries.read(context)
val changed = enabled.layouts.single { it.id == overlay.id }
assertEquals(true, changed.adaptiveSticks)
assertTrue(changed.elements.filter { it.kind == InputElementKind.STICK }.all { !it.hideStickAtRest && it.adaptiveCapture == true })
assertTrue(ControllerPrefs.read(context).adaptiveSticks)
assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK })
assertEquals(library.layouts.filter { it.id != overlay.id }, enabled.layouts.filter { it.id != overlay.id })
@@ -336,20 +336,6 @@ class OnScreenLayoutTest {
}
}
@Test fun dockedSticksStayVisibleWithoutExpandingTheirTouchArea() {
val custom = InputSurfaceElement(InputControl.LS, .2f, .2f, .2f, .3f,
id = "custom-stick", hideWhenIdle = true, adaptiveCapture = true)
val layout = SavedInputLayout("custom", "Custom", listOf(custom), aspect = 1.5f)
val overlay = OnScreenLayout.elements(context, layout, 1200, 800, Rect()).single()
assertTrue(overlay.adaptiveStick)
assertTrue(overlay.hideStickAtRest)
val docked = OnScreenLayout.elements(context, layout, 1200, 800, Rect(),
dock = OnScreenLayout.Dock(false, false)).single()
assertFalse(docked.adaptiveStick)
assertFalse(docked.hideStickAtRest)
assertTrue(docked.floating)
}
@Test fun dockedControlsStayInsideTheSafeAreaAtTheDefaultSizeWithoutAControllerKit() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
ControllerPrefs.setSize(context, 100)
@@ -1,38 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import java.io.File
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
@RunWith(RobolectricTestRunner::class)
class NativeGuestDefaultsTest {
@Test fun savedRuntimeOverridesDoNotDisableNativeExecution() {
val context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putBoolean("nativeUserland", false)
.putBoolean("prootFastPath", false)
.putBoolean("prootNoSeccomp", true)
.apply()
val root = LinuxRuntime.rootDir(context)
val hook = NativeGuest.hook(root)
val loader = File(root, "usr/lib/ld-linux-aarch64.so.1")
hook.parentFile?.mkdirs()
loader.writeText("fixture")
try {
assertTrue(NativeGuest.nextSession(context))
assertFalse(NativeGuest.enabled(context))
hook.writeText("fixture")
assertTrue(NativeGuest.enabled(context))
assertFalse(ProotFastPath.enabled(context, native = true))
} finally {
hook.delete()
loader.delete()
}
}
}
@@ -27,12 +27,14 @@ class ProotFastPathTest {
}
@Test fun fastPathStaysOffForTheRootfsProot() {
assertTrue(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = false))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_ROOTFS, native = false))
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_MISSING, native = false))
assertTrue(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_ROOTFS))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_MISSING))
assertFalse(ProotFastPath.allows(preference = false, noSeccomp = false, source = LinuxRuntime.PROOT_PACK))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = true, source = LinuxRuntime.PROOT_PACK))
}
@Test fun fastPathStaysOffWithoutProot() {
assertFalse(ProotFastPath.allows(source = LinuxRuntime.PROOT_PACK, native = true))
assertFalse(ProotFastPath.allows(preference = true, noSeccomp = false, source = LinuxRuntime.PROOT_PACK, nativeUserland = true))
}
}
@@ -5,8 +5,6 @@ import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.file.Files
import java.nio.file.Path
class PageCacheTrimTest {
private val meminfo = "MemFree: 1048576 kB\nActive(file): 2097152 kB\nInactive(file): 1048576 kB\n"
@@ -17,31 +15,4 @@ class PageCacheTrimTest {
@Test fun skipsSmallBuildUp() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(2000 * 1024, 1200 * 1024), 1000 * 1024))
@Test fun skipsWhenPlentyFree() = assertFalse(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(6000 * 1024, 5000 * 1024), 1000 * 1024))
@Test fun lowFreeAcceptsSmallerBuildUp() = assertTrue(PageCacheTrim.shouldTrim(PageCacheTrim.Mem(500 * 1024, 1200 * 1024), 1000 * 1024))
@Test fun bigFilesSkipLinksButEnterALinkedRoot() {
fun big(dir: Path, name: String): Path = Files.createFile(dir.resolve(name)).also {
java.io.RandomAccessFile(it.toFile(), "rw").use { it.setLength(PageCacheTrim.MIN_FILE_BYTES + 1) }
}
val base = Files.createTempDirectory("dd-trim")
try {
val root = Files.createDirectories(base.resolve("root"))
val outside = Files.createDirectories(base.resolve("outside"))
val big = big(root, "big.bin")
big(Files.createDirectories(root.resolve("sub")), "nested.bin")
Files.createFile(root.resolve("small.bin"))
big(outside, "outside.bin")
Files.createSymbolicLink(root.resolve("linked-dir"), outside)
Files.createSymbolicLink(root.resolve("linked-file"), big)
val rootLink = Files.createSymbolicLink(base.resolve("root-link"), root)
val expected = listOf("big.bin", "nested.bin")
assertEquals(expected, PageCacheTrim.bigFiles(root.toFile()).map { it.name }.sorted())
assertEquals(expected, PageCacheTrim.bigFiles(rootLink.toFile()).map { it.name }.sorted())
val dangling = Files.createSymbolicLink(base.resolve("dangling"), base.resolve("gone"))
assertTrue(PageCacheTrim.bigFiles(dangling.toFile()).isEmpty())
} finally {
base.toFile().deleteRecursively()
}
}
}
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.assumeFilePermissionsEnforced
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.text.SimpleDateFormat
@@ -9,7 +8,6 @@ import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import java.util.zip.ZipFile
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
@@ -146,136 +144,6 @@ class SessionLogShareZipTest {
}
}
@Test fun theEasyAntiCheatLauncherLogsFromGamePrefixesComeAlong() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-09-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat")
val prefix = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata/976730")
val second = File(app.getExternalFilesDir(null), "second-library-${UUID.randomUUID()}").apply { mkdirs() }
val library = SteamLibraries.add(app, second.path) as SteamLibraries.AddResult.Added
try {
File(session, "session.log").writeText("booted\n")
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/4815162342").apply { mkdirs() }
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 261\n")
File(eac, "old.log").apply {
writeText("stale\n")
setLastModified(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
}
val secondEac = File(second, "steamapps/compatdata/976730/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/b1d0a8c3").apply { mkdirs() }
File(secondEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n")
val signedEac = File(prefix.parentFile, "-1768546955/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(signedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30005\n")
val unsignedEac = File(prefix.parentFile, "2526420341/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(unsignedEac, "anticheatlauncher.log").writeText("[Error] Launch Error: 30007\n")
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val logs = archive.entries().toList().filter { it.name.startsWith("anticheat/976730/") }
assertEquals(2, logs.size)
assertTrue(logs.all { it.name.endsWith("/anticheatlauncher.log") && !it.name.contains("4815162342") })
val texts = logs.map { archive.getInputStream(it).bufferedReader().readText() }
assertTrue(texts.any { it.contains("Launch Error: 261") })
assertTrue(texts.any { it.contains("Launch Error: 206") })
val aliases = archive.entries().toList().filter { it.name.startsWith("anticheat/2526420341/") }
assertEquals(2, aliases.size)
assertEquals(2, aliases.map { it.name.split('/')[2] }.filter { it.startsWith("library1") }.toSet().size)
val aliasTexts = aliases.map { archive.getInputStream(it).bufferedReader().readText() }
assertTrue(aliasTexts.any { it.contains("Launch Error: 30005") })
assertTrue(aliasTexts.any { it.contains("Launch Error: 30007") })
}
} finally {
SteamLibraries.remove(app, library.entry.id)
out.deleteRecursively()
session.deleteRecursively()
prefix.deleteRecursively()
File(prefix.parentFile, "-1768546955").deleteRecursively()
File(prefix.parentFile, "2526420341").deleteRecursively()
second.deleteRecursively()
}
}
@Test fun theSessionsGameLogComesAlongWhenManyAntiCheatLogsAreFound() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-11-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-flood")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
val prefixes = (0 until 300).map { File(compatdata, "${900000 + it}") }
try {
File(session, "session.log").writeText("booted\n")
File(session, "steam-976730.log").writeText("proton: game started\n")
prefixes.forEach { prefix ->
val eac = File(prefix, "pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/0a1b").apply { mkdirs() }
File(eac, "anticheatlauncher.log").writeText("[Error] Launch Error: 206\n" + "x".repeat(64 * 1024))
}
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val game = archive.entries().toList().single { it.name.endsWith("/steam-976730.log") }
assertTrue(archive.getInputStream(game).bufferedReader().readText().contains("game started"))
}
} finally {
out.deleteRecursively()
session.deleteRecursively()
prefixes.forEach { it.deleteRecursively() }
}
}
@Test fun aDiscoveryFailureStaysInTheManifestWhenRecordsPassTheLimit() {
assumeFilePermissionsEnforced()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-10-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/manifest-limit")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata").apply { mkdirs() }
try {
repeat(300) {
File(session, "part-$it.log").writeText("line $it\n")
File(session, "wayland-$it.log").writeText("line $it\n")
File(session, "proton-$it.log").writeText("line $it\n")
}
assertTrue(compatdata.setReadable(false, false))
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
assertTrue(entries.length() > 512)
assertTrue(reasons.toString(), "filesystem-error" in reasons)
}
} finally {
compatdata.setReadable(true, false)
out.deleteRecursively()
session.deleteRecursively()
}
}
@Test fun aPrefixThatDeniesTheAntiCheatFolderIsRecordedAsADiscoveryFailure() {
assumeFilePermissionsEnforced()
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
val session = File(LinuxRuntime.logDir(app), "2026-12-05-12-steam").apply { mkdirs() }
val out = File(app.getExternalFilesDir(null), "agent-logs/anticheat-denied")
val compatdata = File(SessionPrefs.steamRoot(app, SessionPrefs.activeSteamClientArch(app)), "steamapps/compatdata")
val prefix = File(compatdata, "976731")
val users = File(prefix, "pfx/drive_c/users").apply { mkdirs() }
try {
File(session, "session.log").writeText("booted\n")
assertTrue(users.setExecutable(false, false))
val zip = EnhancedSessionLogShare.createLegacy(app, session, outputDirectory = out)!!
ZipFile(zip).use { archive ->
val manifest = JSONObject(archive.getInputStream(archive.getEntry("diagnostics-manifest.json")).bufferedReader().readText())
val entries = manifest.getJSONArray("entries")
val reasons = (0 until entries.length()).map { entries.getJSONObject(it) }
.filter { it.optString("origin") == "discovery" }.map { it.optString("reason") }
assertTrue(reasons.toString(), "filesystem-error" in reasons)
}
} finally {
users.setExecutable(true, false)
out.deleteRecursively()
session.deleteRecursively()
prefix.deleteRecursively()
}
}
@Test fun everyTextFileInTheZipIsScrubbedAndTheStoresAndToolsLogsComeAlong() {
val logs = LinuxRuntime.logDir(app)
val session = File(logs, "2026-10-08-01-steam").apply { mkdirs() }
@@ -4,7 +4,6 @@ import android.graphics.Color
import android.view.ContextThemeWrapper
import com.droiddeck.launcher.R
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@@ -23,17 +22,4 @@ class AppThemeTest {
assertEquals(0xFF, Color.alpha(color))
assertTrue(Color.luminance(color) < 0.1f)
}
@Test fun theStatusBarIsOpaqueAndDarkSoNothingLightShowsThroughIt() {
val themed = ContextThemeWrapper(RuntimeEnvironment.getApplication(), R.style.AppTheme)
val attrs = themed.obtainStyledAttributes(
intArrayOf(android.R.attr.statusBarColor, android.R.attr.windowLightStatusBar),
)
val color = attrs.getColor(0, Color.TRANSPARENT)
val lightIcons = attrs.getBoolean(1, true)
attrs.recycle()
assertEquals(0xFF, Color.alpha(color))
assertTrue(Color.luminance(color) < 0.1f)
assertFalse(lightIcons)
}
}
@@ -1,9 +1,6 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
@@ -21,7 +18,6 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
@@ -359,28 +355,6 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_UP, 1 to (490f to 170f))
}
@Test @GraphicsMode(GraphicsMode.Mode.NATIVE)
fun adaptiveSticksDrawAtRestUnlessExplicitlyHidden() {
val legacy = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
fun idlePixel(e: InputSurfaceElement): Int {
show(e)
val target = element(view, e.id)
val bitmap = Bitmap.createBitmap(target.width, target.height, Bitmap.Config.ARGB_8888)
return try {
target.draw(Canvas(bitmap))
bitmap.getPixel(target.width / 2, target.height / 2)
} finally {
bitmap.recycle()
}
}
assertTrue(Color.alpha(idlePixel(legacy)) > 0)
val visible = legacy.copy(adaptiveCapture = true, hideWhenIdle = false)
assertTrue(Color.alpha(idlePixel(visible)) > 0)
assertTrue(view.takesTouchAt(10f, 300f))
assertEquals(0, Color.alpha(idlePixel(visible.copy(hideWhenIdle = true))))
assertTrue(view.takesTouchAt(10f, 300f))
}
@Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() {
val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true)
@@ -1,15 +0,0 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertEquals
import org.junit.Test
class SettingsJumpTest {
@Test fun rowInTheMiddleOfThePageIsCentered() = assertEquals(1050f, centeredScroll(1500f, 100f, 1000f, 4000f), 0f)
@Test fun rowsNearTheEndsStopAtTheEnds() {
assertEquals(0f, centeredScroll(200f, 100f, 1000f, 4000f), 0f)
assertEquals(3000f, centeredScroll(3800f, 100f, 1000f, 4000f), 0f)
}
@Test fun pageThatFitsDoesNotScroll() = assertEquals(0f, centeredScroll(700f, 100f, 1000f, 800f), 0f)
}
@@ -1,43 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SettingsSearchHistoryTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() = SettingsSearchHistory.clear(context)
@Test fun newestComesFirstAndARepeatMovesUp() {
listOf("font", "cpu", "Font ").forEach { SettingsSearchHistory.add(context, it) }
assertEquals(listOf("Font", "cpu"), SettingsSearchHistory.items)
}
@Test fun blankSearchesAreNotKept() {
SettingsSearchHistory.add(context, " ")
assertEquals(emptyList<String>(), SettingsSearchHistory.items)
}
@Test fun onlyTheLatestAreKept() {
(1..SettingsSearchHistory.MAX + 2).forEach { SettingsSearchHistory.add(context, "search $it") }
assertEquals(SettingsSearchHistory.MAX, SettingsSearchHistory.items.size)
assertEquals("search ${SettingsSearchHistory.MAX + 2}", SettingsSearchHistory.items.first())
}
@Test fun savedSearchesLoadInOrderUntilCleared() {
listOf("one", "two, \"three\"").forEach { SettingsSearchHistory.add(context, it) }
SettingsSearchHistory.load(context)
assertEquals(listOf("two, \"three\"", "one"), SettingsSearchHistory.items)
SettingsSearchHistory.clear(context)
SettingsSearchHistory.load(context)
assertEquals(emptyList<String>(), SettingsSearchHistory.items)
}
}
+6 -8
View File
@@ -252,15 +252,13 @@ self-extractor stops at "Path not found", so the values it installs are applied
`goggame-<id>.info`, and a script's own `setRegistry` entries always win over the built-in table.
The script's `supportData` actions run right after: files and folders from the game folder
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}`,
`{localappdata}` or `{userappdata}` in the prefix, and `type: folder` without a source creates the
folder. Mods such as one-click editions ship their `Plugins.txt` and INI files this way. The
`savePath` action's `savePath` folder is created with the same path rules, including the common
case where a one-click edition names it again as a `supportData` folder. Paths match without regard
(`{app}`) or its support files (`{supportDir}`, `support/<id>/`) are copied to `{userdocs}` and
`{localappdata}` in the prefix, and `type: folder` without a source creates the folder. Mods such
as one-click editions ship their `Plugins.txt` and INI files this way. Paths match without regard
to case, links are copied as links, and a path outside those folders is refused. A file the
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` and
`.droiddeck-gog-save-path` in the prefix hold the actions' hashes, so they run once per script
revision and a player's later edits stay.
player already has is replaced only when the action says `overwrite`. `.droiddeck-gog-support` in
the prefix holds the actions' hash, so they run once per script revision and a player's later
edits stay.
A GOG game's exe comes from its own manifest first: `goggame-<id>.info`'s play task in category
`game` (`isPrimary` first), or a primary `launcher` task for launcher games, whose `path` stays
+2 -1
View File
@@ -14,7 +14,8 @@ after restarting. If no complete copy exists, the pack uses the checkout's pin.
- `tools/agent/dd-lab-build` builds the checkout with Gradle on the device (`processReleaseResources`
and `mergeDexRelease`), packs the linked resources and dex files into `overlay.apk`, writes
`overlay.json`, and stages both in the app's `files/lab/next`. It then recompiles the app without
an app image and restarts DroidDeck.
an app image and restarts DroidDeck. The resource linker uses IDs from the installed APK so
base and overlay code resolve the same resource names.
- Run by the app's own agent (`DD_AGENT` set), it writes `files/agent/lab-request` instead, and the
app runs the build in a process of its own, logging to `~/.cache/dd-lab-build.log`; the agent's
copy follows that log and exits with the build. A turn's processes end with the turn, so a build
+3
View File
@@ -27,6 +27,9 @@ Links of the form `droiddeck://settings/<section>` open a Settings section direc
| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine |
| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine |
| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, sync, wine |
| Run proot without seccomp | Settings › Performance (`droiddeck://settings/performance`) | proot |
| proot fast path | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot |
| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor |
| Host name | Settings › Performance (`droiddeck://settings/performance`) | name |
| Desktop runs as a user | Settings › Performance (`droiddeck://settings/performance`) | root, user, sudo, fakeroot |
+48
View File
@@ -134,6 +134,54 @@ fi
gradle=(./gradlew :app:processReleaseResources :app:mergeDexRelease --max-workers=2 -PskipRust=true -x buildVkBridgeServer
-Pandroid.aapt2FromMavenOverride=$HOME/aapt2/aapt2 -Pkotlin.compiler.execution.strategy=daemon
-Pkotlin.daemon.jvmargs=-Xmx${kotlin_heap}m -Dorg.gradle.jvmargs=-Xmx${gradle_heap}m --console=plain)
# Release package aliases rewrite the manifest but keep the resource table under the linker package.
resource_package=com.droiddeck.launcher
resource_cache=$cache/dd-lab-resource-ids
mkdir -p "$resource_cache"
resource_key=$(printf '%s\n' "$pkg" "$base" "$apk" | sha256sum | cut -d ' ' -f1)
stable_ids=$resource_cache/$resource_key.txt
if [ ! -s "$stable_ids" ]; then
progress checking 0 "reading the installed APK resource IDs"
if ! (
resource_work=$(mktemp -d "$resource_cache/.extract.XXXXXX") || exit 1
trap 'rm -rf "$resource_work"' EXIT
adb -s "$serial" pull "$apk" "$resource_work/base.apk" >/dev/null &&
"$HOME/aapt2/aapt2" dump resources "$resource_work/base.apk" > "$resource_work/resources.txt" &&
awk -v package="$resource_package" '
$1 == "Package" { in_package = ($2 == "name=" package) }
in_package && $1 == "resource" && $2 ~ /^0x[[:xdigit:]]+$/ {
print package ":" $3 " = " $2
count++
}
END { if (!count) exit 1 }
' "$resource_work/resources.txt" > "$resource_work/ids.txt" &&
mv "$resource_work/ids.txt" "$stable_ids"
); then
fail "could not read resource IDs from the installed APK"
fi
fi
resource_init=$resource_cache/link.gradle
cat > "$resource_init.part.$$" <<'EOF'
gradle.beforeProject { project ->
if (project.path == ':app') {
project.pluginManager.withPlugin('com.android.application') {
project.androidComponents.finalizeDsl { android ->
android.androidResources.additionalParameters.addAll([
'--stable-ids', project.providers.gradleProperty('droiddeckLabStableIds').get()
])
}
}
}
}
EOF
if cmp -s "$resource_init.part.$$" "$resource_init"; then
rm "$resource_init.part.$$"
else
mv "$resource_init.part.$$" "$resource_init"
fi
gradle+=(--init-script "$resource_init" "-PdroiddeckLabStableIds=$stable_ids")
progress planning
plan_file=$cache/dd-lab-build-plan
plan_key=$(
-4
View File
@@ -4,10 +4,6 @@ set -u
if [ -n "${DD_DEBUG_DIR:-}" ]; then
exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1
fi
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (already in gamescope on $GAMESCOPE_WAYLAND_DISPLAY)"
exec "$@"
fi
width=${DD_WIDTH:-1280}
height=${DD_HEIGHT:-720}
backend=${DD_GAMESCOPE_BACKEND:-wayland}
@@ -573,11 +573,11 @@ def inspector_url(url):
def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15, inspector=None,
command_line_api=False, connect_timeout=5):
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, timeout=connect_timeout) if t.get("webSocketDebuggerUrl")]
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:
@@ -841,75 +841,6 @@ class KeyboardWatcher(threading.Thread):
self.report(params.get("payload") == "true")
NATIVE_SUSPEND_JS = r"""/* Template arguments are inserted by Python after validation. */
async (operation, token, value, order) => {
const root = globalThis;
const leases = root.__droiddeckNativeSleep ??= { current: null, order: 0n, canceled: false };
const sequence = BigInt(order);
if (sequence < leases.order) return operation === "wake" ? "miss" : "expired";
if (sequence > leases.order) {
// An older renderer evaluation can arrive after a newer one. Only
// the newest Android request may own a still-in-flight preparation,
// including when its own preparation cannot start before deadline.
leases.order = sequence;
leases.canceled = false;
if (leases.current && !leases.current.result) {
leases.current.owner = token;
leases.current.wake = false;
} else {
leases.current = null;
}
}
const busy = () => root.SuspendResumeStore?.m_bSuspending === true;
const user = root.SteamClient?.User;
async function recover(lease) {
if (leases.current !== lease || lease.recovered || !lease.wake || busy()) return;
if (typeof user?.ResumeSuspendedGames !== "function") return;
lease.recovered = true;
try { await user.ResumeSuspendedGames(false); } catch { /* no session kick or retry */ }
}
if (operation === "wake") {
leases.canceled = true;
const lease = leases.current;
if (lease?.owner !== token) return "miss";
lease.wake = true;
// If login1 already signaled sleep and preparation had settled before
// wake, its normal resume notification owns recovery. A late success
// must recover again only because that notification could precede it.
if (lease.result === "prepared" && value !== "signaled") void recover(lease);
return "ack";
}
if (leases.canceled) return "expired";
const active = leases.current;
// A reused in-flight call still requires wake recovery, even when
// this request is too late to issue its own call.
if (active && !active.result) return "coalesced";
if (Date.now() >= value) return "expired";
if (typeof user?.PrepareForSystemSuspend !== "function") return "unavailable";
if (busy()) return "steam-busy";
if (active) return active.result;
const lease = { owner: token, result: null, wake: false, recovered: false };
leases.current = lease;
try {
const reply = await user.PrepareForSystemSuspend();
lease.result = reply?.result === 1 ? "prepared" : "rejected";
} catch {
lease.result = "uncertain";
}
if (lease.result === "prepared" && lease.wake) void recover(lease);
return lease.result;
}
"""
def native_suspend_lease(agent_dir, command, token, value, order):
expression = "(" + NATIVE_SUSPEND_JS + ")(" + ", ".join(map(json.dumps, (command, token, value, order))) + ")"
return cdp_eval(agent_dir, expression, timeout=1.45 if command == "prepare" else 0.75,
connect_timeout=0.35).get("value")
def steam_idle_inhibit(agent_dir, inhibit):
expression = """(async want => {
const toggle = () => new Promise(done => {
@@ -1387,23 +1318,6 @@ def main(argv):
time.sleep(0.5)
print({True: "yes", False: "no"}.get(value, "unknown"))
return {True: 0, False: 5}.get(value, 1)
if argv and argv[0] in ("--steam-prepare-native-suspend", "--steam-wake-native-suspend"):
if (len(argv) != 4 or re.fullmatch(r"[0-9a-f]{32}", argv[1]) is None or
re.fullmatch(r"[1-9][0-9]{0,19}", argv[3]) is None):
return 2
prepare = argv[0] == "--steam-prepare-native-suspend"
if prepare and (not argv[2].isascii() or not argv[2].isdigit() or len(argv[2]) > 14):
return 2
if not prepare and argv[2] not in ("signaled", "unsignaled", "uncertain"):
return 2
kind = "prepare" if prepare else "wake"
value = int(argv[2]) if prepare else argv[2]
try:
result = native_suspend_lease(Path(base) / "agent", kind, argv[1], value, argv[3])
except (AgentError, OSError, ValueError):
result = "uncertain"
print(result or "uncertain")
return 0 if result in ("prepared", "ack", "miss") else 1
if argv and argv[0] == "--steam-asleep":
expression = """(() => {
const store = globalThis.SuspendResumeStore;
@@ -7,7 +7,6 @@ import re
import subprocess
import sys
import threading
import time
import uuid
import gi
@@ -21,10 +20,6 @@ INTERFACE = NAME + ".Manager"
UPOWER = "org.freedesktop.UPower"
UPOWER_ROOT = "/org/freedesktop/UPower"
NATIVE_PREPARE_MS = 1500
STEAM_PREPARE_WAIT = 1.95
STEAM_PREPARE_START_MS = 850
STEAM_WAKE_WAIT = 1.25
STEAM_WAKE_RETRY_DELAYS = (0, 0.2, 0.5)
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
ASLEEP_WAIT = 6
INHIBIT_WAIT = 12
@@ -60,10 +55,6 @@ class LoginManager:
self.native_ready = self.directory / "steam-native-ready"
self.pending = None
self.pending_idle = False
self.native_preparation = None
self.native_signaled = False
self.native_order = None
self.native_wake_work = None
self.waiting = set()
self.timeout = None
self.preparation = None
@@ -99,7 +90,6 @@ class LoginManager:
if self.pending:
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
return
self.cancel_native_wake()
self.pending = uuid.uuid4().hex
self.pending_idle = False
self.notify(True)
@@ -143,42 +133,19 @@ class LoginManager:
return
self.pending = token
self.pending_idle = words[1:] == ["idle"]
# Idle requests never take ownership of Steam preparation. Preserve any
# earlier wake delivery so an in-flight prepare cannot outlive its wake.
if not self.pending_idle:
self.cancel_native_wake()
self.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
self.hold(token, self.prepared, token, "hold")
if self.pending_idle:
return
self.native_preparation = "pending"
order = self.native_order = str(time.monotonic_ns())
deadline = int(time.time() * 1000) + STEAM_PREPARE_START_MS
def prepare():
_, out = agent("--steam-prepare-native-suspend", token, str(deadline), order, timeout=STEAM_PREPARE_WAIT)
GLib.idle_add(self.steam_prepared, token, out.strip() or "uncertain")
threading.Thread(target=prepare, daemon=True).start()
def steam_prepared(self, token, outcome):
self.check_state()
if self.pending != token:
return False
self.native_preparation = outcome
self.native_signaled = True
print("== login1: Steam native preparation " + outcome, flush=True)
self.notify(True)
self.bus.flush(None, self.prepare_after_flush, token)
return False
def prepare_after_flush(self, connection, result, token):
try:
connection.flush_finish(result)
except GLib.Error as error:
print("== login1: cannot prepare native sleep: " + str(error), file=sys.stderr)
if self.pending == token:
self.resume()
self.resume()
return
self.check_state()
if self.pending == token:
@@ -302,49 +269,19 @@ class LoginManager:
self.notify(True)
self.bus.flush(None, self.finish_recovery, None)
return
token = self.pending
idle = self.pending_idle
native = self.native_preparation
signaled = self.native_signaled
order = self.native_order
self.native_order = None
self.pending = None
self.pending_idle = False
self.native_preparation = None
self.native_signaled = False
if self.preparation is not None:
GLib.source_remove(self.preparation)
self.preparation = None
if self.timeout is not None:
GLib.source_remove(self.timeout)
self.timeout = None
if not idle and (native is None or signaled):
if not idle:
self.notify(False)
if native in ("pending", "uncertain", "coalesced") or native == "prepared" and not signaled:
phase = "uncertain" if signaled else "unsignaled"
self.deliver_native_wake(token, phase, order)
self.release_later()
def cancel_native_wake(self):
if self.native_wake_work is not None:
self.native_wake_work.set()
self.native_wake_work = None
def deliver_native_wake(self, token, phase, order):
work = self.native_wake_work = threading.Event()
def deliver():
for delay in STEAM_WAKE_RETRY_DELAYS:
if work.wait(delay):
return
code, outcome = agent("--steam-wake-native-suspend", token, phase, order, timeout=STEAM_WAKE_WAIT)
if code == 0 and outcome.strip() in ("ack", "miss"):
return
if not work.is_set():
print("== login1: Steam native wake recovery not acknowledged", file=sys.stderr, flush=True)
threading.Thread(target=deliver, daemon=True).start()
def finish_recovery(self, connection, result, _data):
try:
connection.flush_finish(result)
@@ -968,7 +968,6 @@ def prepare_gog(sidecar, compat_data, launch_dir):
GOG_SCRIPTS = "goggame-*.script"
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
GOG_SUPPORT_MARK = ".droiddeck-gog-support"
GOG_SAVE_PATH_MARK = ".droiddeck-gog-save-path"
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
@@ -1717,7 +1716,7 @@ def prepare_steam_ea(argv, compat_data, launch_dir):
return REPLACED
def gog_script_actions(folder, name):
def gog_support_actions(folder):
found = []
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
@@ -1727,34 +1726,17 @@ def gog_script_actions(folder, name):
continue
for action in actions if isinstance(actions, list) else []:
install = action.get("install") if isinstance(action, dict) else None
if isinstance(install, dict) and install.get("action") == name \
if isinstance(install, dict) and install.get("action") == "supportData" \
and isinstance(install.get("arguments"), dict):
found.append((product, install["arguments"]))
return found
def gog_support_actions(folder):
return gog_script_actions(folder, "supportData")
def gog_case_child(path, part):
exact = path / part
try:
if not exact.exists() and path.is_dir():
return next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
except OSError:
pass
return exact
def gog_support_bases(folder, product, pfx):
user = Path(pfx) / "drive_c" / "users" / "steamuser"
support = Path(folder) / "support" / product
appdata = gog_case_child(user, "AppData")
return {"app": Path(folder), "supportdir": support, "support": support,
"userdocs": gog_case_child(user, "Documents"),
"localappdata": gog_case_child(appdata, "Local"),
"userappdata": gog_case_child(appdata, "Roaming")}
"userdocs": user / "Documents", "localappdata": user / "AppData" / "Local"}
def gog_inside(path, base):
@@ -1773,7 +1755,10 @@ def gog_support_path(text, bases):
base = bases[match.group(1).lower()]
path = base
for part in parts:
path = gog_case_child(path, part)
exact = path / part
if not exact.exists() and path.is_dir():
exact = next((child for child in path.iterdir() if child.name.lower() == part.lower()), exact)
path = exact
if path != base and not gog_inside(path.parent, base):
return None
return path, base
@@ -1845,44 +1830,6 @@ def gog_support_data(folder, compat_data, proton):
return "copied=%d%s" % (copied, note)
def gog_save_paths(folder, compat_data, proton):
actions = gog_script_actions(folder, "savePath")
if not actions:
return "none"
pfx = Path(compat_data) / "pfx" if compat_data else None
if not pfx or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
made = create_prefix(compat_data, proton)
if made not in ("present", "created") or not (pfx / "drive_c" / "users" / "steamuser").is_dir():
return "no-prefix"
stamp = hashlib.sha256(json.dumps(actions, sort_keys=True).encode("utf-8")).hexdigest()
marker = pfx / GOG_SAVE_PATH_MARK
try:
if marker.is_file() and marker.read_text() == stamp:
return "ready"
except OSError:
pass
paths = skipped = 0
for product, arguments in actions:
bases = gog_support_bases(folder, product, pfx)
found = gog_support_path(arguments.get("savePath") or arguments.get("target"), bases)
if found is None:
skipped += 1
continue
target, _root = found
try:
target.mkdir(parents=True, exist_ok=True)
paths += 1
except OSError:
skipped += 1
note = " skipped=%d" % skipped if skipped else ""
if not skipped:
try:
marker.write_text(stamp)
except OSError:
pass
return "paths=%d%s" % (paths, note)
def main(argv):
if os.environ.get("DROIDDECK_GOG_MAINTENANCE") == "1":
return 0
@@ -1929,7 +1876,6 @@ def main(argv):
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
log("gog save paths: " + gog_save_paths(folder, compat_data, os.environ.get("DD_STORE_PROTON", "")))
if store == "rockstar":
if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar):
if compat_data:
+1 -17
View File
@@ -24,8 +24,7 @@ class DesktopGpuWindowTest(unittest.TestCase):
fake.chmod(0o755)
def run_gpu(self, **env):
base = {k: v for k, v in os.environ.items()
if k not in KEYS + ("DD_DEBUG_DIR", "DD_DESKTOP_GPU_WINDOW", "GAMESCOPE_WAYLAND_DISPLAY")}
base = {k: v for k, v in os.environ.items() if k not in KEYS + ("DD_DEBUG_DIR", "DD_DESKTOP_GPU_WINDOW")}
base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), DD_WIDTH="1280", DD_HEIGHT="720", **env)
subprocess.run(["bash", str(GPU), "game.exe"], env=base, check=True, capture_output=True)
return json.loads(self.out.read_text())
@@ -52,21 +51,6 @@ class DesktopGpuWindowTest(unittest.TestCase):
self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"])
self.assertIsNone(run["env"]["DD_GPU_CHILD_WSI"])
def test_inside_a_gamescope_session_the_program_runs_in_it(self):
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DD_DEBUG_DIR", "DD_DESKTOP_GPU_WINDOW")}
env.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
WAYLAND_DISPLAY="", MESA_VK_WSI_DEBUG="linear", SDL_VIDEODRIVER="wayland")
script = "import json, os, sys; print(json.dumps([sys.argv[1:], {k: os.environ.get(k) for k in %r}]))" % (KEYS,)
out = subprocess.run(["bash", str(GPU), sys.executable, "-c", script, "--flag"], env=env,
check=True, capture_output=True, text=True).stdout
args, child = json.loads(out.splitlines()[-1])
self.assertFalse(self.out.exists())
self.assertEqual(args, ["--flag"])
self.assertEqual(child["WAYLAND_DISPLAY"], "")
self.assertEqual(child["MESA_VK_WSI_DEBUG"], "linear")
self.assertEqual(child["SDL_VIDEODRIVER"], "wayland")
self.assertIsNone(child["DD_DESKTOP_GPU_CHILD"])
def test_the_game_inside_the_window_gets_its_own_settings_back(self):
script = "import json, os; print(json.dumps({k: os.environ.get(k) for k in %r}))" % (KEYS,)
for saved, expected in (("linear", "linear"), ("", None)):
+1 -1
View File
@@ -63,7 +63,7 @@ class DesktopGamescopeBackendTest(unittest.TestCase):
)
gamescope.chmod(0o755)
env = dict(os.environ)
for name in ("DD_GAMESCOPE_BACKEND", "DD_DEBUG_DIR", "DD_FPS", "DD_REFRESH", "DD_HDR", "GAMESCOPE_WAYLAND_DISPLAY"):
for name in ("DD_GAMESCOPE_BACKEND", "DD_DEBUG_DIR", "DD_FPS", "DD_REFRESH", "DD_HDR"):
env.pop(name, None)
env.update(PATH=f"{root}{os.pathsep}{env.get('PATH', '')}",
GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0", DD_DESKTOP_GPU_WINDOW="0",
+2 -240
View File
@@ -1,9 +1,7 @@
from contextlib import contextmanager
import os
from pathlib import Path
import subprocess
import signal
import shutil
import tempfile
import time
import unittest
@@ -148,9 +146,9 @@ class SleepHandshakeTest(unittest.TestCase):
staged.write_text("wake\n")
staged.replace(self.dir / "steam-wake")
def request_native(self, token="1" * 32, idle=False):
def request_native(self, token="1" * 32):
staged = self.dir / "steam-native-sleep.tmp"
staged.write_text(token + (" idle" if idle else "") + "\n")
staged.write_text(token + "\n")
staged.replace(self.dir / "steam-native-sleep")
return token
@@ -327,132 +325,6 @@ class AsleepSteamTest(FakeAgentCase):
"--steam-idle-inhibit", "off"], self.asked())
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class NativePrepareTest(FakeAgentCase):
AGENT_EXIT = 0
def prepare_agent(self, delay, fail_first_wake=False, gated=False):
script = self.dir / "bin/droiddeck-agent"
prepare = f'sleep {delay}'
failed_wake = ':'
if gated:
prepare = f'while [ ! -f "{self.dir / "release-prepare"}" ]; do sleep 0.025; done'
failed_wake = f'while [ ! -f "{self.dir / "release-wake"}" ]; do sleep 0.025; done'
script.write_text(
f'#!/bin/sh\necho "$@" >> "{self.dir / "agent-calls"}"\n'
f'case "$1" in --steam-prepare-native-suspend) {prepare}; echo prepared;;\n'
'--steam-wake-native-suspend)\n'
f' if [ "{int(fail_first_wake)}" -eq 1 ] && [ ! -f "{self.dir / "wake-tried"}" ]; then\n'
f' touch "{self.dir / "wake-tried"}"; {failed_wake}; echo uncertain; exit 1; fi\n'
' echo ack;; esac\n'
"exit 0\n"
)
@contextmanager
def gated_agent(self, fail_first_wake=False):
self.prepare_agent(0, fail_first_wake=fail_first_wake, gated=True)
release_prepare = self.dir / "release-prepare"
release_wake = self.dir / "release-wake"
try:
yield release_prepare, release_wake
finally:
release_prepare.touch()
release_wake.touch()
def test_native_prepare_precedes_real_sleep_and_normal_wake_does_not_call_recovery(self):
with self.gated_agent() as (release_prepare, _):
token = self.request_native()
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
self.assertEqual(self.signals, [])
release_prepare.touch()
self.wait_for(lambda: self.signals == [True])
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
self.state(token, "paused")
self.state(token, "awake")
self.wait_for(lambda: self.signals == [True, False])
self.assertNotIn("--steam-wake-native-suspend", self.asked())
def test_awake_during_rpc_never_notifies_or_publishes_a_stale_pause(self):
with self.gated_agent() as (release_prepare, _):
token = self.request_native()
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
self.state(token, "awake")
self.wait_for(lambda: "unsignaled" in self.asked())
release_prepare.touch()
time.sleep(0.6)
self.assertFalse((self.dir / "steam-native-ready").exists())
self.assertEqual(self.signals, [])
subsequent = self.request_native("3" * 32)
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
self.assertEqual((self.dir / "steam-native-ready").read_text().strip(), subsequent)
self.state(subsequent, "awake")
self.wait_for(lambda: self.signals == [True, False])
def test_ambiguous_wake_retries_transient_discovery_with_same_token(self):
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
token = self.request_native()
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
self.state(token, "awake")
self.wait_for(lambda: (self.dir / "wake-tried").exists())
release_prepare.touch()
release_wake.touch()
self.wait_for(lambda: self.asked().count("--steam-wake-native-suspend") == 2)
time.sleep(0.8)
calls = (self.dir / "agent-calls").read_text().splitlines()
wakes = [call.split() for call in calls if call.startswith("--steam-wake-native-suspend ")]
self.assertEqual(len(wakes), 2)
self.assertEqual(wakes[0], wakes[1])
self.assertEqual(wakes[0][1:3], [token, "unsignaled"])
prepare = next(call.split() for call in calls if call.startswith("--steam-prepare-native-suspend "))
self.assertEqual(wakes[0][3], prepare[3])
self.assertEqual(self.signals, [])
def test_new_sleep_request_cancels_retry_of_older_wake(self):
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
first = self.request_native()
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
self.state(first, "awake")
self.wait_for(lambda: (self.dir / "wake-tried").exists())
second = self.request_native("3" * 32)
self.wait_for(lambda: second in self.asked())
release_prepare.touch()
release_wake.touch()
time.sleep(0.9)
self.assertEqual(self.asked().count("--steam-wake-native-suspend"), 1)
self.state(second, "awake")
def test_idle_request_preserves_retry_of_older_wake(self):
with self.gated_agent(fail_first_wake=True) as (release_prepare, release_wake):
first = self.request_native()
self.wait_for(lambda: "--steam-prepare-native-suspend" in self.asked())
self.state(first, "awake")
self.wait_for(lambda: (self.dir / "wake-tried").exists())
release_prepare.touch()
idle = self.request_native("3" * 32, idle=True)
ready = self.dir / "steam-native-ready"
self.wait_for(lambda: ready.exists() and ready.read_text().strip() == idle)
self.state(idle, "paused")
self.state(idle, "awake")
release_wake.touch()
self.wait_for(lambda: self.asked().count("--steam-wake-native-suspend") == 2)
wakes = [call for call in (self.dir / "agent-calls").read_text().splitlines()
if call.startswith("--steam-wake-native-suspend ")]
self.assertEqual(wakes[0], wakes[1])
self.assertEqual(wakes[0].split()[1:3], [first, "unsignaled"])
self.assertEqual(self.asked().count("--steam-prepare-native-suspend"), 1)
self.assertEqual(self.signals, [])
def test_timed_out_rpc_allows_sleep_and_wake_recovers_that_token(self):
self.prepare_agent(6)
token = self.request_native()
self.wait_for(lambda: self.signals == [True], timeout=3.0)
self.wait_for(lambda: (self.dir / "steam-native-ready").exists(), timeout=2.0)
self.state(token, "paused")
self.state(token, "awake")
self.wait_for(lambda: self.signals == [True, False] and "uncertain" in self.asked())
self.assertIn(token, self.asked())
class WithNetworkManagerTest(SleepHandshakeTest):
ARGS = ["--with-netmanager"]
@@ -470,115 +342,5 @@ class WithNetworkManagerTest(SleepHandshakeTest):
self.assertEqual(self.owner(NAME), self.process.pid)
@unittest.skipUnless(shutil.which("node"), "node is not installed")
class NativeSleepLeaseTest(unittest.TestCase):
def test_wake_and_prepare_ordering_in_the_renderer(self):
result = subprocess.run(["node", "-e", NATIVE_LEASE_CASES, str(SCRIPT.with_name("droiddeck-agent"))],
text=True, capture_output=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("PASS nine native preparation lease sequences", result.stdout)
NATIVE_LEASE_CASES = r'''const assert = require("node:assert/strict");
const fs = require("node:fs");
const text = fs.readFileSync(process.argv[1], "utf8").match(/NATIVE_SUSPEND_JS = r"""([\s\S]*?)"""/)[1];
const call = eval("(" + text + ")");
const run = (op, token, value) => call(op, token, value, token === a ? "100" : "200");
const a = "1".repeat(32);
const b = "2".repeat(32);
const future = () => Date.now() + 5000;
let invoked, resumes, result;
function setup() {
delete globalThis.__droiddeckNativeSleep;
globalThis.SuspendResumeStore = { m_bSuspending: false };
invoked = resumes = 0;
globalThis.SteamClient = { User: {
PrepareForSystemSuspend() { invoked++; return new Promise(resolve => { result = resolve; }); },
ResumeSuspendedGames(kick) { assert.equal(kick, false); resumes++; return Promise.resolve({ result: 1 }); }
}};
}
(async () => {
setup();
assert.equal(await run("prepare", a, Date.now() - 1), "expired");
assert.equal(await run("wake", a, "unsignaled"), "miss");
assert.equal(await run("prepare", a, future()), "expired");
assert.equal(invoked, 0);
setup();
let prep = run("prepare", a, future());
result({result: 1});
assert.equal(await prep, "prepared");
await run("wake", a, "signaled");
assert.equal(resumes, 0);
setup();
prep = run("prepare", a, future());
await run("wake", a, "unsignaled");
result({result: 1});
assert.equal(await prep, "prepared");
await run("wake", a, "unsignaled");
assert.equal(resumes, 1);
setup();
prep = run("prepare", a, future());
result({result: 1});
await prep;
await run("wake", a, "uncertain");
assert.equal(resumes, 1);
setup();
prep = run("prepare", a, future());
await run("wake", a, "unsignaled");
assert.equal(await run("prepare", b, future()), "coalesced");
result({result: 1});
await prep;
assert.equal(invoked, 1);
assert.equal(resumes, 0);
await run("wake", b, "uncertain");
assert.equal(resumes, 1);
setup();
prep = run("prepare", a, future());
await run("wake", a, "unsignaled");
globalThis.SuspendResumeStore.m_bSuspending = true;
result({result: 1});
await prep;
assert.equal(resumes, 0);
assert.equal(await run("prepare", b, future()), "steam-busy");
assert.equal(invoked, 1);
setup();
prep = run("prepare", a, future());
assert.equal(await run("wake", a, "uncertain"), "ack");
assert.equal(await run("prepare", b, Date.now() - 1), "coalesced");
assert.equal(await run("wake", a, "uncertain"), "miss");
assert.equal(await run("prepare", a, future()), "expired");
result({result: 1});
await prep;
assert.equal(invoked, 1);
assert.equal(resumes, 0);
await run("wake", b, "uncertain");
assert.equal(resumes, 1);
setup();
prep = run("prepare", a, future());
assert.equal(await run("wake", b, "uncertain"), "ack");
assert.equal(await run("prepare", b, future()), "expired");
result({result: 1});
await prep;
assert.equal(invoked, 1);
assert.equal(resumes, 1);
setup();
prep = run("prepare", a, future());
result({result: 1});
await prep;
assert.equal(await run("wake", a, "uncertain"), "ack");
assert.equal(await run("wake", a, "uncertain"), "ack");
assert.equal(resumes, 1);
console.log("PASS nine native preparation lease sequences");
})().catch(error => { console.error(error); process.exitCode = 1; });
'''
if __name__ == "__main__":
unittest.main()
-115
View File
@@ -667,10 +667,6 @@ def support_data(**arguments):
return {'install': {'action': 'supportData', 'arguments': arguments}, 'name': 'supportData'}
def save_path(**arguments):
return {'install': {'action': 'savePath', 'arguments': arguments}, 'name': 'saveFolders'}
class GogSupportData(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
@@ -854,117 +850,6 @@ class GogSupportData(unittest.TestCase):
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogSavePaths(unittest.TestCase):
def prefix(self, root):
user = Path(root) / 'compat/pfx/drive_c/users/steamuser'
user.mkdir(parents=True)
return user
def test_the_london_script_creates_its_save_path_and_keeps_player_settings(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1897848199')
user = self.prefix(root)
support = folder / 'support/1897848199'
(support / 'docs').mkdir(parents=True)
(folder / '__AppData').mkdir()
(folder / '__AppData/save.dat').write_text('save')
for name in ('Fallout4Prefs.ini', 'Fallout4.ini'):
(support / 'docs' / name).write_text('[Archive]\n')
for name in ('DLCList.txt', 'Plugins.txt', 'UserDownloadedContent.txt'):
(support / name).write_text('*LondonWorldSpace.esm\n')
gog_script(folder, '1897848199', [
save_path(savePath='{userdocs}/My Games/Fallout4', type='folder'),
set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\Fallout4',
valueName='Installed Path', valueData='{app}\\', valueType='string'),
support_data(type='folder', target='{userdocs}/My Games/Fallout4'),
support_data(type='folder', target='{localappdata}/Fallout4'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4Prefs.ini',
target='{userdocs}/My Games/Fallout4/Fallout4Prefs.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/docs/Fallout4.ini',
target='{userdocs}/My Games/Fallout4/Fallout4.ini'),
support_data(type='file', overwrite=True, source='{supportDir}/DLCList.txt',
target='{localappdata}/Fallout4/DLCList.txt'),
support_data(type='file', overwrite=True, source='{supportDir}/Plugins.txt',
target='{localappdata}/Fallout4/Plugins.txt'),
support_data(type='file', overwrite=True, source='{supportDir}/UserDownloadedContent.txt',
target='{localappdata}/Fallout4/UserDownloadedContent.txt'),
support_data(type='folder', overwrite=True, source='{app}/__AppData', target='{localappdata}/Fallout4'),
])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('copied=6', store.gog_support_data(folder, root + '/compat', '/proton'))
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_not_called()
saves = user / 'Documents/My Games/Fallout4'
self.assertTrue(saves.is_dir())
self.assertEqual('[Archive]\n', (saves / 'Fallout4.ini').read_text())
self.assertEqual('*LondonWorldSpace.esm\n', (user / 'AppData/Local/Fallout4/Plugins.txt').read_text())
self.assertTrue((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).is_file())
(saves / 'my settings.ini').write_text('player')
self.assertEqual('ready', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertEqual('player', (saves / 'my settings.ini').read_text())
def test_existing_prefix_base_names_keep_their_actual_case(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
(user / 'documents' / 'fixture').mkdir(parents=True)
(user / 'aPPdATA' / 'roaming').mkdir(parents=True)
gog_script(folder, '9', [
save_path(savePath='{UserDocs}/Fixture/Saves'),
save_path(savePath='{UserAppData}/Fixture/Settings'),
])
self.assertEqual('paths=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'documents/fixture/Saves').is_dir())
self.assertTrue((user / 'aPPdATA/roaming/Fixture/Settings').is_dir())
self.assertEqual({'documents', 'aPPdATA'}, {p.name for p in user.iterdir()})
self.assertEqual({'roaming'}, {p.name for p in (user / 'aPPdATA').iterdir()})
def test_only_save_path_actions_create_known_folders(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
user = self.prefix(root)
saves = user / 'Documents/My Games/Fallout4'
saves.mkdir(parents=True)
(saves / 'Fallout4Prefs.ini').write_text('player')
gog_script(folder, '9', [
set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string'),
{'install': {'action': 'createFolder', 'arguments': {'savePath': '{userdocs}/Other'}}},
save_path(savePath='{windir}/evil'),
save_path(savePath='{userdocs}/../../escape'),
save_path(savePath='{userappdata}/Ubisoft/Anno1404/Config'),
])
self.assertEqual('paths=1 skipped=2', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((user / 'AppData/Roaming/Ubisoft/Anno1404/Config').is_dir())
self.assertFalse((user / 'Documents/Other').exists())
self.assertFalse((Path(root) / 'escape').exists())
self.assertEqual('player', (saves / 'Fallout4Prefs.ini').read_text())
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_SAVE_PATH_MARK).exists())
def test_without_save_paths_no_prefix_is_made(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a',
valueData='b', valueType='string')])
with patch.object(store, 'create_prefix') as create:
self.assertEqual('none', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_not_called()
def test_a_missing_prefix_is_made_first(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='9')
gog_script(folder, '9', [save_path(savePath='{userdocs}/My Games/G')])
with patch.object(store, 'create_prefix', return_value='failed') as create:
self.assertEqual('no-prefix', store.gog_save_paths(folder, root + '/compat', '/proton'))
create.assert_called_once_with(root + '/compat', '/proton')
def made(compat_data, proton):
self.prefix(root)
return 'created'
with patch.object(store, 'create_prefix', side_effect=made):
self.assertEqual('paths=1', store.gog_save_paths(folder, root + '/compat', '/proton'))
self.assertTrue((Path(root) / 'compat/pfx/drive_c/users/steamuser/Documents/My Games/G').is_dir())
class GogRegistry(unittest.TestCase):
def test_patch_registration_uses_authentic_build_and_the_prefix_registry_executable(self):
with tempfile.TemporaryDirectory() as root: