From e8752b7d79c68d2acbec5a77ea31ba9e70233203 Mon Sep 17 00:00:00 2001
From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Date: Fri, 27 Nov 2026 02:46:29 -0500
Subject: [PATCH] fix(bottom): Steam dialogs take input over the parked Quick
Access menu; review fixes
---
.../com/droiddeck/launcher/SessionActivity.kt | 88 +++++++---
.../droiddeck/launcher/session/GameLinks.kt | 69 +++++---
.../launcher/session/LoopbackWebSocket.kt | 21 ++-
.../droiddeck/launcher/session/SteamQam.kt | 44 ++++-
.../droiddeck/launcher/ui/BottomArtPanel.kt | 19 +-
.../droiddeck/launcher/ui/BottomBrightness.kt | 10 +-
.../com/droiddeck/launcher/ui/BottomChrome.kt | 10 +-
.../droiddeck/launcher/ui/BottomDashboard.kt | 2 +-
.../droiddeck/launcher/ui/BottomGuidesPage.kt | 69 ++++----
.../droiddeck/launcher/ui/BottomIdleHome.kt | 2 +-
.../droiddeck/launcher/ui/BottomMirrorPage.kt | 49 ++++--
.../com/droiddeck/launcher/ui/BottomPages.kt | 3 +-
.../launcher/ui/BottomSteamQamPanel.kt | 163 ++++++++++--------
.../launcher/ui/SecondScreenPresentation.kt | 27 ++-
.../launcher/session/GameLinksTest.kt | 9 +
.../launcher/session/LoopbackWebSocketTest.kt | 83 +++++++++
.../launcher/session/SteamQamTest.kt | 16 +-
.../launcher/ui/BottomBrightnessTest.kt | 10 ++
docs/development/bottom-screen-guides.md | 2 +-
docs/development/bottom-screen.md | 10 +-
.../overlay/usr/local/bin/droiddeck-qam-relay | 89 ++++++++--
tools/tests/test_qam_relay.py | 24 ++-
22 files changed, 596 insertions(+), 223 deletions(-)
create mode 100644 app/src/test/java/com/droiddeck/launcher/session/LoopbackWebSocketTest.kt
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 3a47f6fd21..4214d4c5f3 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -2937,7 +2937,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode)
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
- WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedHolds == 0)
+ WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode) && composedOutputFree())
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
@@ -3990,6 +3990,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val presentation = secondScreenPresentation ?: return
presentation.showMenu(false)
if (secondScreenMode == SecondScreenMode.NONE) closeSecondScreen(reset = false) else updateKeyboardRoute()
+ if (gamePanelPending) uiHandler.post { restoreGamePanel(gestureGame) }
}
@@ -4456,9 +4457,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
typingReturnMode = null
automaticPanel = false
SessionPrefs.setSecondScreenPanel(this, desktopSession, SecondScreenMode.MENU.id)
+ bottomGameKey()?.let { SessionPrefs.setGameSecondScreenPanel(this, it, SecondScreenMode.MENU.id) }
+ gamePanelApplied = bottomGameKey() != null
drawerOpen = true
}
+ /** What bottom-screen memory is kept under: the game id in direct-run mode when there is one, else the focused game. */
+ private fun bottomGameKey(): String? =
+ if (SessionState.mode == SessionService.MODE_RUN) SessionState.gameId?.takeIf { it.isNotBlank() }?.let { "game:$it" } ?: gestureGame
+ else gestureGame
+
private fun settleDualScreenControls() {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
@@ -4578,17 +4586,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.bottomMenu = false
if (mode != SecondScreenMode.NONE) {
SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
- gestureGame?.let { SessionPrefs.setGameSecondScreenPanel(this, it, mode.id) }
- gamePanelApplied = gestureGame != null
+ bottomGameKey()?.let { SessionPrefs.setGameSecondScreenPanel(this, it, mode.id) }
+ gamePanelApplied = bottomGameKey() != null
}
selectSecondScreenMode(mode)
}
private var gamePanelApplied = false
+ private var gamePanelPending = false
private fun restoreGamePanel(game: String?) {
- if (secondScreenMode == SecondScreenMode.NONE || typingReturnMode != null || menuShownOnBottom() || pipUi) return
- val remembered = game?.let { SessionPrefs.gameSecondScreenPanel(this, it) }
+ if (secondScreenMode == SecondScreenMode.NONE || pipUi) return
+ // The bottom menu or field keyboard is in the way; the panel is restored once it closes.
+ if (typingReturnMode != null || menuShownOnBottom()) {
+ gamePanelPending = true
+ return
+ }
+ gamePanelPending = false
+ val remembered = game?.let { bottomGameKey() }?.let { SessionPrefs.gameSecondScreenPanel(this, it) }
val wanted = when {
remembered != null -> SecondScreenMode.opening(remembered, SessionState.deckPad, bottomPages().isNotEmpty(),
com.droiddeck.launcher.session.BottomDesktop.available(), SessionState.mode == SessionService.MODE_STEAM)
@@ -4651,10 +4666,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
BottomDashboard(
bottomPages(), com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
- gamePage = { gestureGame?.let { SessionPrefs.gameBottomPage(this@SessionActivity, it) } },
+ gamePage = { bottomGameKey()?.let { SessionPrefs.gameBottomPage(this@SessionActivity, it) } },
onPage = {
com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it)
- gestureGame?.let { game -> SessionPrefs.setGameBottomPage(this@SessionActivity, game, it) }
+ bottomGameKey()?.let { game -> SessionPrefs.setGameBottomPage(this@SessionActivity, game, it) }
},
strip = { pageId ->
com.droiddeck.launcher.ui.SessionBottomStrip(pageId) { if (::hud.isInitialized) hud.liveFps else null }
@@ -4673,10 +4688,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
takeScreenshot = ::captureScreenshot,
fps = { if (::hud.isInitialized) hud.liveFps else null },
runningGame = { gestureGame },
+ gameKey = ::bottomGameKey,
copyRegion = ::copyGameRegion,
+ sourceAspect = { gameSource()?.takeIf { it.width > 0 && it.height > 0 }?.let { it.width.toFloat() / it.height } ?: (16f / 9f) },
holdComposed = ::holdComposedOutput,
maskRegion = ::maskGameRegion,
- screenOff = { secondScreenPresentation?.screenOff() },
)
private fun captureScreenshot(onDone: (Boolean) -> Unit) = copyGameFrame { bitmap ->
@@ -4726,9 +4742,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
+ private fun gameSource(): android.view.SurfaceView? = if (glassesOutputActive) glassesScreen?.surfaceView
+ else if (bottomOutputActive) bottomGame?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
+
private fun copyGameRegion(region: android.graphics.RectF?, outWidth: Int, outHeight: Int, onFrame: (android.graphics.Bitmap?) -> Unit) {
- val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (bottomOutputActive) bottomGame?.surfaceView
- else if (::surfaceView.isInitialized) surfaceView else null
+ val source = gameSource()
val width = source?.width ?: 0
val height = source?.height ?: 0
if (source == null || width <= 0 || height <= 0 || outWidth <= 0 || outHeight <= 0 || source.holder.surface?.isValid != true) {
@@ -4747,16 +4765,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onFrame(null)
return
}
- try {
- android.view.PixelCopy.request(source, src, bitmap, { result ->
- if (result == android.view.PixelCopy.SUCCESS) onFrame(bitmap) else {
- bitmap.recycle()
- onFrame(null)
- }
- }, uiHandler)
- } catch (_: IllegalArgumentException) {
- bitmap.recycle()
- onFrame(null)
+ withPictureFrame { done ->
+ try {
+ android.view.PixelCopy.request(source, src, bitmap, { result ->
+ done()
+ if (result == android.view.PixelCopy.SUCCESS) onFrame(bitmap) else {
+ bitmap.recycle()
+ onFrame(null)
+ }
+ }, uiHandler)
+ } catch (_: IllegalArgumentException) {
+ done()
+ bitmap.recycle()
+ onFrame(null)
+ }
}
}
@@ -5062,7 +5084,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.ui.SessionTyping.returnFocus(this, taskId)
val mode = typingReturnMode ?: return
typingReturnMode = null
- uiHandler.post { if (secondScreenMode == SecondScreenMode.KEYBOARD_TRACKPAD) selectSecondScreenMode(mode) }
+ uiHandler.post {
+ if (secondScreenMode == SecondScreenMode.KEYBOARD_TRACKPAD) selectSecondScreenMode(mode)
+ if (gamePanelPending) restoreGamePanel(gestureGame)
+ }
}
private fun updateKeyboardRoute() {
@@ -5993,7 +6018,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (zeroCopyActive()) {
WaylandCompositor.nativeSetZeroCopy(false)
val restore = java.util.concurrent.atomic.AtomicBoolean(false)
- val back = { if (restore.compareAndSet(false, true)) WaylandCompositor.nativeSetZeroCopy(composedHolds == 0) }
+ pauseCaptures++
+ val back = {
+ if (restore.compareAndSet(false, true)) {
+ pauseCaptures--
+ if (!isDestroyed) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
+ }
+ }
uiHandler.postDelayed({ capturePausedFrame(manual = true, onDone = back) }, ZERO_COPY_SETTLE_MS)
uiHandler.postDelayed({ back() }, ZERO_COPY_RESTORE_MS)
} else {
@@ -6003,6 +6034,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var composedHolds = 0
+ private var pauseCaptures = 0
+
+ private fun composedOutputFree() = composedHolds == 0 && pauseCaptures == 0
private var mirrorMask: android.view.View? = null
private var maskedRegion: android.graphics.RectF? = null
private var maskDim = false
@@ -6035,15 +6069,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val w = surfaceView.width
val h = surfaceView.height
mask.layoutParams = FrameLayout.LayoutParams(((r.right - r.left) * w).toInt(), ((r.bottom - r.top) * h).toInt(), Gravity.TOP or Gravity.START).apply {
- leftMargin = surfaceView.left + (r.left * w).toInt()
- topMargin = surfaceView.top + (r.top * h).toInt()
+ leftMargin = surfaceView.left - sessionRoot.paddingLeft + (r.left * w).toInt()
+ topMargin = surfaceView.top - sessionRoot.paddingTop + (r.top * h).toInt()
}
mask.visibility = android.view.View.VISIBLE
}
private fun holdComposedOutput(hold: Boolean) {
composedHolds = (composedHolds + if (hold) 1 else -1).coerceAtLeast(0)
- if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedHolds == 0)
+ if (zeroCopyActive()) WaylandCompositor.nativeSetZeroCopy(composedOutputFree())
}
private fun zeroCopyActive(): Boolean =
@@ -6773,10 +6807,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else -> BottomDashboard(
pages, com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
- gamePage = { gestureGame?.let { SessionPrefs.gameBottomPage(this@SessionActivity, it) } },
+ gamePage = { bottomGameKey()?.let { SessionPrefs.gameBottomPage(this@SessionActivity, it) } },
onPage = {
com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it)
- gestureGame?.let { game -> SessionPrefs.setGameBottomPage(this@SessionActivity, game, it) }
+ bottomGameKey()?.let { game -> SessionPrefs.setGameBottomPage(this@SessionActivity, game, it) }
},
bar = bar(getString(R.string.second_mode_dashboard)),
strip = { pageId ->
diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameLinks.kt b/app/src/main/java/com/droiddeck/launcher/session/GameLinks.kt
index b503da1959..c6e8a73dc6 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/GameLinks.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/GameLinks.kt
@@ -59,7 +59,15 @@ object GameLinks {
}
/** Direct pages for what Wikidata has no ID for, found from each site's own routes rather than a web search. */
- internal fun direct(name: String, found: List, exists: (String) -> Boolean, strategyWiki: (String) -> String?): List {
+ internal fun direct(name: String, found: List, exists: (String) -> Boolean, strategyWiki: (String) -> String?): List =
+ merge(found, discover(name, found, exists, strategyWiki))
+
+ /** Wikidata's links with the discovered ones; a discovered IGN wiki replaces Wikidata's IGN game page. */
+ internal fun merge(found: List, extra: List): List =
+ found.filterNot { it.kind == Kind.IGN && extra.any { e -> e.kind == Kind.IGN } } +
+ extra.filterNot { e -> e.kind != Kind.IGN && found.any { it.kind == e.kind } }
+
+ internal fun discover(name: String, found: List, exists: (String) -> Boolean, strategyWiki: (String) -> String?): List {
val have = found.map { it.kind }.toSet()
val slugs = slugs(name)
fun first(urls: List) = urls.firstOrNull(exists)
@@ -73,7 +81,7 @@ object GameLinks {
?.let { Link(Kind.WIKI, "https://$it.fandom.com/") },
if (Kind.STRATEGYWIKI in have) null else strategyWiki(name.split(":").first().trim())?.let { Link(Kind.STRATEGYWIKI, it) },
)
- return found.filterNot { it.kind == Kind.IGN && extra.any { e -> e.kind == Kind.IGN } } + extra
+ return extra
}
internal fun parseOpenSearch(json: String, title: String): String? = runCatching {
@@ -83,38 +91,44 @@ object GameLinks {
(0 until titles.length()).firstOrNull { titles.getString(it).equals(title, ignoreCase = true) }?.let { urls.getString(it) }
}.getOrNull()
- private fun exists(url: String): Boolean = runCatching {
+ /** Whether the page exists, or null when the site could not be asked. */
+ private fun exists(url: String): Boolean? = runCatching {
val c = URL(url).openConnection() as HttpURLConnection
c.instanceFollowRedirects = false
c.connectTimeout = 6_000
c.readTimeout = 6_000
c.setRequestProperty("User-Agent", BROWSER)
- try { c.responseCode in 200..399 } finally { c.disconnect() }
- }.getOrDefault(false)
+ try { c.responseCode.takeIf { it < 500 }?.let { it in 200..399 } } finally { c.disconnect() }
+ }.getOrNull()
- private fun strategyWiki(title: String): String? = runCatching {
+ private fun strategyWiki(title: String): Result = runCatching {
parseOpenSearch(get("https://strategywiki.org/w/api.php?action=opensearch&namespace=0&limit=5&format=json&search=" +
URLEncoder.encode(title, "UTF-8")), title)
- }.getOrNull()
+ }
fun links(context: Context, appId: Long, name: String? = null): List {
val cache = File(context.cacheDir, "game-links/$appId.json")
val fresh = cache.isFile && System.currentTimeMillis() - cache.lastModified() < CACHE_MS
val text = if (fresh) runCatching { cache.readText() }.getOrNull() else null
- val json = text ?: runCatching {
+ val fetched = text ?: runCatching {
get("https://query.wikidata.org/sparql?format=json&query=" + URLEncoder.encode(sparql(appId), "UTF-8"))
}.getOrNull()?.also { runCatching { cache.parentFile?.mkdirs(); cache.writeText(it) } }
- ?: runCatching { cache.readText() }.getOrNull()
+ val json = fetched ?: runCatching { cache.readText() }.getOrNull()
val wikidata = json?.let { runCatching { parse(it) }.getOrNull() }.orEmpty()
val withFixes = if (wikidata.any { it.kind == Kind.PCGAMINGWIKI }) wikidata
else wikidata + Link(Kind.PCGAMINGWIKI, "https://www.pcgamingwiki.com/api/appid.php?appid=$appId")
if (name.isNullOrBlank()) return withFixes
- val directCache = File(context.cacheDir, "game-links/$appId-direct-v2.json")
+ // Only the discovered pages are cached, and only when every site answered, so an offline lookup is retried.
+ val directCache = File(context.cacheDir, "game-links/$appId-direct-v3.json")
val cached = directCache.takeIf { it.isFile && System.currentTimeMillis() - it.lastModified() < CACHE_MS }
?.let { runCatching { readLinks(it.readText()) }.getOrNull() }
- if (cached != null) return cached
- return direct(name, withFixes, ::exists, ::strategyWiki)
- .also { runCatching { directCache.parentFile?.mkdirs(); directCache.writeText(writeLinks(it)) } }
+ if (cached != null) return merge(withFixes, cached)
+ var complete = fetched != null
+ val extra = discover(name, withFixes, { url -> exists(url).also { if (it == null) complete = false } == true }) { title ->
+ strategyWiki(title).onFailure { complete = false }.getOrNull()
+ }
+ if (complete) runCatching { directCache.parentFile?.mkdirs(); directCache.writeText(writeLinks(extra)) }
+ return merge(withFixes, extra)
}
internal fun writeLinks(links: List): String =
@@ -215,22 +229,25 @@ object GuideLibrary {
val ext = IMAGE_TYPES[c.contentType?.substringBefore(';')?.trim()?.lowercase()] ?: return null
if (c.contentLengthLong > MAX_MAP_BYTES) return null
val out = File(dir(context, game, "maps").apply { mkdirs() }, "${System.currentTimeMillis()}.$ext")
- c.inputStream.use { input ->
- out.outputStream().use { output ->
- val buf = ByteArray(64 * 1024)
- var total = 0L
- while (true) {
- val n = input.read(buf)
- if (n < 0) break
- total += n
- if (total > MAX_MAP_BYTES) {
- output.close()
- out.delete()
- return null
+ // Written beside the map and renamed when complete, so the Maps list never shows a partial image.
+ val part = File(out.path + ".part")
+ try {
+ c.inputStream.use { input ->
+ part.outputStream().use { output ->
+ val buf = ByteArray(64 * 1024)
+ var total = 0L
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ total += n
+ if (total > MAX_MAP_BYTES) return null
+ output.write(buf, 0, n)
}
- output.write(buf, 0, n)
}
}
+ if (!part.renameTo(out)) return null
+ } finally {
+ part.delete()
}
out
} finally {
diff --git a/app/src/main/java/com/droiddeck/launcher/session/LoopbackWebSocket.kt b/app/src/main/java/com/droiddeck/launcher/session/LoopbackWebSocket.kt
index 0e65fd364c..851a5996d1 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/LoopbackWebSocket.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/LoopbackWebSocket.kt
@@ -1,4 +1,4 @@
-package com.droiddeck.launcher.companion
+package com.droiddeck.launcher.session
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
@@ -7,6 +7,7 @@ import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.Socket
+import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
@@ -19,7 +20,7 @@ class LoopbackWebSocket(port: Int, path: String = "/", connectTimeoutMs: Int = 1
init {
try {
socket.connect(InetSocketAddress("127.0.0.1", port), connectTimeoutMs)
- socket.soTimeout = readTimeoutMs
+ socket.soTimeout = UPGRADE_TIMEOUT_MS
socket.tcpNoDelay = true
out = socket.getOutputStream()
input = DataInputStream(socket.getInputStream().buffered())
@@ -28,11 +29,19 @@ class LoopbackWebSocket(port: Int, path: String = "/", connectTimeoutMs: Int = 1
"Sec-WebSocket-Key: $key\r\nSec-WebSocket-Version: 13\r\n\r\n").toByteArray())
out.flush()
val status = line(input) ?: throw IOException("no upgrade response")
- if (!status.contains(" 101")) throw IOException("upgrade refused: $status")
+ if (status.split(' ').getOrNull(1) != "101") throw IOException("upgrade refused: $status")
+ val headers = HashMap()
while (true) {
val header = line(input) ?: throw IOException("upgrade cut short")
if (header.isEmpty()) break
+ val colon = header.indexOf(':')
+ if (colon > 0) headers[header.substring(0, colon).trim().lowercase()] = header.substring(colon + 1).trim()
}
+ if (!headers["upgrade"].equals("websocket", ignoreCase = true) ||
+ headers["connection"]?.split(',')?.none { it.trim().equals("upgrade", ignoreCase = true) } != false ||
+ headers["sec-websocket-accept"] != accept(key)
+ ) throw IOException("bad upgrade headers")
+ socket.soTimeout = readTimeoutMs
} catch (e: Exception) {
runCatching { socket.close() }
throw e
@@ -103,7 +112,11 @@ class LoopbackWebSocket(port: Int, path: String = "/", connectTimeoutMs: Int = 1
runCatching { socket.close() }
}
- private companion object {
+ internal companion object {
const val MAX_FRAME = 16L * 1024 * 1024
+ const val UPGRADE_TIMEOUT_MS = 3_000
+
+ fun accept(key: String): String = Base64.getEncoder().encodeToString(
+ MessageDigest.getInstance("SHA-1").digest((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").toByteArray()))
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt
index 43c19f2f7a..cc74b34168 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt
@@ -29,13 +29,22 @@ object SteamQam {
const width = (h) => g.__ddQamAspect > 0 ? Math.round(h * g.__ddQamAspect) : 0;
if (!c.__ddQam) {
c.__ddQam = c.ComputeOverallMinimumRequestedComposition;
- c.ComputeOverallMinimumRequestedComposition = function (...a) {
- const v = c.__ddQam.apply(this, a);
- return v === 2 && ours() ? 1 : v;
- };
m.__ddQam = m.OnMenuDeactivated;
m.OnMenuDeactivated = function (d) { if (d === QAM && held() && !g.__ddQamTop) return; return m.__ddQam.call(this, d); };
}
+ if (c.__ddQamV !== 2) {
+ c.__ddQamV = 2;
+ // Only the menu's own overlay request is lowered: a dialog over the game still needs Steam to take input.
+ c.ComputeOverallMinimumRequestedComposition = function (...a) {
+ const v = c.__ddQam.apply(this, a);
+ if (v !== 2 || !ours()) return v;
+ m.IsSideMenuVisible = () => false;
+ m.IsSideMenuInteractable = () => false;
+ let without;
+ try { without = c.__ddQam.apply(this, a); } finally { delete m.IsSideMenuVisible; delete m.IsSideMenuInteractable; }
+ return without >= 2 ? v : 1;
+ };
+ }
const views = () => popup?.m_rgChildBrowserViews || [];
const backdrop = (hide) => {
const doc = popup?.m_popup?.document;
@@ -64,6 +73,7 @@ object SteamQam {
}
if (!held()) {
g.__ddQamTop = false;
+ g.__ddQamPress = undefined;
if (!g.__ddQamOn) return;
g.__ddQamOn = false;
backdrop(false);
@@ -71,6 +81,14 @@ object SteamQam {
c.EnsureCorrectComposition?.();
return;
}
+ // Steam sends the pad to an open side menu, so a dialog over the game would get no input: step aside until it closes.
+ const dialog = nav?.m_rgGamepadNavigationTrees?.some(t => t.m_ID?.startsWith("ModalDialogOverlay") && t.m_Root?.m_element?.isConnected);
+ if (dialog && !g.__ddQamTop) {
+ g.__ddQamPress = W.m_flLastQuickAccessPressMS || 0;
+ if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus();
+ if (g.__ddQamOn) { g.__ddQamOn = false; backdrop(false); c.EnsureCorrectComposition?.(); }
+ return;
+ }
// The Quick Access button shows the menu on the top screen as usual; closing it there parks it again.
const press = W.m_flLastQuickAccessPressMS || 0;
if (g.__ddQamPress === undefined) g.__ddQamPress = press;
@@ -138,15 +156,29 @@ object SteamQam {
fun release(context: Context, relayPort: Int) {
eval(context, script(false))
+ stopRelay(context, relayPort)
+ }
+
+ fun stopRelay(context: Context, relayPort: Int) {
if (relayPort > 0) helper(context, "stop", relayPort.toString())
}
+ /** Starts the guest relay to Steam's DevTools and finds the menu's page; the relay is stopped again when there is none. */
fun target(context: Context): Target? = runCatching {
val devtools = File(AgentGuest.dir(context), "cdp-port").readText().trim().toInt()
- val relay = helper(context, "start", devtools.toString())?.trim()?.toIntOrNull() ?: return null
- parseTarget(relay, get(relay, "/json"))
+ val (relay, secret) = parseRelay(helper(context, "start", devtools.toString())) ?: return null
+ val found = runCatching { parseTarget(relay, get(relay, "/$secret/json"))?.let { it.copy(path = "/$secret${it.path}") } }
+ if (found.getOrNull() == null) helper(context, "stop", relay.toString())
+ found.getOrThrow()
}.onFailure { android.util.Log.e(TAG, "no quick access target: $it") }.getOrNull()
+ internal fun parseRelay(text: String?): Pair? {
+ val parts = text?.trim()?.split(' ') ?: return null
+ val port = parts.getOrNull(0)?.toIntOrNull() ?: return null
+ val secret = parts.getOrNull(1)?.takeIf { it.matches(Regex("[0-9a-f]{16,64}")) } ?: return null
+ return port to secret
+ }
+
private fun helper(context: Context, vararg args: String): String? = runCatching {
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf("droiddeck-qam-relay") + args)).put("timeout", 5.0)
val answer = AgentGuest.call(context, request, 8_000, trusted = true)
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomArtPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomArtPanel.kt
index 23d72378ba..a180ccb25f 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomArtPanel.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomArtPanel.kt
@@ -46,6 +46,7 @@ import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
private const val ART_POLL_MS = 2_000L
+private const val RESCAN_MS = 30_000L
private const val DRIFT_MS = 28_000
/** The game's art filling the bottom screen with a slow pan and zoom, for the running game or the one selected in Steam. */
@@ -56,20 +57,28 @@ internal fun ArtPanel(runningGame: () -> String?) {
var playing by remember { mutableStateOf(false) }
FullScreenChrome()
LaunchedEffect(Unit) {
- val games = withContext(Dispatchers.IO) { runCatching { Library.steamGames(context) }.getOrDefault(emptyList()) }
+ var games = emptyList()
+ var scanned = 0L
while (isActive) {
val running = runningGame()?.toLongOrNull()
val shown = running ?: withContext(Dispatchers.IO) { runCatching { AgentGuest.selectedSteamAppId(context) }.getOrNull() }
- if (shown == null || shown != game?.appId?.toLong()) {
- withContext(Dispatchers.IO) { IdleHome.load(context, games, shown) }?.let { game = it }
+ val missing = games.isEmpty() || (shown != null && games.none { it.appId.toLong() == shown })
+ if (missing && (scanned == 0L || System.currentTimeMillis() - scanned > RESCAN_MS)) {
+ withContext(Dispatchers.IO) { runCatching { Library.steamGames(context) }.getOrNull() }?.let { games = it }
+ scanned = System.currentTimeMillis()
}
+ // Reloaded every poll so stats that failed to load once still arrive; the crossfade is keyed by app id.
+ withContext(Dispatchers.IO) { IdleHome.load(context, games, shown) }?.takeIf { it != game }?.let { game = it }
playing = running != null && running == game?.appId?.toLong()
delay(ART_POLL_MS)
}
}
Box(Modifier.fillMaxSize().background(Color.Black).testTag("bottom-art")) {
- Crossfade(game, label = "art") { g ->
- if (g != null) ArtScene(g, playing)
+ // Keyed by app id so a refreshed game keeps its pan; the fading-out scene keeps its last details.
+ val seen = remember { HashMap() }
+ game?.let { seen[it.appId] = it }
+ Crossfade(game?.appId, label = "art") { id ->
+ seen[id]?.let { ArtScene(it, playing) }
}
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomBrightness.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomBrightness.kt
index f38a5afb07..2cc7f31fad 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomBrightness.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomBrightness.kt
@@ -45,8 +45,14 @@ internal object BottomBrightness {
Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS) * 100 / 255
}.getOrDefault(60))
- /** Auto-dim never brightens a screen the user set darker. */
- fun dimmed(context: Context, dim: Float): Float = level(context)?.let { minOf(it, dim) } ?: dim
+ /** Auto-dim never brightens a screen the user set darker, here or in the system's manual brightness. */
+ fun dimmed(context: Context, dim: Float): Float = minOf(dim, level(context) ?: system(context) ?: dim)
+
+ private fun system(context: Context): Float? = runCatching {
+ val resolver = context.contentResolver
+ if (Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE) != Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) null
+ else Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS) / 255f
+ }.getOrNull()
}
/** A dropdown under the bottom bar: a brightness slider and the screen-off button. A tap outside closes it. */
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomChrome.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomChrome.kt
index f4d569fa83..2d714863e2 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomChrome.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomChrome.kt
@@ -60,6 +60,8 @@ internal fun FullScreenChrome() {
}
}
+private const val PULL_PX = 6f
+
/** The tab at the top edge that brings the hidden bar back, by a tap or a pull down. */
@Composable
internal fun PullTab() {
@@ -71,7 +73,13 @@ internal fun PullTab() {
modifier = Modifier.testTag("bottom-pull-tab").size(width = 72.dp, height = 26.dp)
.semantics { contentDescription = description }
.clip(shape).background(Color.Black.copy(alpha = 0.55f)).border(1.dp, Color.White.copy(alpha = 0.14f), shape)
- .pointerInput(Unit) { detectVerticalDragGestures { change, drag -> if (drag > 6f) { change.consume(); BottomChrome.show(true) } } }
+ .pointerInput(Unit) {
+ var pulled = 0f
+ detectVerticalDragGestures(onDragStart = { pulled = 0f }, onDragEnd = { pulled = 0f }, onDragCancel = { pulled = 0f }) { change, drag ->
+ pulled = (pulled + drag).coerceAtLeast(0f)
+ if (pulled > PULL_PX) { change.consume(); pulled = 0f; BottomChrome.show(true) }
+ }
+ }
.clickable(role = Role.Button) { BottomChrome.show(true) },
) {
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = Color.White.copy(alpha = 0.85f), modifier = Modifier.size(22.dp))
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomDashboard.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomDashboard.kt
index ae29d4b5ff..21a685eee9 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomDashboard.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomDashboard.kt
@@ -86,7 +86,7 @@ internal fun BottomDashboard(
strip: (@Composable (String?) -> Unit)? = null,
) {
val colors = MaterialTheme.colorScheme
- var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
+ var current by remember { mutableStateOf(gamePage()?.takeIf { id -> pages.any { it.id == id } } ?: pickBottomPage(remembered, pages.map { it.id })) }
val startsWhenOpened = remember { gameStarts }
LaunchedEffect(gameStarts) {
if (gameStarts != startsWhenOpened) pageForGameStart(pages.map { it.id }, gamePage())?.let { current = it }
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomGuidesPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomGuidesPage.kt
index 2f99e17fd0..d570a5ad16 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomGuidesPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomGuidesPage.kt
@@ -36,6 +36,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
@@ -152,34 +153,37 @@ internal fun GuidesPanel(runningGame: () -> String?) {
return
}
reading?.let { open ->
- GuideReaderPanel(
- url = open,
- scroll = SteamGuides.place(context, game)?.takeIf { it.url == open }?.scroll ?: 0f,
- note = note,
- onBack = { reading = null; note = null },
- onPlace = { url, s -> SteamGuides.savePlace(context, game, url, s) },
- onSave = { view ->
- val file = GuideLibrary.savedFile(context, game)
- val title = view.title.orEmpty()
- val url = view.url.orEmpty()
- view.saveWebArchive(file.path, false) { path ->
- if (path != null) {
- GuideLibrary.recordSaved(file, title, url)
- note = savedMsg
+ // A new game or page needs a new WebView: its factory runs once and keeps the first page's callbacks.
+ key(game, open) {
+ GuideReaderPanel(
+ url = open,
+ scroll = SteamGuides.place(context, game)?.takeIf { it.url == open }?.scroll ?: 0f,
+ note = note,
+ onBack = { reading = null; note = null },
+ onPlace = { url, s -> SteamGuides.savePlace(context, game, url, s) },
+ onSave = { view ->
+ val file = GuideLibrary.savedFile(context, game)
+ val title = view.title.orEmpty()
+ val url = view.url.orEmpty()
+ view.saveWebArchive(file.path, false) { path ->
+ if (path != null) {
+ GuideLibrary.recordSaved(file, title, url)
+ note = savedMsg
+ libraryRevision++
+ }
+ }
+ },
+ onPin = { image ->
+ scope.launch {
+ val cookies = CookieManager.getInstance().getCookie(image)
+ val file = withContext(Dispatchers.IO) { GuideLibrary.pin(context, game, image, cookies) }
+ note = if (file != null) pinnedMsg else pinFailedMsg
libraryRevision++
}
- }
- },
- onPin = { image ->
- scope.launch {
- val cookies = CookieManager.getInstance().getCookie(image)
- val file = withContext(Dispatchers.IO) { GuideLibrary.pin(context, game, image, cookies) }
- note = if (file != null) pinnedMsg else pinFailedMsg
- libraryRevision++
- }
- },
- onStopped = { reading = null },
- )
+ },
+ onStopped = { reading = null },
+ )
+ }
return
}
PanelColumn {
@@ -231,7 +235,7 @@ private fun WikiSection(appId: Long, name: String?, onOpen: (String) -> Unit) {
val context = LocalContext.current
var links by remember(appId) { mutableStateOf?>(null) }
var tier by remember(appId) { mutableStateOf(null) }
- LaunchedEffect(appId) {
+ LaunchedEffect(appId, name) {
val (found, t) = withContext(Dispatchers.IO) {
val pending = async { GameLinks.protonTier(appId) }
GameLinks.links(context, appId, name) to pending.await()
@@ -377,6 +381,8 @@ internal object ReaderAds {
}
}
+private const val REDIRECT_GRACE_MS = 10_000L
+
internal fun readerAllows(start: String, target: Uri, userInitiated: Boolean): Boolean {
val host = target.host ?: return false
if (target.scheme != "https" && target.scheme != "http") return false
@@ -405,9 +411,14 @@ private fun GuideReader(
settings.allowContentAccess = false
settings.allowFileAccess = url.startsWith("file:") && GuideLibrary.isSaved(context, File(Uri.parse(url).path.orEmpty()))
var restore = scroll
+ // Opening the page and each tapped link may redirect off the site for a moment; a page's own navigation may not.
+ var approvedUntil = android.os.SystemClock.uptimeMillis() + REDIRECT_GRACE_MS
webViewClient = object : WebViewClient() {
- override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
- !readerAllows(url, request.url, request.hasGesture() || request.isRedirect)
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+ val now = android.os.SystemClock.uptimeMillis()
+ if (request.hasGesture()) approvedUntil = now + REDIRECT_GRACE_MS
+ return !readerAllows(url, request.url, request.hasGesture() || (request.isRedirect && now < approvedUntil))
+ }
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): android.webkit.WebResourceResponse? =
if (ReaderAds.blocks(request.url.host)) android.webkit.WebResourceResponse("text/plain", "utf-8", java.io.ByteArrayInputStream(ByteArray(0)))
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomIdleHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomIdleHome.kt
index 87b6d1480f..fa97a401cc 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomIdleHome.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomIdleHome.kt
@@ -21,7 +21,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
-class IdleGame(
+data class IdleGame(
val appId: Int,
val name: String,
val art: File?,
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomMirrorPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomMirrorPage.kt
index a22a21aaa0..263c925979 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomMirrorPage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomMirrorPage.kt
@@ -28,6 +28,9 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.key
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -97,8 +100,9 @@ internal object MirrorRegion {
private const val FRAME_MS = 66L
private const val COMPOSED_SETTLE_MS = 250L
-private const val EDIT_WIDTH = 960
-private const val EDIT_HEIGHT = 540
+private const val EDIT_LONGEST = 960
+private const val EDIT_TRIES = 3
+private const val EDIT_RETRY_MS = 500L
private const val LIVE_LONGEST = 720
@Composable
@@ -113,19 +117,22 @@ internal fun MirrorPanel(actions: BottomPageActions) {
actions.holdComposed(true)
onDispose { actions.holdComposed(false) }
}
- val game = actions.runningGame() ?: "steam"
+ val game = actions.gameKey() ?: "steam"
var region by remember(game) { mutableStateOf(MirrorRegion.parse(SessionPrefs.mirrorRegion(context, game))) }
var editing by remember(game) { mutableStateOf(region == null) }
var sharp by remember { mutableStateOf(true) }
val host = rememberMenuHost()
if (editing) {
- MirrorEditor(copy, region,
- onSave = {
- region = it
- SessionPrefs.setMirrorRegion(context, game, MirrorRegion.format(it))
- editing = false
- },
- onCancel = if (region != null) ({ editing = false }) else null)
+ // A game change must not carry the last game's still or pick into this one's editor.
+ key(game) {
+ MirrorEditor(copy, region, actions.sourceAspect(),
+ onSave = {
+ region = it
+ SessionPrefs.setMirrorRegion(context, game, MirrorRegion.format(it))
+ editing = false
+ },
+ onCancel = if (region != null) ({ editing = false }) else null)
+ }
return
}
val r = region ?: return
@@ -138,7 +145,7 @@ internal fun MirrorPanel(actions: BottomPageActions) {
var failed by remember(r) { mutableStateOf(false) }
LaunchedEffect(r) {
while (isActive) {
- val (w, h) = MirrorRegion.outputSize(r, 16f / 9f, LIVE_LONGEST)
+ val (w, h) = MirrorRegion.outputSize(r, actions.sourceAspect(), LIVE_LONGEST)
val bitmap = capture(copy, r, w, h)
failed = bitmap == null
if (bitmap != null) frame = bitmap.asImageBitmap()
@@ -158,7 +165,7 @@ internal fun MirrorPanel(actions: BottomPageActions) {
) {
val shape = RoundedCornerShape(16.dp)
Column(
- Modifier.padding(12.dp).width(380.dp).testTag("bottom-mirror-options").clip(shape).background(MaterialTheme.colorScheme.background)
+ Modifier.padding(12.dp).widthIn(max = 380.dp).fillMaxWidth().testTag("bottom-mirror-options").clip(shape).background(MaterialTheme.colorScheme.background)
.border(1.dp, pal.line, shape).clickable(remember { MutableInteractionSource() }, indication = null) {}
.padding(horizontal = 10.dp, vertical = 4.dp),
) {
@@ -190,6 +197,7 @@ internal object MirrorOptions {
private fun MirrorEditor(
copy: (RectF?, Int, Int, (Bitmap?) -> Unit) -> Unit,
current: RectF?,
+ sourceAspect: Float,
onSave: (RectF) -> Unit,
onCancel: (() -> Unit)?,
) {
@@ -199,9 +207,17 @@ private fun MirrorEditor(
var start by remember { mutableStateOf(null) }
var end by remember { mutableStateOf(null) }
var picked by remember { mutableStateOf(current) }
- LaunchedEffect(Unit) {
+ var attempt by remember { mutableIntStateOf(0) }
+ LaunchedEffect(attempt) {
delay(COMPOSED_SETTLE_MS)
- val bitmap = capture(copy, null, EDIT_WIDTH, EDIT_HEIGHT)
+ val (w, h) = MirrorRegion.outputSize(RectF(0f, 0f, 1f, 1f), sourceAspect, EDIT_LONGEST)
+ // The surface can be briefly invalid while the session settles, so a failed still is retried a few times.
+ var bitmap: Bitmap? = null
+ for (i in 0 until EDIT_TRIES) {
+ bitmap = capture(copy, null, w, h)
+ if (bitmap != null) break
+ delay(EDIT_RETRY_MS)
+ }
failed = bitmap == null
still = bitmap?.asImageBitmap()
}
@@ -216,7 +232,10 @@ private fun MirrorEditor(
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth().padding(bottom = 6.dp), contentAlignment = Alignment.Center) {
val image = still
if (image == null) {
- if (failed) MirrorNote(stringResource(R.string.bottom_mirror_no_frame))
+ if (failed) Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ MirrorNote(stringResource(R.string.bottom_mirror_no_frame))
+ SecondaryButton(stringResource(R.string.agent_retry), compact = true) { failed = false; attempt++ }
+ }
return@BoxWithConstraints
}
Box(Modifier.aspectRatio(image.width.toFloat() / image.height).clip(RoundedCornerShape(8.dp))) {
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt
index f3eb1dffdf..ff1e64bdb6 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt
@@ -27,8 +27,9 @@ class BottomPageActions(
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
val fps: () -> Float? = { null },
val runningGame: () -> String? = { null },
- val screenOff: (() -> Unit)? = null,
+ val gameKey: () -> String? = runningGame,
val copyRegion: ((android.graphics.RectF?, Int, Int, (android.graphics.Bitmap?) -> Unit) -> Unit)? = null,
+ val sourceAspect: () -> Float = { 16f / 9f },
val holdComposed: (Boolean) -> Unit = {},
val maskRegion: (android.graphics.RectF?, Boolean) -> Unit = { _, _ -> },
)
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt
index 43bdc1858d..a32e9340eb 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt
@@ -15,7 +15,6 @@ import androidx.compose.material.icons.outlined.AlignHorizontalLeft
import androidx.compose.material.icons.outlined.AlignHorizontalRight
import androidx.compose.material.icons.outlined.WidthFull
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -38,16 +37,17 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import com.droiddeck.launcher.R
-import com.droiddeck.launcher.companion.CdpPage
+import com.droiddeck.launcher.session.CdpPage
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SteamQam
-import kotlin.concurrent.thread
import kotlin.math.min
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
+import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
@@ -138,70 +138,75 @@ internal fun SteamQamPanel() {
val aspect = remember { floatArrayOf(0f) }
val measure = Modifier.fillMaxSize().onSizeChanged { if (it.height > 0) aspect[0] = it.width.toFloat() / it.height }
val show = { frame: ImageBitmap -> image = frame; QamCache.image = frame; live.set(true) }
- DisposableEffect(Unit) {
- onDispose {
- val page = holder[0]
- val port = relay[0]
- holder[0] = null
- thread(name = "qam-release", isDaemon = true) {
- runCatching { page?.send("Page.stopScreencast") }
- page?.close()
- SteamQam.release(context, port)
- }
- }
- }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
- while (isActive) {
- // Holding the menu before Steam's first frame keeps gamescope from presenting it.
- if (SessionState.phase != SessionPhase.READY) {
- delay(FAST_TICK_MS)
- continue
- }
- if (aspect[0] == 0f) {
- delay(FAST_TICK_MS)
- continue
- }
- val held = SteamQam.hold(context, aspect[0])
- failed = held == null
- if (held?.open == SteamQam.QUICK_ACCESS) {
- var page = holder[0]
- if (page == null || page.closed) {
- page?.close()
- live.set(false)
- page = SteamQam.target(context)?.let { t ->
- relay[0] = t.port
- runCatching {
- CdpPage(t.port, t.path) { method, params ->
- if (method == "Page.screencastFrame") {
- holder[0]?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
- decodeFrame(params.optString("data"))?.let(show)
+ try {
+ while (isActive) {
+ // Holding the menu before Steam's first frame keeps gamescope from presenting it.
+ if (SessionState.phase != SessionPhase.READY) {
+ delay(FAST_TICK_MS)
+ continue
+ }
+ if (aspect[0] == 0f) {
+ delay(FAST_TICK_MS)
+ continue
+ }
+ val held = SteamQam.hold(context, aspect[0])
+ ensureActive()
+ var reached = held != null
+ if (held?.open == SteamQam.QUICK_ACCESS) {
+ var page = holder[0]
+ if (page == null || page.closed) {
+ page?.close()
+ live.set(false)
+ page = SteamQam.target(context)?.let { t ->
+ if (relay[0] != 0 && relay[0] != t.port) SteamQam.stopRelay(context, relay[0])
+ relay[0] = t.port
+ runCatching {
+ CdpPage(t.port, t.path) { method, params ->
+ if (method == "Page.screencastFrame") {
+ holder[0]?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
+ decodeFrame(params.optString("data"))?.let(show)
+ }
}
- }
- }.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull()
+ }.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull()
+ }
+ holder[0] = page
+ ensureActive()
+ page?.send("Page.enable")
+ page?.send("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
+ .put("maxWidth", 1920).put("maxHeight", 1440))
}
- holder[0] = page
- page?.send("Page.enable")
- page?.send("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
- .put("maxWidth", 1920).put("maxHeight", 1440))
- }
- // The screencast sends frames only when the menu repaints, so a still menu needs one screenshot.
- if (!live.get()) {
- page?.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85))
- ?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(show)
- }
- val wide = !held.top && QamFit.current(context) == QamFit.FULL
- (page?.evaluate(QamLayout.contentScript(wide)) as? String)?.let { text ->
- runCatching {
- val a = JSONArray(text)
- val layout = floatArrayOf(a.getDouble(0).toFloat(), a.getDouble(1).toFloat(), a.getDouble(2).toFloat(), a.getDouble(3).toFloat())
- if (!layout.contentEquals(shape)) { shape = layout; QamCache.shape = layout }
+ // The screencast sends frames only when the menu repaints, so a still menu needs one screenshot.
+ if (!live.get()) {
+ page?.call("Page.captureScreenshot", JSONObject().put("format", "jpeg").put("quality", 85))
+ ?.optJSONObject("result")?.optString("data")?.let(::decodeFrame)?.let(show)
}
+ reached = page != null
+ val wide = !held.top && QamFit.current(context) == QamFit.FULL
+ (page?.evaluate(QamLayout.contentScript(wide)) as? String)?.let { text ->
+ runCatching {
+ val a = JSONArray(text)
+ val layout = floatArrayOf(a.getDouble(0).toFloat(), a.getDouble(1).toFloat(), a.getDouble(2).toFloat(), a.getDouble(3).toFloat())
+ if (!layout.contentEquals(shape)) { shape = layout; QamCache.shape = layout }
+ }
+ }
+ }
+ failed = !reached
+ val used = QamFit.current(context)
+ withTimeoutOrNull(if (live.get()) TICK_MS else FAST_TICK_MS) {
+ snapshotFlow { QamFit.current(context) }.first { it != used }
}
}
- val used = QamFit.current(context)
- withTimeoutOrNull(if (live.get()) TICK_MS else FAST_TICK_MS) {
- snapshotFlow { QamFit.current(context) }.first { it != used }
+ } finally {
+ withContext(NonCancellable) {
+ val page = holder[0]
+ holder[0] = null
+ runCatching { page?.send("Page.stopScreencast") }
+ // The page outlives this connection, so the widened layout would otherwise stay on the top screen.
+ runCatching { page?.evaluate(QamLayout.contentScript(wide = false)) }
+ page?.close()
+ SteamQam.release(context, relay[0])
}
}
}
@@ -225,23 +230,29 @@ internal fun SteamQamPanel() {
Canvas(
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, fit) {
var touching = false
- awaitPointerEventScope {
- while (true) {
- val event = awaitPointerEvent()
- val change = event.changes.firstOrNull() ?: continue
- val (x, y) = QamLayout.toCss(change.position.x, change.position.y, scale, left)
- val type = when (event.type) {
- PointerEventType.Press -> if (x in 0f..f.contentRight && y in 0f..f.cssHeight) "touchStart" else null
- PointerEventType.Move -> "touchMove"
- PointerEventType.Release -> "touchEnd"
- else -> null
- }?.takeIf { it == "touchStart" || touching } ?: continue
- touching = type != "touchEnd"
- val points = if (type == "touchEnd") JSONArray()
- else JSONArray().put(JSONObject().put("x", x.toDouble()).put("y", y.toDouble()))
- holder[0]?.send("Input.dispatchTouchEvent", JSONObject().put("type", type).put("touchPoints", points))
- change.consume()
+ val touched = holder[0]
+ try {
+ awaitPointerEventScope {
+ while (true) {
+ val event = awaitPointerEvent()
+ val change = event.changes.firstOrNull() ?: continue
+ val (x, y) = QamLayout.toCss(change.position.x, change.position.y, scale, left)
+ val type = when (event.type) {
+ PointerEventType.Press -> if (x in 0f..f.contentRight && y in 0f..f.cssHeight) "touchStart" else null
+ PointerEventType.Move -> "touchMove"
+ PointerEventType.Release -> "touchEnd"
+ else -> null
+ }?.takeIf { it == "touchStart" || touching } ?: continue
+ touching = type != "touchEnd"
+ val points = if (type == "touchEnd") JSONArray()
+ else JSONArray().put(JSONObject().put("x", x.toDouble()).put("y", y.toDouble()))
+ holder[0]?.send("Input.dispatchTouchEvent", JSONObject().put("type", type).put("touchPoints", points))
+ change.consume()
+ }
}
+ } finally {
+ if (touching) (touched ?: holder[0])?.send("Input.dispatchTouchEvent",
+ JSONObject().put("type", "touchCancel").put("touchPoints", JSONArray()))
}
},
) {
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt
index 3b13725cda..1ebe5d6ebd 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt
+++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt
@@ -115,6 +115,7 @@ class SecondScreenPresentation(
fun requestKeyboard(forField: Boolean = false) {
if (!showsKeyboard || keyboardHost == null) return
+ wake()
if (forField) fieldKeyboard = true
keyboardPending = true
if (window?.decorView?.hasWindowFocus() == true) showPendingKeyboard()
@@ -159,6 +160,7 @@ class SecondScreenPresentation(
fun showChat(onLost: () -> Unit, content: @androidx.compose.runtime.Composable () -> Unit) {
if (!showsKeyboard || chatView != null) return
+ wake()
keyboardHost?.takeIf { it.shown }?.hide()
keyboardShown.value = false
keyboardPending = false
@@ -197,6 +199,7 @@ class SecondScreenPresentation(
val content = menu ?: return
menuShown = on
if (on) {
+ wake()
keyboardHost?.takeIf { it.shown }?.hide()
keyboardShown.value = false
ownComposeViews()
@@ -249,7 +252,9 @@ class SecondScreenPresentation(
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD || currentMode.sessionPanel ||
currentMode == SecondScreenMode.DESKTOP
val back = event.keyCode == KeyEvent.KEYCODE_BACK && currentMode == SecondScreenMode.DASHBOARD
- val forward = menuShown || !ownKeys || back || PadBridge.isControllerKeyEvent(event)
+ val pad = PadBridge.isControllerKeyEvent(event)
+ if (!pad) uiActivity()
+ val forward = menuShown || !ownKeys || back || pad
if (forward && sessionActivity.dispatchKeyEvent(event)) return true
return super.dispatchKeyEvent(event)
}
@@ -277,7 +282,20 @@ class SecondScreenPresentation(
private var waking = false
private val dim = Runnable { if (screen == BottomScreenLight.ON) light(BottomScreenLight.DIM) }
- fun screenOff() = light(BottomScreenLight.OFF)
+ fun screenOff() {
+ // A control held by another finger would keep its press, since the screen-off overlay takes the release.
+ controlsView?.releaseInputs()
+ light(BottomScreenLight.OFF)
+ }
+
+ /** Keyboard or mouse use of the bottom screen's own UI counts as activity; an explicit screen off stays off. */
+ private fun uiActivity() {
+ when (screen) {
+ BottomScreenLight.DIM -> wake()
+ BottomScreenLight.ON -> scheduleDim()
+ BottomScreenLight.OFF -> Unit
+ }
+ }
fun wake() {
light(BottomScreenLight.ON)
@@ -317,6 +335,7 @@ class SecondScreenPresentation(
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (PadBridge.isControllerMotionEvent(event) && sessionActivity.dispatchGenericMotionEvent(event)) return true
+ if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) uiActivity()
return super.dispatchGenericMotionEvent(event)
}
@@ -381,7 +400,7 @@ class SecondScreenPresentation(
attachKeyboard()
}
SecondScreenMode.DASHBOARD -> renderDashboard()
- SecondScreenMode.GUIDES, SecondScreenMode.MIRROR, SecondScreenMode.COMPANION, SecondScreenMode.STEAM_QAM, SecondScreenMode.ART -> renderPanel(mode)
+ SecondScreenMode.GUIDES, SecondScreenMode.MIRROR, SecondScreenMode.STEAM_QAM, SecondScreenMode.ART -> renderPanel(mode)
SecondScreenMode.DESKTOP -> {
root.addView(BottomDesktopPanel(context, onClose, onMenu,
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap,
@@ -434,7 +453,7 @@ class SecondScreenPresentation(
MirrorOptions.open.value = !MirrorOptions.open.value
}) + extras)
SecondScreenMode.DASHBOARD, SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.GUIDES,
- SecondScreenMode.COMPANION, SecondScreenMode.ART -> model(extras)
+ SecondScreenMode.ART -> model(extras)
SecondScreenMode.TERMINAL -> model(listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard,
tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }) + extras)
else -> null
diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameLinksTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameLinksTest.kt
index d98cd898e8..1f7a6cec41 100644
--- a/app/src/test/java/com/droiddeck/launcher/session/GameLinksTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/session/GameLinksTest.kt
@@ -91,6 +91,15 @@ class GameLinksTest {
assertNull(GameLinks.parseOpenSearch(json, "Canis Canem Edit"))
}
+ @Test
+ fun cachedDiscoveriesYieldToNewWikidataLinks() {
+ val fandom = GameLinks.Link(GameLinks.Kind.WIKI, "https://bully.fandom.com/")
+ val map = GameLinks.Link(GameLinks.Kind.MAPGENIE, "https://mapgenie.io/bully")
+ val wiki = GameLinks.Link(GameLinks.Kind.WIKI, "https://bully.wiki.gg/")
+ assertEquals(listOf(wiki, map), GameLinks.merge(listOf(wiki), listOf(fandom, map)))
+ assertEquals(listOf(fandom, map), GameLinks.merge(emptyList(), listOf(fandom, map)))
+ }
+
@Test
fun cachedLinksRoundTrip() {
val links = listOf(GameLinks.Link(GameLinks.Kind.MAPGENIE, "https://mapgenie.io/bully"))
diff --git a/app/src/test/java/com/droiddeck/launcher/session/LoopbackWebSocketTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LoopbackWebSocketTest.kt
new file mode 100644
index 0000000000..7c453bc390
--- /dev/null
+++ b/app/src/test/java/com/droiddeck/launcher/session/LoopbackWebSocketTest.kt
@@ -0,0 +1,83 @@
+package com.droiddeck.launcher.session
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertThrows
+import org.junit.Test
+import java.io.DataInputStream
+import java.io.IOException
+import java.net.ServerSocket
+import kotlin.concurrent.thread
+
+class LoopbackWebSocketTest {
+ @Test
+ fun talksToALoopbackWebSocketServer() {
+ val server = ServerSocket(0)
+ var received: String? = null
+ val worker = thread {
+ server.accept().use { client ->
+ val input = DataInputStream(client.getInputStream())
+ val out = client.getOutputStream()
+ out.write(upgrade(handshakeKey(input)).toByteArray())
+ for (text in listOf("""{"id":1}""", "x".repeat(300))) {
+ val bytes = text.toByteArray()
+ out.write(0x81)
+ if (bytes.size < 126) out.write(bytes.size) else { out.write(126); out.write(bytes.size shr 8); out.write(bytes.size and 0xFF) }
+ out.write(bytes)
+ }
+ out.flush()
+ val b0 = input.read()
+ val len = input.read() and 0x7F
+ val mask = ByteArray(4).also(input::readFully)
+ val payload = ByteArray(len).also(input::readFully)
+ for (i in payload.indices) payload[i] = (payload[i].toInt() xor mask[i % 4].toInt()).toByte()
+ if (b0 == 0x81) received = String(payload)
+ }
+ }
+ LoopbackWebSocket(server.localPort).use { ws ->
+ assertEquals("""{"id":1}""", ws.receive())
+ assertEquals(300, ws.receive()!!.length)
+ ws.send("""{"id":2}""")
+ }
+ worker.join(5_000)
+ server.close()
+ assertEquals("""{"id":2}""", received)
+ }
+
+ @Test
+ fun rejectsAnUpgradeWithoutTheRightAcceptHeader() {
+ for (reply in listOf(
+ "HTTP/1.1 101 Switching Protocols\r\n\r\n",
+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: wrong\r\n\r\n",
+ "HTTP/1.1 1010 Nope\r\n\r\n",
+ )) {
+ val server = ServerSocket(0)
+ val worker = thread {
+ server.accept().use { client ->
+ handshakeKey(DataInputStream(client.getInputStream()))
+ client.getOutputStream().apply { write(reply.toByteArray()); flush() }
+ Thread.sleep(200)
+ }
+ }
+ assertThrows(IOException::class.java) { LoopbackWebSocket(server.localPort).close() }
+ worker.join(5_000)
+ server.close()
+ }
+ }
+
+ private fun upgrade(key: String) = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
+ "Sec-WebSocket-Accept: ${LoopbackWebSocket.accept(key)}\r\n\r\n"
+
+ private fun handshakeKey(input: DataInputStream): String =
+ generateSequence { readLine(input) }.takeWhile { it.isNotEmpty() }.toList()
+ .first { it.startsWith("Sec-WebSocket-Key:") }.substringAfter(':').trim()
+
+ private fun readLine(input: DataInputStream): String? {
+ val sb = StringBuilder()
+ while (true) {
+ val c = input.read()
+ if (c < 0) return null
+ if (c == '\n'.code) return sb.toString().trimEnd('\r')
+ sb.append(c.toChar())
+ }
+ }
+}
diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt
index 0952c894e3..c1c51eb8e6 100644
--- a/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt
@@ -60,9 +60,23 @@ class SteamQamTest {
assertFalse(SteamQam.script(false, 1.5f).contains("g.__ddQamAspect ="))
}
+ @Test fun aSteamDialogOverTheGameGetsTheInput() {
+ val script = SteamQam.script(true)
+ assertTrue(script.contains("t.m_ID?.startsWith(\"ModalDialogOverlay\") && t.m_Root?.m_element?.isConnected"))
+ assertTrue(script.contains("if (dialog && !g.__ddQamTop) {"))
+ assertTrue(script.indexOf("if (dialog && !g.__ddQamTop)") < script.indexOf("g.__ddQamDecky = decky;"))
+ }
+
+ @Test fun theRelayAnswersWithItsPortAndSecret() {
+ assertEquals(41234 to "0123456789abcdef0123456789abcdef", SteamQam.parseRelay("41234 0123456789abcdef0123456789abcdef\n"))
+ assertNull(SteamQam.parseRelay("41234"))
+ assertNull(SteamQam.parseRelay("41234 not-a-secret"))
+ assertNull(SteamQam.parseRelay(null))
+ }
+
@Test fun whileHeldTheMenuStaysOffTheTopScreenAndOutOfTheGamesWay() {
val script = SteamQam.script(true)
- assertTrue(script.contains("return v === 2 && ours() ? 1 : v;"))
+ assertTrue(script.contains("return without >= 2 ? v : 1;"))
assertTrue(script.contains("if (w > 0 && ours()) { x = popup.m_popup.innerWidth + 64; w = width(h) || w; }"))
assertTrue(script.contains("nav.m_LastActiveNavTree?.m_ID?.startsWith(\"QuickAccess\")"))
assertTrue(script.contains("if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus();"))
diff --git a/app/src/test/java/com/droiddeck/launcher/ui/BottomBrightnessTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/BottomBrightnessTest.kt
index 547c93d6fc..99fae40305 100644
--- a/app/src/test/java/com/droiddeck/launcher/ui/BottomBrightnessTest.kt
+++ b/app/src/test/java/com/droiddeck/launcher/ui/BottomBrightnessTest.kt
@@ -34,4 +34,14 @@ class BottomBrightnessTest {
SessionPrefs.setBottomBrightness(context, 80)
assertEquals(0.05f, BottomBrightness.dimmed(context, 0.05f), 0.001f)
}
+
+ @Test fun autoDimFollowsADarkerManualSystemLevelWhenNothingIsSaved() {
+ val resolver = context.contentResolver
+ android.provider.Settings.System.putInt(resolver, android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE,
+ android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)
+ android.provider.Settings.System.putInt(resolver, android.provider.Settings.System.SCREEN_BRIGHTNESS, 3)
+ assertEquals(3 / 255f, BottomBrightness.dimmed(context, 0.05f), 0.001f)
+ android.provider.Settings.System.putInt(resolver, android.provider.Settings.System.SCREEN_BRIGHTNESS, 200)
+ assertEquals(0.05f, BottomBrightness.dimmed(context, 0.05f), 0.001f)
+ }
}
diff --git a/docs/development/bottom-screen-guides.md b/docs/development/bottom-screen-guides.md
index cfb9d77aed..6f13941a21 100644
--- a/docs/development/bottom-screen-guides.md
+++ b/docs/development/bottom-screen-guides.md
@@ -45,7 +45,7 @@ Recommended order for the tab: Steam guides → achievements → StrategyWiki or
Paths are under [`app/src/main/java/com/droiddeck/launcher/`](../../app/src/main/java/com/droiddeck/launcher/).
-- **Game identity.** `AgentGuest.activeSteamAppId` from gamescope focus (ignoring the Steam client, 769), passed to bottom pages as `runningGame`. Non-Steam store games are Steam shortcuts; `resolveAchievementsInFront` already maps the focused id to the store and store id through the library cache.
+- **Game identity.** Bottom pages receive `gestureGame` as `runningGame`. In Steam mode it is the gamescope-focused app id (ignoring the Steam client, 769); in direct-run mode it is `program:`, which is not a Steam app id, so Steam lookups must not use it. `AgentGuest.activeSteamAppId` reads the focused Steam app directly and is the source for Steam lookups. Non-Steam store games are Steam shortcuts; `resolveAchievementsInFront` already maps the focused id to the store and store id through the library cache.
- **WebView base.** [`ui/BottomChatPage.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/BottomChatPage.kt) loads Steam Community with a host allow-list, desktop user agent, fit-to-screen CSS and crash recovery. [`session/SteamWebLogin.kt`](../../app/src/main/java/com/droiddeck/launcher/session/SteamWebLogin.kt) imports the Steam client's own `steamcommunity.com` cookies, so guides load signed in without another login.
- **Achievements.** [`stores/StoreAchievements.kt`](../../app/src/main/java/com/droiddeck/launcher/stores/StoreAchievements.kt) is a provider base with a per-game cache; GOG and Epic implement it. [`ui/StoreAchievementsUi.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/StoreAchievementsUi.kt) has the rows, tab and session panel. A Steam provider plugs in as source `steam`.
- **Per-game storage.** `SessionPrefs` already keys settings by game (for example `fpsLimit.game.`); the guide workspace fits the same pattern.
diff --git a/docs/development/bottom-screen.md b/docs/development/bottom-screen.md
index a8bc294143..5df5515289 100644
--- a/docs/development/bottom-screen.md
+++ b/docs/development/bottom-screen.md
@@ -1,6 +1,6 @@
# Bottom screen: research and proposals
-Researched 2026-11-26 against `main` at `d788afc12` (0.7.11). Implementation is not scheduled yet. This document records what other dual-screen Android projects put on the second screen, how they get their data, where DroidDeck stands, and the features we want to build. Three proposals have their own documents: [region mirror](bottom-screen-region-mirror.md), [guides tab](bottom-screen-guides.md) and [companion API](bottom-screen-companion-api.md).
+Researched 2026-11-26 against `main` at `d788afc12` (0.7.11). This document records what other dual-screen Android projects put on the second screen, how they get their data, where DroidDeck stood at that commit, and the features we want to build. "DroidDeck today" is that researched baseline; each proposal's **Status** line says what has been built since, and proposals without one are not scheduled. Two proposals have their own documents: [region mirror](bottom-screen-region-mirror.md) and [guides tab](bottom-screen-guides.md).
The starting point was WULFF DEN's survey video [Dual screen Android apps are getting crazy](https://youtu.be/dAiuG2A-wkc) (2026-11-26). It covers the AYN Thor and Retroid Pocket Duo, and most of its apps come from the [GAFT list](https://andreyvelsk.github.io/GAFT) of Thor apps.
@@ -65,6 +65,8 @@ Other GAFT companions: Thor Pip-Boy, FNVDS, Grand Theft Companion, FFXII, Terrar
## DroidDeck today
+As of `d788afc12`, before the work in the Status lines below.
+
Paths are under [`app/src/main/java/com/droiddeck/launcher/`](../../app/src/main/java/com/droiddeck/launcher/).
**Panels.** [`input/SecondScreenMode.kt`](../../app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt) lists the modes: menu, keyboard + trackpad, terminal, Deck grips + trackpads, profile controls, dashboard and the KDE desktop. [`ui/SecondScreenPresentation.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt) hosts them in a `Presentation`, with the bar in [`ui/BottomScreenBar.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/BottomScreenBar.kt). The last mode is remembered once for game sessions and once for desktop sessions (`SessionPrefs.secondScreenPanel`), not per game. Outside a session the launcher shows [`ui/DualScreenPanel.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt).
@@ -122,7 +124,7 @@ Remember the bottom mode, dashboard tab and control layout per Steam app id, and
An achievements page for the running game (progress, recent unlocks, locked list with hidden descriptions behind a tap) and a notifications page (friends, invites, downloads finished).
-- Source: `steamEval` against Steam's UI stores; the Steam Web API as a fallback for achievements when the client is offline.
+- Source: `steamEval` against Steam's UI stores, which keep the last synced achievements while the device is offline. The Steam Web API is a fallback only when the device has a network but the Steam client is offline; with no network, the page shows the cached list or says achievements are unavailable.
- Matches the existing Epic, GOG and EA achievement readers so all stores look the same.
### 4. Quick tiles and per-game rules
@@ -165,12 +167,10 @@ Details: [bottom-screen-guides.md](bottom-screen-guides.md).
### 8. Companion API for PC games
-**Status:** phase 1 started, as its own bottom-screen panel (Companion in the panel picker), drawn with the settings groups and rows. It connects over loopback only while shown: Stardew Valley (the dual-screen SMAPI mod on 7786: day, gold, energy, health, a tappable hotbar, birthdays, quests), Skyrim SE (SkyrimWebSocket on 8765) and Fallout 4 (Thor Pip-Boy on 8767: vitals, caps, rads, carry weight, favorites to equip or use, radio). Code: [`companion/`](../../app/src/main/java/com/droiddeck/launcher/companion/), [`ui/BottomCompanionPage.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/BottomCompanionPage.kt).
+**Status:** not built here; the first adapters (Stardew Valley, Skyrim SE, Fallout 4) follow in their own change.
Let mods running in Proton drive native bottom-screen pages over loopback. Thor Pip-Boy (Fallout 4) and Grand Theft Companion (GTA) already run against DroidDeck as separate apps, and the Stardew, Skyrim and RimWorld ecosystems have servers we can adapt to. Plan: adapters for those first, then DroidDeck's own token-authenticated protocol with declarative pages and normalized state keys, then "run on bottom", then memory profiles only if needed. The existing racing, War Thunder and Elite Dangerous telemetry is the first set of built-in adapters.
-Details: [bottom-screen-companion-api.md](bottom-screen-companion-api.md).
-
### 9. Steam's Quick Access menu on the bottom screen
**Status:** built as its own panel (Quick Access in the panel picker, Steam sessions only) and checked on a Retroid Pocket Duo Lite Plus in Big Picture and in a game. The bottom screen shows Steam's real Quick Access menu: notifications, friends and chat, quick settings, performance, soundtracks and help, plus Decky Loader's tab and its plugins when Decky is enabled. Taps, drags and scrolling go to it; the controller stays on the top screen, so the d-pad drives the library or the game while the menu stays open. Code: [`session/SteamQam.kt`](../../app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt), [`ui/BottomSteamQamPanel.kt`](../../app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt), [`droiddeck-qam-relay`](../../tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay).
diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay b/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay
index cbe72f9ff0..c7366a63e9 100755
--- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay
+++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay
@@ -1,10 +1,14 @@
#!/usr/bin/python3
# Relays the app to Steam's DevTools port, which only answers clients inside the guest, while the bottom screen
-# shows Steam's quick access menu.
-# droiddeck-qam-relay start prints the relay port
+# shows Steam's quick access menu. Only requests carrying the secret printed at start reach DevTools, and only for
+# the target list and page sockets, so other local apps cannot use the relay to reach Steam.
+# droiddeck-qam-relay start prints the relay port and its secret
# droiddeck-qam-relay stop [] stops the relay, or only the one on that port
+import hmac
import os
+import re
+import secrets
import socket
import sys
import threading
@@ -13,6 +17,24 @@ import time
FLAG = "/tmp/.dd-qam-relay"
INTERVAL = 0.5
MAX_SECONDS = 6 * 3600
+IDLE_SECONDS = 30
+ALLOWED = re.compile(r"^/(json|json/list|devtools/page/[A-Za-z0-9-]+)$")
+
+
+class Activity:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.open = 0
+ self.last = time.monotonic()
+
+ def change(self, delta):
+ with self.lock:
+ self.open += delta
+ self.last = time.monotonic()
+
+ def idle(self):
+ with self.lock:
+ return self.open == 0 and time.monotonic() - self.last > IDLE_SECONDS
def owner():
@@ -39,25 +61,61 @@ def pipe(src, dst):
pass
-def relay(server, devtools_port):
+def rewrite(head, token):
+ """Returns the request with the secret removed from its path, or None when it is not an allowed request."""
+ line, sep, rest = head.partition(b"\r\n")
+ parts = line.split(b" ")
+ if not sep or len(parts) != 3 or parts[0] != b"GET" or not parts[2].startswith(b"HTTP/1."):
+ return None
+ prefix = b"/" + token.encode()
+ path = parts[1]
+ if not hmac.compare_digest(path[:len(prefix)], prefix) or not ALLOWED.match(path[len(prefix):].decode("ascii", "replace")):
+ return None
+ return b"GET " + path[len(prefix):] + b" " + parts[2] + sep + rest
+
+
+def handle(client, devtools_port, token, activity):
+ activity.change(1)
+ try:
+ client.settimeout(3)
+ head = b""
+ while b"\r\n" not in head and len(head) < 4096:
+ data = client.recv(4096)
+ if not data:
+ break
+ head += data
+ request = rewrite(head, token)
+ if request is None:
+ client.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ return
+ client.settimeout(None)
+ upstream = socket.create_connection(("127.0.0.1", devtools_port), 3)
+ upstream.sendall(request)
+ back = threading.Thread(target=pipe, args=(upstream, client), daemon=True)
+ back.start()
+ pipe(client, upstream)
+ back.join()
+ except OSError:
+ pass
+ finally:
+ client.close()
+ activity.change(-1)
+
+
+def relay(server, devtools_port, token, activity):
while True:
try:
client, _ = server.accept()
except OSError:
return
- try:
- upstream = socket.create_connection(("127.0.0.1", devtools_port), 3)
- except OSError:
- client.close()
- continue
- for a, b in ((client, upstream), (upstream, client)):
- threading.Thread(target=pipe, args=(a, b), daemon=True).start()
+ threading.Thread(target=handle, args=(client, devtools_port, token, activity), daemon=True).start()
-def serve(server, devtools_port, me):
- threading.Thread(target=relay, args=(server, devtools_port), daemon=True).start()
+def serve(server, devtools_port, me, token):
+ activity = Activity()
+ threading.Thread(target=relay, args=(server, devtools_port, token, activity), daemon=True).start()
started = time.monotonic()
- while owner()[:1] == [me] and time.monotonic() - started < MAX_SECONDS:
+ while owner()[:1] == [me] and time.monotonic() - started < MAX_SECONDS and not activity.idle():
time.sleep(INTERVAL)
server.close()
@@ -80,7 +138,8 @@ def main():
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", 0))
server.listen(4)
- print(server.getsockname()[1], flush=True)
+ token = secrets.token_hex(16)
+ print(server.getsockname()[1], token, flush=True)
if os.fork():
return 0
os.setsid()
@@ -90,7 +149,7 @@ def main():
devnull = os.open(os.devnull, os.O_RDWR)
for fd in (0, 1, 2):
os.dup2(devnull, fd)
- serve(server, devtools_port, me)
+ serve(server, devtools_port, me, token)
return 0
diff --git a/tools/tests/test_qam_relay.py b/tools/tests/test_qam_relay.py
index fed503e482..13d7fe3f43 100644
--- a/tools/tests/test_qam_relay.py
+++ b/tools/tests/test_qam_relay.py
@@ -44,12 +44,12 @@ class QamRelayTest(unittest.TestCase):
server.listen(1)
port = server.getsockname()[1]
Path(self.relay.FLAG).write_text("me %d" % port)
- serving = threading.Thread(target=self.relay.serve, args=(server, upstream.getsockname()[1], "me"), daemon=True)
+ serving = threading.Thread(target=self.relay.serve, args=(server, upstream.getsockname()[1], "me", "s3cret"), daemon=True)
serving.start()
with socket.create_connection(("127.0.0.1", port), 2) as client:
- client.sendall(b"GET /json")
+ client.sendall(b"GET /s3cret/json HTTP/1.1\r\nHost: x\r\n\r\n")
client.settimeout(2)
- self.assertEqual(b"answer:GET /json", client.recv(100))
+ self.assertEqual(b"answer:GET /json HTTP/1.1\r\nHost: x\r\n\r\n", client.recv(100))
with mock.patch.object(self.relay.sys, "argv", ["x", "stop", str(port + 1)]):
self.assertEqual(0, self.relay.main())
serving.join(0.3)
@@ -59,6 +59,24 @@ class QamRelayTest(unittest.TestCase):
serving.join(2)
self.assertFalse(serving.is_alive())
+ def test_refuses_requests_without_the_secret_or_outside_the_allowed_paths(self):
+ rewrite = self.relay.rewrite
+ self.assertEqual(b"GET /devtools/page/AB-1 HTTP/1.1\r\n", rewrite(b"GET /k/devtools/page/AB-1 HTTP/1.1\r\n", "k"))
+ for head in (b"GET /json HTTP/1.1\r\n", b"GET /x/json HTTP/1.1\r\n", b"POST /k/json HTTP/1.1\r\n",
+ b"GET /k/devtools/browser/1 HTTP/1.1\r\n", b"GET /k/json/new?x HTTP/1.1\r\n", b"GET /k/json HTTP/1.1"):
+ self.assertIsNone(rewrite(head, "k"), head)
+
+ def test_stops_after_an_idle_period(self):
+ self.relay.IDLE_SECONDS = 0.1
+ server = socket.socket()
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ Path(self.relay.FLAG).write_text("me %d" % server.getsockname()[1])
+ serving = threading.Thread(target=self.relay.serve, args=(server, 1, "me", "k"), daemon=True)
+ serving.start()
+ serving.join(2)
+ self.assertFalse(serving.is_alive())
+
def test_rejects_unknown_commands(self):
for argv in (["x"], ["x", "start"], ["x", "stop", "1", "2"]):
with mock.patch.object(self.relay.sys, "argv", argv), mock.patch.object(self.relay.sys, "stderr"):