feat(bottom): Steam's Quick Access menu as a bottom screen panel

This commit is contained in:
Kurt Himebauch committed 2026-11-26 22:21:51 -05:00
1 parent f692ef9de9
commit aba41ac958
51 files changed
+735 -9

No files matched your search

@@ -4446,7 +4446,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available())
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), SessionState.mode == SessionService.MODE_STEAM)
private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
@@ -4607,7 +4607,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val remembered = game?.let { SessionPrefs.gameSecondScreenPanel(this, it) }
val wanted = when {
remembered != null -> SecondScreenMode.opening(remembered, SessionState.deckPad, bottomPages().isNotEmpty(),
com.droiddeck.launcher.session.BottomDesktop.available())
com.droiddeck.launcher.session.BottomDesktop.available(), SessionState.mode == SessionService.MODE_STEAM)
gamePanelApplied -> openingPanel()
else -> return
}
@@ -0,0 +1,60 @@
package com.droiddeck.launcher.companion
import org.json.JSONObject
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.CompletableFuture
import kotlin.concurrent.thread
class CdpPage(port: Int, path: String, private val onEvent: (String, JSONObject) -> Unit) : AutoCloseable {
private val ws = LoopbackWebSocket(port, path, connectTimeoutMs = 2_000)
private val ids = AtomicInteger()
private val pending = ConcurrentHashMap<Int, CompletableFuture<JSONObject>>()
private val sender = Executors.newSingleThreadExecutor { r -> Thread(r, "cdp-send").apply { isDaemon = true } }
@Volatile var closed = false
private set
init {
thread(name = "cdp-read", isDaemon = true) {
try {
while (true) {
val m = JSONObject(ws.receive() ?: break)
if (m.has("id")) pending.remove(m.optInt("id"))?.complete(m)
else onEvent(m.optString("method"), m.optJSONObject("params") ?: JSONObject())
}
} catch (_: Exception) {
}
closed = true
pending.values.forEach { it.complete(JSONObject()) }
}
}
fun send(method: String, params: JSONObject = JSONObject()) {
if (closed) return
val id = ids.incrementAndGet()
val text = JSONObject().put("id", id).put("method", method).put("params", params).toString()
sender.execute { runCatching { ws.send(text) } }
}
fun call(method: String, params: JSONObject = JSONObject(), timeoutMs: Long = 3_000): JSONObject? {
if (closed) return null
val id = ids.incrementAndGet()
val future = CompletableFuture<JSONObject>()
pending[id] = future
val text = JSONObject().put("id", id).put("method", method).put("params", params).toString()
sender.execute { runCatching { ws.send(text) }.onFailure { future.complete(JSONObject()) } }
return runCatching { future.get(timeoutMs, TimeUnit.MILLISECONDS) }.getOrNull().also { pending.remove(id) }
}
fun evaluate(expression: String): Any? =
call("Runtime.evaluate", JSONObject().put("expression", expression).put("returnByValue", true))
?.optJSONObject("result")?.optJSONObject("result")?.opt("value")
override fun close() {
closed = true
sender.shutdown()
runCatching { ws.close() }
}
}
@@ -18,9 +18,10 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
GUIDES("guides", R.string.bottom_page_guides),
MIRROR("mirror", R.string.bottom_page_mirror),
COMPANION("companion", R.string.bottom_page_companion),
STEAM_QAM("steam-qam", R.string.bottom_qam_title),
DESKTOP("desktop", R.string.second_mode_desktop);
val sessionPanel: Boolean get() = this == GUIDES || this == MIRROR || this == COMPANION
val sessionPanel: Boolean get() = this == GUIDES || this == MIRROR || this == COMPANION || this == STEAM_QAM
val controls: Boolean get() = this == CUSTOM_CONTROLS || bindings != null
@@ -28,9 +29,10 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
companion object {
/** The mode the bottom screen opens in: the one picked last if it is still available, else the DroidDeck menu. */
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false): SecondScreenMode =
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false,
steam: Boolean = false): SecondScreenMode =
entries.firstOrNull {
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD && !it.sessionPanel || dashboard) &&
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD && !it.sessionPanel || dashboard) && (it != STEAM_QAM || steam) &&
(it != DESKTOP || bottomDesktop)
} ?: MENU
}
@@ -0,0 +1,114 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.agent.AgentGuest
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
// Steam renders the quick access menu only while it is open. It stays open with its window parked outside the Big
// Picture window, composition held at "notification" so gamescope keeps the game focused, and gamepad focus on the main UI.
object SteamQam {
data class Target(val port: Int, val path: String)
const val QUICK_ACCESS = 2
private const val TAG = "SteamQam"
private const val EVAL_MS = 6_000L
internal fun script(on: Boolean): String = """(() => {
const W = SteamUIStore.WindowStore.SteamUIWindows[0];
const m = W.MenuStore, c = W.m_CompositionStateStore;
const nav = SteamUIStore.m_GamepadNavigationManager.m_ActiveContext;
const doc = g_PopupManager.GetExistingPopup("SP BPM_uid0")?.m_popup?.document;
const QAM = 2;
if (!c.__dd) {
c.__dd = c.ComputeOverallMinimumRequestedComposition;
c.ComputeOverallMinimumRequestedComposition = function (...a) {
const v = c.__dd.apply(this, a);
return globalThis.__ddQam && v === 2 && m.m_eOpenSideMenu === QAM ? 1 : v;
};
m.__dd = m.OnMenuDeactivated;
m.OnMenuDeactivated = function (d) { if (globalThis.__ddQam && d === QAM) return; return m.__dd.call(this, d); };
}
const backdrop = (hide) => {
if (!doc) return;
for (const e of doc.querySelectorAll("div")) {
if (e.dataset.ddQam) { if (!hide) { e.style.removeProperty("visibility"); delete e.dataset.ddQam; } continue; }
if (!hide) continue;
const s = getComputedStyle(e), r = e.getBoundingClientRect(), v = doc.defaultView;
if (s.backdropFilter && s.backdropFilter !== "none" && r.width >= v.innerWidth - 2 && r.height >= v.innerHeight - 2) {
e.dataset.ddQam = "1";
e.style.setProperty("visibility", "hidden", "important");
}
}
};
if (${if (on) "true" else "false"}) {
globalThis.__ddQam = true;
if (m.m_eOpenSideMenu === 0) m.OpenQuickAccessMenu();
if (m.m_eOpenSideMenu === QAM) {
const main = nav.m_rgGamepadNavigationTrees.find(t => t.m_ID === "GamepadUI_Full_Root");
if (main && nav.m_LastActiveNavTree?.m_ID?.startsWith("QuickAccess")) nav.SetActiveNavTree(main);
backdrop(true);
}
} else {
globalThis.__ddQam = false;
backdrop(false);
if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus();
}
c.EnsureCorrectComposition?.();
return m.m_eOpenSideMenu;
})()"""
fun hold(context: Context): Int? = eval(context, script(true))?.toIntOrNull()
fun release(context: Context) {
eval(context, script(false))
helper(context, "stop")
}
fun park(context: Context, width: Int, height: Int) {
helper(context, "size", width.toString(), height.toString())
}
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"))
}.onFailure { android.util.Log.w(TAG, "no quick access target: $it") }.getOrNull()
private fun helper(context: Context, vararg args: String): String? = runCatching {
val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf("droiddeck-qam-park") + args)).put("timeout", 5.0)
val answer = AgentGuest.call(context, request, 8_000, trusted = true)
if (answer.optInt("exitCode", -1) == 0) answer.optJSONObject("stdout")?.optString("text") ?: answer.optString("stdout") else null
}.getOrNull()
private fun get(port: Int, path: String): String = java.net.Socket().use { s ->
s.connect(java.net.InetSocketAddress("127.0.0.1", port), 2_000)
s.soTimeout = 3_000
s.getOutputStream().apply {
write("GET $path HTTP/1.1\r\nHost: 127.0.0.1:$port\r\nAccept: */*\r\nConnection: close\r\n\r\n".toByteArray())
flush()
}
val response = s.getInputStream().readBytes().toString(Charsets.UTF_8)
val split = response.indexOf("\r\n\r\n")
check(response.startsWith("HTTP/1.1 200") && split > 0) { "devtools answered ${response.take(80)}" }
response.substring(split + 4)
}
internal fun parseTarget(port: Int, json: String): Target? {
val list = JSONArray(json)
for (i in 0 until list.length()) {
val t = list.optJSONObject(i) ?: continue
if (!t.optString("title").startsWith("QuickAccess")) continue
val ws = t.optString("webSocketDebuggerUrl")
val path = Regex("^ws://[^/]+(/devtools/page/[A-Za-z0-9-]+)$").find(ws)?.groupValues?.get(1) ?: continue
return Target(port, path)
}
return null
}
private fun eval(context: Context, expression: String): String? = runCatching {
val answer = AgentGuest.steamEval(context, expression, EVAL_MS)
if (answer.optBoolean("ok")) answer.opt("value")?.takeIf { it != JSONObject.NULL }?.toString() else null
}.getOrNull()
}
@@ -26,6 +26,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Dashboard
import androidx.compose.material.icons.outlined.Extension
import androidx.compose.material.icons.outlined.ViewSidebar
import androidx.compose.material.icons.outlined.CropFree
import androidx.compose.material.icons.outlined.MenuBook
import androidx.compose.material.icons.outlined.DesktopAccessDisabled
@@ -242,6 +243,7 @@ internal val SecondScreenMode.icon: ImageVector get() = when (this) {
SecondScreenMode.GUIDES -> Icons.Outlined.MenuBook
SecondScreenMode.MIRROR -> Icons.Outlined.CropFree
SecondScreenMode.COMPANION -> Icons.Outlined.Extension
SecondScreenMode.STEAM_QAM -> Icons.Outlined.ViewSidebar
SecondScreenMode.DESKTOP -> Icons.Outlined.DesktopWindows
}
@@ -36,6 +36,7 @@ internal fun BottomSessionPanel(mode: SecondScreenMode, actions: BottomPageActio
SecondScreenMode.GUIDES -> GuidesPanel(actions.runningGame)
SecondScreenMode.MIRROR -> MirrorPanel(actions)
SecondScreenMode.COMPANION -> CompanionPanel(actions.runningGame)
SecondScreenMode.STEAM_QAM -> SteamQamPanel()
else -> Unit
}
}
@@ -0,0 +1,167 @@
package com.droiddeck.launcher.ui
import android.graphics.BitmapFactory
import android.util.Base64
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
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.SteamQam
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import kotlin.concurrent.thread
import kotlin.math.min
import kotlin.math.roundToInt
internal class QamFrame(val image: ImageBitmap, val cssWidth: Float, val cssHeight: Float, val contentRight: Float) {
val pxPerCss: Float get() = image.width / cssWidth
}
internal object QamLayout {
fun fit(boxWidth: Float, boxHeight: Float, contentRight: Float, cssHeight: Float): Pair<Float, Float> {
val scale = min(boxWidth / contentRight, boxHeight / cssHeight)
return scale to (boxWidth - contentRight * scale) / 2f
}
fun toCss(x: Float, y: Float, scale: Float, left: Float): Pair<Float, Float> = (x - left) / scale to y / scale
const val CONTENT_SCRIPT = "(() => { const w = innerWidth; let right = 0; for (const e of document.body.querySelectorAll('*')) { " +
"const r = e.getBoundingClientRect(); if (r.width > 0 && r.height > 0 && r.width < w * 0.75 && r.right > right) right = r.right; } " +
"return JSON.stringify([w, innerHeight, devicePixelRatio, right]); })()"
}
private const val TICK_MS = 1_000L
@Composable
internal fun SteamQamPanel() {
val context = LocalContext.current.applicationContext
var image by remember { mutableStateOf<ImageBitmap?>(null) }
var shape by remember { mutableStateOf<FloatArray?>(null) }
var failed by remember { mutableStateOf(false) }
val holder = remember { arrayOfNulls<CdpPage>(1) }
DisposableEffect(Unit) {
onDispose {
val page = holder[0]
holder[0] = null
thread(name = "qam-release", isDaemon = true) {
runCatching { page?.send("Page.stopScreencast") }
page?.close()
SteamQam.release(context)
}
}
}
LaunchedEffect(Unit) {
var layout = floatArrayOf(0f, 0f, 1f, 0f)
var parked: Pair<Int, Int>? = null
withContext(Dispatchers.IO) {
while (isActive) {
val open = SteamQam.hold(context)
failed = open == null
if (open == SteamQam.QUICK_ACCESS) {
var page = holder[0]
if (page == null || page.closed) {
page?.close()
page = SteamQam.target(context)?.let { t ->
runCatching {
CdpPage(t.port, t.path) { method, params ->
if (method == "Page.screencastFrame") {
holder[0]?.send("Page.screencastFrameAck", JSONObject().put("sessionId", params.optInt("sessionId")))
val bytes = Base64.decode(params.optString("data"), Base64.DEFAULT)
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.let { image = it.asImageBitmap() }
}
}
}.onFailure { android.util.Log.w("SteamQam", "devtools connect: $it") }.getOrNull()
}
holder[0] = page
page?.send("Page.enable")
page?.send("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
.put("maxWidth", 1920).put("maxHeight", 1440))
}
(page?.evaluate(QamLayout.CONTENT_SCRIPT) as? String)?.let { text ->
runCatching {
val a = JSONArray(text)
layout = floatArrayOf(a.getDouble(0).toFloat(), a.getDouble(1).toFloat(), a.getDouble(2).toFloat(), a.getDouble(3).toFloat())
if (!layout.contentEquals(shape)) shape = layout
}
}
val size = (layout[0] * layout[2]).roundToInt() to (layout[1] * layout[2]).roundToInt()
if (layout[0] > 0f && size != parked) {
SteamQam.park(context, size.first, size.second)
parked = size
}
}
delay(TICK_MS)
}
}
}
val img = image
val l = shape
val f = if (img != null && l != null && l[0] > 0f) QamFrame(img, l[0], l[1], l[3].coerceIn(l[0] * 0.25f, l[0])) else null
if (f == null) {
PanelNote(stringResource(if (failed) R.string.bottom_qam_unavailable else R.string.achievements_reading))
return
}
BoxWithConstraints(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
val density = LocalDensity.current
val boxW = with(density) { maxWidth.toPx() }
val boxH = with(density) { maxHeight.toPx() }
val (scale, left) = QamLayout.fit(boxW, boxH, f.contentRight, f.cssHeight)
Canvas(
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
val change = event.changes.firstOrNull() ?: continue
val type = when (event.type) {
PointerEventType.Press -> "touchStart"
PointerEventType.Move -> "touchMove"
PointerEventType.Release -> "touchEnd"
else -> null
} ?: continue
val (x, y) = QamLayout.toCss(change.position.x, change.position.y, scale, left)
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 px = f.pxPerCss
drawImage(
f.image,
srcOffset = IntOffset.Zero,
srcSize = IntSize((f.contentRight * px).roundToInt().coerceAtMost(f.image.width), f.image.height),
dstOffset = IntOffset(left.roundToInt(), 0),
dstSize = IntSize((f.contentRight * scale).roundToInt(), (f.cssHeight * scale).roundToInt()),
filterQuality = FilterQuality.Medium,
)
}
}
}
@@ -338,7 +338,7 @@ class SecondScreenPresentation(
attachKeyboard()
}
SecondScreenMode.DASHBOARD -> renderDashboard()
SecondScreenMode.GUIDES, SecondScreenMode.MIRROR, SecondScreenMode.COMPANION -> renderPanel(mode)
SecondScreenMode.GUIDES, SecondScreenMode.MIRROR, SecondScreenMode.COMPANION, SecondScreenMode.STEAM_QAM -> renderPanel(mode)
SecondScreenMode.DESKTOP -> {
root.addView(BottomDesktopPanel(context, onClose, onMenu,
(onSteamMenu to onQam).takeIf { SessionState.mode == SessionService.MODE_STEAM }, onSwap,
@@ -368,7 +368,7 @@ class SecondScreenPresentation(
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }) + extras)
SecondScreenMode.DECK_CONTROLS -> model(extras, deckPanelTabs(context, deckPanel.value, ::selectDeckPanel))
SecondScreenMode.DASHBOARD, SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.GUIDES, SecondScreenMode.MIRROR,
SecondScreenMode.COMPANION -> model(extras)
SecondScreenMode.COMPANION, SecondScreenMode.STEAM_QAM -> 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
@@ -1430,10 +1430,13 @@ private fun SteamVrRow(a: DrawerActions) {
}
}
internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boolean, desktop: Boolean): List<SecondScreenMode> =
internal fun secondScreenModes(none: Boolean, deckPad: Boolean, dashboard: Boolean, desktop: Boolean,
steam: Boolean = com.droiddeck.launcher.session.SessionState.mode == com.droiddeck.launcher.session.SessionService.MODE_STEAM): List<SecondScreenMode> =
(if (none) listOf(SecondScreenMode.NONE) else emptyList()) + listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
(if (deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) + listOf(SecondScreenMode.CUSTOM_CONTROLS) +
(if (dashboard) listOf(SecondScreenMode.DASHBOARD, SecondScreenMode.GUIDES, SecondScreenMode.MIRROR, SecondScreenMode.COMPANION) else emptyList()) +
(if (dashboard) listOf(SecondScreenMode.DASHBOARD) else emptyList()) +
(if (dashboard && steam) listOf(SecondScreenMode.STEAM_QAM) else emptyList()) +
(if (dashboard) listOf(SecondScreenMode.GUIDES, SecondScreenMode.MIRROR, SecondScreenMode.COMPANION) else emptyList()) +
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
private val DRAWER_MIN_WIDTH = 300.dp
+2
View File
@@ -2243,6 +2243,8 @@
<string name="bottom_companion_character">الشخصية</string>
<string name="bottom_companion_weight">الحمولة</string>
<string name="bottom_companion_radio">الراديو</string>
<string name="bottom_qam_title">الوصول السريع</string>
<string name="bottom_qam_unavailable">قائمة الوصول السريع في Steam غير متاحة بعد.</string>
<string name="bottom_page_telemetry">إحصاءات داخل اللعبة</string>
<string name="bottom_hud_group">مؤشرات الشاشة السفلية</string>
<string name="bottom_strip_tabs">شريط على كل تبويب</string>
@@ -2238,6 +2238,8 @@
<string name="bottom_companion_character">Personaje</string>
<string name="bottom_companion_weight">Peso cargado</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Acceso rápido</string>
<string name="bottom_qam_unavailable">El menú de acceso rápido de Steam aún no está disponible.</string>
<string name="bottom_page_telemetry">Estadísticas del juego</string>
<string name="bottom_hud_group">HUD de la pantalla inferior</string>
<string name="bottom_strip_tabs">Franja en todas las pestañas</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Герой</string>
<string name="bottom_companion_weight">Товар</string>
<string name="bottom_companion_radio">Радио</string>
<string name="bottom_qam_title">Бърз достъп</string>
<string name="bottom_qam_unavailable">Менюто за бърз достъп на Steam още не е налично.</string>
<string name="bottom_page_telemetry">Статистика в играта</string>
<string name="bottom_hud_group">HUD на долния екран</string>
<string name="bottom_strip_tabs">Лента на всеки раздел</string>
+2
View File
@@ -2193,6 +2193,8 @@
<string name="bottom_companion_character">Postava</string>
<string name="bottom_companion_weight">Nosnost</string>
<string name="bottom_companion_radio">Rádio</string>
<string name="bottom_qam_title">Rychlý přístup</string>
<string name="bottom_qam_unavailable">Nabídka rychlého přístupu Steamu zatím není k dispozici.</string>
<string name="bottom_page_telemetry">Statistiky ve hře</string>
<string name="bottom_hud_group">HUD na spodní obrazovce</string>
<string name="bottom_strip_tabs">Lišta na každé kartě</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Figur</string>
<string name="bottom_companion_weight">Bæreevne</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Hurtig adgang</string>
<string name="bottom_qam_unavailable">Steams menu til hurtig adgang er ikke tilgængelig endnu.</string>
<string name="bottom_page_telemetry">Statistik i spillet</string>
<string name="bottom_hud_group">HUD på nederste skærm</string>
<string name="bottom_strip_tabs">Stribe på alle faner</string>
+2
View File
@@ -2135,6 +2135,8 @@
<string name="bottom_companion_character">Charakter</string>
<string name="bottom_companion_weight">Traglast</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Schnellzugriff</string>
<string name="bottom_qam_unavailable">Das Schnellzugriffsmenü von Steam ist noch nicht verfügbar.</string>
<string name="bottom_page_telemetry">Spielstatistiken</string>
<string name="bottom_hud_group">HUD für den unteren Bildschirm</string>
<string name="bottom_strip_tabs">Leiste auf jedem Tab</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Χαρακτήρας</string>
<string name="bottom_companion_weight">Φορτίο</string>
<string name="bottom_companion_radio">Ραδιόφωνο</string>
<string name="bottom_qam_title">Γρήγορη πρόσβαση</string>
<string name="bottom_qam_unavailable">Το μενού γρήγορης πρόσβασης του Steam δεν είναι ακόμη διαθέσιμο.</string>
<string name="bottom_page_telemetry">Στατιστικά παιχνιδιού</string>
<string name="bottom_hud_group">HUD κάτω οθόνης</string>
<string name="bottom_strip_tabs">Λωρίδα σε κάθε καρτέλα</string>
+2
View File
@@ -2168,6 +2168,8 @@
<string name="bottom_companion_character">Personaje</string>
<string name="bottom_companion_weight">Peso cargado</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Acceso rápido</string>
<string name="bottom_qam_unavailable">El menú de acceso rápido de Steam aún no está disponible.</string>
<string name="bottom_page_telemetry">Estadísticas del juego</string>
<string name="bottom_hud_group">HUD de la pantalla inferior</string>
<string name="bottom_strip_tabs">Barra en todas las pestañas</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Hahmo</string>
<string name="bottom_companion_weight">Kantokyky</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Pikavalikko</string>
<string name="bottom_qam_unavailable">Steamin pikavalikko ei ole vielä käytettävissä.</string>
<string name="bottom_page_telemetry">Pelinsisäiset tilastot</string>
<string name="bottom_hud_group">Alanäytön HUD</string>
<string name="bottom_strip_tabs">Palkki kaikilla välilehdillä</string>
+2
View File
@@ -2167,6 +2167,8 @@
<string name="bottom_companion_character">Personnage</string>
<string name="bottom_companion_weight">Charge</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Accès rapide</string>
<string name="bottom_qam_unavailable">Le menu d’accès rapide de Steam n’est pas encore disponible.</string>
<string name="bottom_page_telemetry">Statistiques en jeu</string>
<string name="bottom_hud_group">HUD de l\'écran du bas</string>
<string name="bottom_strip_tabs">Bande sur tous les onglets</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">किरदार</string>
<string name="bottom_companion_weight">वज़न क्षमता</string>
<string name="bottom_companion_radio">रेडियो</string>
<string name="bottom_qam_title">क्विक एक्सेस</string>
<string name="bottom_qam_unavailable">Steam का क्विक एक्सेस मेनू अभी उपलब्ध नहीं है।</string>
<string name="bottom_page_telemetry">इन-गेम आंकड़े</string>
<string name="bottom_hud_group">निचली स्क्रीन HUD</string>
<string name="bottom_strip_tabs">हर टैब पर स्ट्रिप</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Karakter</string>
<string name="bottom_companion_weight">Teherbírás</string>
<string name="bottom_companion_radio">Rádió</string>
<string name="bottom_qam_title">Gyorselérés</string>
<string name="bottom_qam_unavailable">A Steam gyorselérési menüje még nem érhető el.</string>
<string name="bottom_page_telemetry">Játékon belüli statisztikák</string>
<string name="bottom_hud_group">HUD az alsó képernyőn</string>
<string name="bottom_strip_tabs">Sáv minden lapon</string>
+2
View File
@@ -2119,6 +2119,8 @@
<string name="bottom_companion_character">Karakter</string>
<string name="bottom_companion_weight">Beban</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Akses Cepat</string>
<string name="bottom_qam_unavailable">Menu Akses Cepat Steam belum tersedia.</string>
<string name="bottom_page_telemetry">Statistik dalam gim</string>
<string name="bottom_hud_group">HUD layar bawah</string>
<string name="bottom_strip_tabs">Strip di setiap tab</string>
+2
View File
@@ -2159,6 +2159,8 @@
<string name="bottom_companion_character">Personaggio</string>
<string name="bottom_companion_weight">Peso trasportato</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Accesso rapido</string>
<string name="bottom_qam_unavailable">Il menu di accesso rapido di Steam non è ancora disponibile.</string>
<string name="bottom_page_telemetry">Statistiche di gioco</string>
<string name="bottom_hud_group">HUD dello schermo inferiore</string>
<string name="bottom_strip_tabs">Barra su ogni scheda</string>
+2
View File
@@ -2119,6 +2119,8 @@
<string name="bottom_companion_character">キャラクター</string>
<string name="bottom_companion_weight">所持重量</string>
<string name="bottom_companion_radio">ラジオ</string>
<string name="bottom_qam_title">クイックアクセス</string>
<string name="bottom_qam_unavailable">Steam のクイックアクセスメニューはまだ使えません。</string>
<string name="bottom_page_telemetry">ゲーム内統計</string>
<string name="bottom_hud_group">下部画面の HUD</string>
<string name="bottom_strip_tabs">すべてのタブにストリップを表示</string>
+2
View File
@@ -2119,6 +2119,8 @@
<string name="bottom_companion_character">캐릭터</string>
<string name="bottom_companion_weight">소지 무게</string>
<string name="bottom_companion_radio">라디오</string>
<string name="bottom_qam_title">빠른 메뉴</string>
<string name="bottom_qam_unavailable">Steam 빠른 메뉴를 아직 사용할 수 없습니다.</string>
<string name="bottom_page_telemetry">게임 내 통계</string>
<string name="bottom_hud_group">하단 화면 HUD</string>
<string name="bottom_strip_tabs">모든 탭에 스트립 표시</string>
+2
View File
@@ -2119,6 +2119,8 @@
<string name="bottom_companion_character">Watak</string>
<string name="bottom_companion_weight">Beban</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Akses Pantas</string>
<string name="bottom_qam_unavailable">Menu Akses Pantas Steam belum tersedia.</string>
<string name="bottom_page_telemetry">Statistik dalam permainan</string>
<string name="bottom_hud_group">HUD skrin bawah</string>
<string name="bottom_strip_tabs">Jalur pada setiap tab</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Figur</string>
<string name="bottom_companion_weight">Bæreevne</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Hurtigtilgang</string>
<string name="bottom_qam_unavailable">Steams hurtigtilgangsmeny er ikke tilgjengelig ennå.</string>
<string name="bottom_page_telemetry">Statistikk i spillet</string>
<string name="bottom_hud_group">HUD på bunnskjermen</string>
<string name="bottom_strip_tabs">Stripe på hver fane</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Personage</string>
<string name="bottom_companion_weight">Draaggewicht</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Snelle toegang</string>
<string name="bottom_qam_unavailable">Het menu Snelle toegang van Steam is nog niet beschikbaar.</string>
<string name="bottom_page_telemetry">In-game statistieken</string>
<string name="bottom_hud_group">HUD op het onderste scherm</string>
<string name="bottom_strip_tabs">Strip op elk tabblad</string>
+2
View File
@@ -2193,6 +2193,8 @@
<string name="bottom_companion_character">Postać</string>
<string name="bottom_companion_weight">Udźwig</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Szybki dostęp</string>
<string name="bottom_qam_unavailable">Menu szybkiego dostępu Steam nie jest jeszcze dostępne.</string>
<string name="bottom_page_telemetry">Statystyki w grze</string>
<string name="bottom_hud_group">HUD dolnego ekranu</string>
<string name="bottom_strip_tabs">Pasek na każdej karcie</string>
@@ -2173,6 +2173,8 @@
<string name="bottom_companion_character">Personagem</string>
<string name="bottom_companion_weight">Peso transportado</string>
<string name="bottom_companion_radio">Rádio</string>
<string name="bottom_qam_title">Acesso rápido</string>
<string name="bottom_qam_unavailable">O menu de acesso rápido do Steam ainda não está disponível.</string>
<string name="bottom_page_telemetry">Estatísticas no jogo</string>
<string name="bottom_hud_group">HUD do ecrã inferior</string>
<string name="bottom_strip_tabs">Faixa em todos os separadores</string>
+2
View File
@@ -2181,6 +2181,8 @@
<string name="bottom_companion_character">Personagem</string>
<string name="bottom_companion_weight">Peso carregado</string>
<string name="bottom_companion_radio">Rádio</string>
<string name="bottom_qam_title">Acesso rápido</string>
<string name="bottom_qam_unavailable">O menu de acesso rápido do Steam ainda não está disponível.</string>
<string name="bottom_page_telemetry">Estatísticas no jogo</string>
<string name="bottom_hud_group">HUD da tela inferior</string>
<string name="bottom_strip_tabs">Faixa em todas as abas</string>
+2
View File
@@ -2168,6 +2168,8 @@
<string name="bottom_companion_character">Personaj</string>
<string name="bottom_companion_weight">Greutate purtată</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Acces rapid</string>
<string name="bottom_qam_unavailable">Meniul de acces rapid Steam nu este încă disponibil.</string>
<string name="bottom_page_telemetry">Statistici în joc</string>
<string name="bottom_hud_group">HUD pe ecranul de jos</string>
<string name="bottom_strip_tabs">Bandă pe fiecare filă</string>
+2
View File
@@ -2194,6 +2194,8 @@
<string name="bottom_companion_character">Персонаж</string>
<string name="bottom_companion_weight">Переносимый вес</string>
<string name="bottom_companion_radio">Радио</string>
<string name="bottom_qam_title">Быстрый доступ</string>
<string name="bottom_qam_unavailable">Меню быстрого доступа Steam пока недоступно.</string>
<string name="bottom_page_telemetry">Игровая статистика</string>
<string name="bottom_hud_group">HUD нижнего экрана</string>
<string name="bottom_strip_tabs">Полоса на всех вкладках</string>
+2
View File
@@ -2143,6 +2143,8 @@
<string name="bottom_companion_character">Karaktär</string>
<string name="bottom_companion_weight">Bärvikt</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Snabbåtkomst</string>
<string name="bottom_qam_unavailable">Steams snabbåtkomstmeny är inte tillgänglig än.</string>
<string name="bottom_page_telemetry">Statistik i spelet</string>
<string name="bottom_hud_group">HUD på nedre skärmen</string>
<string name="bottom_strip_tabs">Remsa på varje flik</string>
+2
View File
@@ -2119,6 +2119,8 @@
<string name="bottom_companion_character">ตัวละคร</string>
<string name="bottom_companion_weight">น้ำหนักที่แบก</string>
<string name="bottom_companion_radio">วิทยุ</string>
<string name="bottom_qam_title">เข้าถึงด่วน</string>
<string name="bottom_qam_unavailable">เมนูเข้าถึงด่วนของ Steam ยังไม่พร้อมใช้งาน</string>
<string name="bottom_page_telemetry">สถิติในเกม</string>
<string name="bottom_hud_group">HUD หน้าจอล่าง</string>
<string name="bottom_strip_tabs">แถบในทุกแท็บ</string>
+2
View File
@@ -2135,6 +2135,8 @@
<string name="bottom_companion_character">Karakter</string>
<string name="bottom_companion_weight">Taşıma ağırlığı</string>
<string name="bottom_companion_radio">Radyo</string>
<string name="bottom_qam_title">Hızlı Erişim</string>
<string name="bottom_qam_unavailable">Steam Hızlı Erişim menüsü henüz kullanılamıyor.</string>
<string name="bottom_page_telemetry">Oyun içi istatistikler</string>
<string name="bottom_hud_group">Alt ekrandaki HUD</string>
<string name="bottom_strip_tabs">Her sekmede şerit</string>
+2
View File
@@ -2193,6 +2193,8 @@
<string name="bottom_companion_character">Персонаж</string>
<string name="bottom_companion_weight">Вага ноші</string>
<string name="bottom_companion_radio">Радіо</string>
<string name="bottom_qam_title">Швидкий доступ</string>
<string name="bottom_qam_unavailable">Меню швидкого доступу Steam ще недоступне.</string>
<string name="bottom_page_telemetry">Ігрова статистика</string>
<string name="bottom_hud_group">HUD на нижньому екрані</string>
<string name="bottom_strip_tabs">Смуга на кожній вкладці</string>
+2
View File
@@ -2119,6 +2119,8 @@
<string name="bottom_companion_character">Nhân vật</string>
<string name="bottom_companion_weight">Trọng lượng mang</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Truy cập nhanh</string>
<string name="bottom_qam_unavailable">Menu Truy cập nhanh của Steam chưa sẵn sàng.</string>
<string name="bottom_page_telemetry">Thông số trong game</string>
<string name="bottom_hud_group">HUD màn hình dưới</string>
<string name="bottom_strip_tabs">Thanh trên mọi tab</string>
@@ -2196,6 +2196,8 @@
<string name="bottom_companion_character">角色</string>
<string name="bottom_companion_weight">负重</string>
<string name="bottom_companion_radio">收音机</string>
<string name="bottom_qam_title">快速访问</string>
<string name="bottom_qam_unavailable">Steam 快速访问菜单暂不可用。</string>
<string name="bottom_page_telemetry">游戏内数据</string>
<string name="bottom_hud_group">下屏 HUD</string>
<string name="bottom_strip_tabs">所有页签显示横条</string>
@@ -2118,6 +2118,8 @@
<string name="bottom_companion_character">角色</string>
<string name="bottom_companion_weight">負重</string>
<string name="bottom_companion_radio">收音機</string>
<string name="bottom_qam_title">快速存取</string>
<string name="bottom_qam_unavailable">Steam 快速存取選單暫時無法使用。</string>
<string name="bottom_page_telemetry">遊戲內數據</string>
<string name="bottom_hud_group">下方螢幕 HUD</string>
<string name="bottom_strip_tabs">在所有分頁顯示資訊列</string>
@@ -2118,6 +2118,8 @@
<string name="bottom_companion_character">角色</string>
<string name="bottom_companion_weight">負重</string>
<string name="bottom_companion_radio">收音機</string>
<string name="bottom_qam_title">快速存取</string>
<string name="bottom_qam_unavailable">Steam 快速存取選單暫時無法使用。</string>
<string name="bottom_page_telemetry">遊戲內數據</string>
<string name="bottom_hud_group">下螢幕 HUD</string>
<string name="bottom_strip_tabs">在每個分頁顯示資訊列</string>
+2
View File
@@ -2426,6 +2426,8 @@
<string name="bottom_companion_character">Character</string>
<string name="bottom_companion_weight">Carry weight</string>
<string name="bottom_companion_radio">Radio</string>
<string name="bottom_qam_title">Quick Access</string>
<string name="bottom_qam_unavailable">Steam\'s Quick Access menu is not available yet.</string>
<string name="bottom_page_telemetry">In-game stats</string>
<string name="bottom_hud_group">Bottom screen HUD</string>
<string name="bottom_strip_tabs">Strip on every tab</string>
@@ -99,6 +99,12 @@ class SecondScreenModeTest {
assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("dashboard", deckPad = false))
}
@Test fun steamQuickAccessOpensAgainOnlyInASteamSession() {
assertEquals(SecondScreenMode.STEAM_QAM, SecondScreenMode.opening("steam-qam", deckPad = true, dashboard = true, steam = true))
assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("steam-qam", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("steam-qam", deckPad = true, steam = true))
}
@Test fun theDesktopOpensAgainOnlyWhileItCanRun() {
assertEquals(SecondScreenMode.DESKTOP, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true, bottomDesktop = true))
assertEquals(SecondScreenMode.MENU, SecondScreenMode.opening("desktop", deckPad = true, dashboard = true))
@@ -0,0 +1,51 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.ui.QamLayout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class SteamQamTest {
@Test fun findsTheQuickAccessPageAndKeepsOnlyItsPath() {
val json = """[
{"title":"SP BPM_uid0","webSocketDebuggerUrl":"ws://127.0.0.1:8080/devtools/page/AAA"},
{"title":"QuickAccess_uid2","webSocketDebuggerUrl":"ws://127.0.0.1:8080/devtools/page/0F3A-b9"}
]"""
assertEquals(SteamQam.Target(4321, "/devtools/page/0F3A-b9"), SteamQam.parseTarget(4321, json))
}
@Test fun ignoresMissingOrForeignDebuggerUrls() {
assertNull(SteamQam.parseTarget(1, """[{"title":"SP BPM_uid0","webSocketDebuggerUrl":"ws://127.0.0.1:1/devtools/page/A"}]"""))
assertNull(SteamQam.parseTarget(1, """[{"title":"QuickAccess_uid2"}]"""))
assertNull(SteamQam.parseTarget(1, """[{"title":"QuickAccess_uid2","webSocketDebuggerUrl":"ws://x/devtools/page/A?b=1"}]"""))
}
@Test fun holdingCapsCompositionOnlyWhileTheMenuIsOursAndReleasingClosesIt() {
val on = SteamQam.script(true)
val off = SteamQam.script(false)
assertTrue(on.contains("if (true)"))
assertTrue(off.contains("if (false)"))
assertTrue(on.contains("globalThis.__ddQam && v === 2 && m.m_eOpenSideMenu === QAM ? 1 : v"))
assertTrue(on.contains("startsWith(\"QuickAccess\")"))
assertTrue(off.contains("m.CloseSideMenus()"))
}
@Test fun theMenuFillsTheHeightAndCentresAndTouchesMapBack() {
val (scale, left) = QamLayout.fit(1280f, 832f, 400f, 640f)
assertEquals(1.3f, scale, 0.001f)
assertEquals((1280f - 520f) / 2f, left, 0.001f)
val (x, y) = QamLayout.toCss(left + 130f, 260f, scale, left)
assertEquals(100f, x, 0.001f)
assertEquals(200f, y, 0.001f)
}
@Test fun aWideMenuFitsTheWidth() {
val (scale, left) = QamLayout.fit(1280f, 832f, 1280f, 640f)
assertEquals(1f, scale, 0.001f)
assertEquals(0f, left, 0.001f)
}
}
+19
View File
@@ -163,6 +163,25 @@ Let mods running in Proton drive native bottom-screen pages over loopback. Thor
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 any tab a plugin loader adds. 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-park`](../../tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-park).
Plugin loaders expose Steam's CEF DevTools so the menu can be viewed in a desktop browser, but it renders only while it is open on the main screen. The panel keeps it open without covering the top screen:
- Steam's UI is told to open the menu and keep it open: its composition request is capped at "notification" while the menu is ours, so gamescope keeps focus on the game, and losing focus no longer closes it. Gamepad focus moves from the menu back to the main UI only when the menu took it, so Steam's own popups keep the controller. The blurred backdrop is hidden.
- `droiddeck-qam-park` moves the menu's X window outside the Big Picture window, where it keeps rendering but is not shown on top. It also relays the app to the DevTools port, which only answers clients inside the guest.
- The panel streams the menu with `Page.startScreencast`, scales its content to the panel height and forwards touches with `Input.dispatchTouchEvent`.
- Leaving the panel closes the menu and turns the patches off; the Steam button and the normal Quick Access button then work as before. Opening Steam's main menu replaces the Quick Access menu for as long as it is open, as on a Deck.
Limits: it relies on Steam's minified UI stores and method names, so a client update can break it; the panel then shows that the menu is not available. Plugin tabs appear only if a loader is installed in the session.
| Big Picture, friends | In game, performance | Quick settings, scrolled |
| --- | --- | --- |
| ![](evidence/bottom-screen-qam-friends-2026-11-27.png) | ![](evidence/bottom-screen-qam-performance-ingame-2026-11-27.png) | ![](evidence/bottom-screen-qam-settings-2026-11-27.png) |
The top screen during that game, with the menu open on the bottom: ![](evidence/bottom-screen-qam-top-ingame-2026-11-27.png)
## Related fixes
- Add the missing dual-screen settings to `SettingsIndex` and regenerate [`settings-map.md`](../settings-map.md).
Binary file not shown.

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 821 KiB

+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/python3
# Keeps Steam's quick access menu rendering for the bottom screen: parks its X window outside the Big Picture window,
# and relays the app to Steam's DevTools port, which only answers clients inside the guest.
# droiddeck-qam-park start <devtools port> prints the relay port
# droiddeck-qam-park size <width> <height> pixels of the menu's X window
# droiddeck-qam-park stop
import ctypes
import os
import re
import socket
import subprocess
import sys
import threading
import time
FLAG = "/tmp/.dd-qam-park"
SIZE = "/tmp/.dd-qam-size"
TOLERANCE = 4
INTERVAL = 0.25
MAX_SECONDS = 6 * 3600
CHILD = re.compile(r"^\s+(0x[0-9a-f]+) .*?\s(\d+)x(\d+)\+(-?\d+)\+(-?\d+)\s")
def display():
return os.environ.get("DISPLAY") or ":0"
def find(width, height):
lines = subprocess.run(["xwininfo", "-root", "-tree"], env=dict(os.environ, DISPLAY=display()),
capture_output=True, text=True, timeout=5).stdout.splitlines()
for i, line in enumerate(lines):
if '"Steam Big Picture Mode"' not in line:
continue
parent = re.search(r"\s(\d+)x(\d+)\+", line)
parent_width = int(parent.group(1)) if parent else 1280
indent = len(line) - len(line.lstrip())
for child in lines[i + 1:]:
if child.strip() and len(child) - len(child.lstrip()) <= indent:
break
m = CHILD.match(child)
if not m or len(child) - len(child.lstrip()) != indent + 3:
continue
w, h, x, y = int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5))
if abs(w - width) <= TOLERANCE and abs(h - height) <= TOLERANCE:
return int(m.group(1), 16), x, y, parent_width
return None
def owner():
try:
with open(FLAG) as f:
return f.read().strip()
except OSError:
return None
def wanted_size():
try:
with open(SIZE) as f:
w, h = f.read().split()
return int(w), int(h)
except (OSError, ValueError):
return None
def pipe(src, dst):
try:
while True:
data = src.recv(65536)
if not data:
break
dst.sendall(data)
except OSError:
pass
for s in (src, dst):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def relay(server, devtools_port):
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()
def park():
x11 = ctypes.CDLL("libX11.so.6")
x11.XOpenDisplay.restype = ctypes.c_void_p
x11.XOpenDisplay.argtypes = [ctypes.c_char_p]
x11.XMoveWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int]
x11.XFlush.argtypes = [ctypes.c_void_p]
d = x11.XOpenDisplay(display().encode())
started = time.monotonic()
me = str(os.getpid())
while owner() == me and time.monotonic() - started < MAX_SECONDS:
size = wanted_size()
if d and size:
try:
found = find(*size)
except (OSError, subprocess.SubprocessError):
found = None
if found:
win, x, y, parent_width = found
if x < parent_width:
x11.XMoveWindow(d, win, parent_width + 64, y)
x11.XFlush(d)
time.sleep(INTERVAL)
def main():
command = sys.argv[1] if len(sys.argv) > 1 else ""
if command == "stop":
for path in (FLAG, SIZE):
try:
os.unlink(path)
except FileNotFoundError:
pass
return 0
if command == "size" and len(sys.argv) == 4:
with open(SIZE, "w") as f:
f.write("%d %d" % (int(sys.argv[2]), int(sys.argv[3])))
return 0
if command != "start" or len(sys.argv) != 3:
print("usage: droiddeck-qam-park start <devtools port> | size <width> <height> | stop", file=sys.stderr)
return 2
devtools_port = int(sys.argv[2])
server = socket.socket()
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)
if os.fork():
return 0
os.setsid()
with open(FLAG, "w") as f:
f.write(str(os.getpid()))
devnull = os.open(os.devnull, os.O_RDWR)
for fd in (0, 1, 2):
os.dup2(devnull, fd)
threading.Thread(target=relay, args=(server, devtools_port), daemon=True).start()
park()
server.close()
return 0
if __name__ == "__main__":
sys.exit(main())
+76
View File
@@ -0,0 +1,76 @@
import importlib.machinery
import importlib.util
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest import mock
HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-qam-park"
TREE = """
Root window id: 0x3c3 (the root window) (has no name)
1 child:
0x2000035 "Steam Big Picture Mode": ("steamwebhelper" "steam") 1280x720+0+0 +0+0
4 children:
0x1600014 (has no name): () 1136x615+%d+53 +%d+53
1 child:
0x1600015 (has no name): () 1136x615+0+0 +0+53
0x1600016 (has no name): () 426x107+0+0 +0+0
1 child:
0x1600017 (has no name): () 426x107+0+0 +0+0
0x1600012 (has no name): () 1x1+0+0 +0+0
0x2000040 "Other": () 1136x615+0+0 +0+0
"""
def load():
loader = importlib.machinery.SourceFileLoader("qam_park", str(HELPER))
spec = importlib.util.spec_from_loader("qam_park", loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
class QamParkTest(unittest.TestCase):
def setUp(self):
self.park = load()
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.park.FLAG = str(self.tmp / "flag")
self.park.SIZE = str(self.tmp / "size")
def tree(self, x):
return mock.patch.object(self.park.subprocess, "run",
return_value=subprocess.CompletedProcess([], 0, TREE % (x, x), ""))
def test_finds_the_menu_window_among_big_picture_children(self):
with self.tree(818):
self.assertEqual((0x1600014, 818, 53, 1280), self.park.find(1136, 615))
with self.tree(1344):
self.assertEqual((0x1600014, 1344, 53, 1280), self.park.find(1135, 617))
def test_ignores_windows_of_another_size_or_outside_big_picture(self):
with self.tree(818):
self.assertIsNone(self.park.find(1136, 722))
self.assertIsNone(self.park.find(1136, 600))
def test_size_and_stop_manage_the_state_files(self):
with mock.patch.object(self.park.sys, "argv", ["x", "size", "1136", "615"]):
self.assertEqual(0, self.park.main())
self.assertEqual((1136, 615), self.park.wanted_size())
Path(self.park.FLAG).write_text("1")
with mock.patch.object(self.park.sys, "argv", ["x", "stop"]):
self.assertEqual(0, self.park.main())
self.assertFalse(os.path.exists(self.park.FLAG))
self.assertIsNone(self.park.wanted_size())
def test_rejects_unknown_commands(self):
with mock.patch.object(self.park.sys, "argv", ["x", "start"]), mock.patch.object(self.park.sys, "stderr"):
self.assertEqual(2, self.park.main())
if __name__ == "__main__":
unittest.main()