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 f5ed5c07df..262f529620 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamQam.kt @@ -6,31 +6,37 @@ 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. +// Steam renders the quick access menu only while it is open. While the app holds it, the menu is kept open with its +// browser view placed outside the Big Picture window, composition capped at "notification" so gamescope keeps the game +// focused, and gamepad focus on the main UI. The hold is a lease the app renews, so Steam recovers if the app goes away. object SteamQam { data class Target(val port: Int, val path: String) const val QUICK_ACCESS = 2 + const val LEASE_MS = 5_000 private const val TAG = "SteamQam" private const val EVAL_MS = 6_000L internal fun script(on: Boolean): String = """(() => { + const g = globalThis, QAM = 2; 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; + const nav = W.m_FocusNavContext; + const popup = g_PopupManager.GetExistingPopup("SP BPM_uid0"); + const held = () => g.__ddQamUntil > Date.now(); + const ours = () => held() && m.m_eOpenSideMenu === QAM; + if (!c.__ddQam) { + c.__ddQam = c.ComputeOverallMinimumRequestedComposition; c.ComputeOverallMinimumRequestedComposition = function (...a) { - const v = c.__dd.apply(this, a); - return globalThis.__ddQam && v === 2 && m.m_eOpenSideMenu === QAM ? 1 : v; + const v = c.__ddQam.apply(this, a); + return v === 2 && ours() ? 1 : v; }; - m.__dd = m.OnMenuDeactivated; - m.OnMenuDeactivated = function (d) { if (globalThis.__ddQam && d === QAM) return; return m.__dd.call(this, d); }; + m.__ddQam = m.OnMenuDeactivated; + m.OnMenuDeactivated = function (d) { if (d === QAM && held()) return; return m.__ddQam.call(this, d); }; } + const views = () => popup?.m_rgChildBrowserViews || []; const backdrop = (hide) => { + const doc = popup?.m_popup?.document; 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; } @@ -42,20 +48,47 @@ object SteamQam { } } }; - 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); + const keep = () => { + for (const v of views()) { + if (v.__ddQam) continue; + v.__ddQam = v.SetBounds; + v.SetBounds = function (x, y, w, h, ...r) { + v.__ddAsked = [x, y, w, h]; + if (w > 0 && ours()) x = popup.m_popup.innerWidth + 64; + v.__ddAt = x; + return v.__ddQam.call(this, x, y, w, h, ...r); + }; } - } else { - globalThis.__ddQam = false; - backdrop(false); - if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus(); + if (!held()) { + if (!g.__ddQamOn) return; + g.__ddQamOn = false; + backdrop(false); + if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus(); + c.EnsureCorrectComposition?.(); + return; + } + if (m.m_eOpenSideMenu === 0) { m.OpenQuickAccessMenu(); c.EnsureCorrectComposition?.(); } + if (m.m_eOpenSideMenu !== QAM) return; + if (!g.__ddQamOn) { g.__ddQamOn = true; c.EnsureCorrectComposition?.(); } + for (const v of views()) { + if (!v.__ddAsked) { + const b = v.GetBounds?.(); + if (b && b.width > 0) { v.__ddAsked = [b.x, b.y, b.width, b.height]; v.__ddAt = b.x; } + } + if (v.__ddAsked?.[2] > 0 && v.__ddAt < popup.m_popup.innerWidth) v.SetBounds(...v.__ddAsked); + } + 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); + }; + g.__ddQamUntil = ${if (on) "Date.now() + $LEASE_MS" else "0"}; + keep(); + if (held() && !g.__ddQamTimer) { + g.__ddQamTimer = setInterval(() => { + keep(); + if (!held() && !g.__ddQamOn) { clearInterval(g.__ddQamTimer); g.__ddQamTimer = 0; } + }, 250); } - c.EnsureCorrectComposition?.(); return m.m_eOpenSideMenu; })()""" @@ -66,10 +99,6 @@ object SteamQam { 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 @@ -77,7 +106,7 @@ object SteamQam { }.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 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) if (answer.optInt("exitCode", -1) == 0) answer.optJSONObject("stdout")?.optString("text") ?: answer.optString("stdout") else null }.getOrNull() 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 2dad748855..66d1a119a8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomSteamQamPanel.kt @@ -7,7 +7,6 @@ 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 @@ -16,8 +15,10 @@ 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.Color import androidx.compose.ui.graphics.FilterQuality import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.input.pointer.PointerEventType import androidx.compose.ui.input.pointer.pointerInput @@ -28,19 +29,27 @@ 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.SessionPhase +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.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 + + /** The menu's own background, sampled inside its right edge, to fill the panel around it. */ + val fill: Color = runCatching { + val x = (contentRight * pxPerCss).roundToInt() - 4 + Color(image.asAndroidBitmap().getPixel(x.coerceIn(0, image.width - 1), image.height / 2)) + }.getOrDefault(Color.Black) } internal object QamLayout { @@ -77,10 +86,13 @@ internal fun SteamQamPanel() { } } LaunchedEffect(Unit) { - var layout = floatArrayOf(0f, 0f, 1f, 0f) - var parked: Pair? = null withContext(Dispatchers.IO) { while (isActive) { + // Holding the menu before Steam's first frame keeps gamescope from presenting it. + if (SessionState.phase != SessionPhase.READY) { + delay(TICK_MS) + continue + } val open = SteamQam.hold(context) failed = open == null if (open == SteamQam.QUICK_ACCESS) { @@ -106,15 +118,10 @@ internal fun SteamQamPanel() { (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()) + 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 } } - 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) } @@ -122,12 +129,14 @@ internal fun SteamQamPanel() { } 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 + val f = remember(img, l) { + 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)) { + BoxWithConstraints(Modifier.fillMaxSize().background(f.fill)) { val density = LocalDensity.current val boxW = with(density) { maxWidth.toPx() } val boxH = with(density) { maxHeight.toPx() } 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 122c8900c8..fd0fb36e7b 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamQamTest.kt @@ -24,14 +24,17 @@ class SteamQamTest { 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 holdingIsALeaseAndReleasingEndsIt() { + assertTrue(SteamQam.script(true).contains("g.__ddQamUntil = Date.now() + ${SteamQam.LEASE_MS};")) + assertTrue(SteamQam.script(false).contains("g.__ddQamUntil = 0;")) + } + + @Test fun whileHeldTheMenuStaysOffTheTopScreenAndOutOfTheGamesWay() { + val script = SteamQam.script(true) + assertTrue(script.contains("return v === 2 && ours() ? 1 : v;")) + assertTrue(script.contains("if (w > 0 && ours()) x = popup.m_popup.innerWidth + 64;")) + assertTrue(script.contains("nav.m_LastActiveNavTree?.m_ID?.startsWith(\"QuickAccess\")")) + assertTrue(script.contains("if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus();")) } @Test fun theMenuFillsTheHeightAndCentresAndTouchesMapBack() { diff --git a/docs/development/bottom-screen.md b/docs/development/bottom-screen.md index ac6c8ced0d..cf148ae061 100644 --- a/docs/development/bottom-screen.md +++ b/docs/development/bottom-screen.md @@ -165,18 +165,20 @@ 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). +**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-relay`](../../tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay). 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`. +- The menu's browser view is placed just outside the Big Picture window through its own `SetBounds`, so it keeps rendering but never shows on top, including while Steam slides it wider for Friends and chat. +- A timer inside Steam keeps this state every 250 ms, so the menu comes back as soon as Steam's main menu closes. It runs on a 5 s lease that the panel renews each second: if the app stops, Steam returns to normal by itself. +- The hold starts only once the session is ready: holding the menu before Steam's first frame kept gamescope from presenting anything. +- `droiddeck-qam-relay` 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 and fills the rest with the menu's own background, 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 | +| Big Picture, friends | In game, performance | In game, quick settings | | --- | --- | --- | | ![](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) | diff --git a/docs/development/evidence/bottom-screen-qam-friends-2026-11-27.png b/docs/development/evidence/bottom-screen-qam-friends-2026-11-27.png index 8376864d0f..25ce2514cf 100644 Binary files a/docs/development/evidence/bottom-screen-qam-friends-2026-11-27.png and b/docs/development/evidence/bottom-screen-qam-friends-2026-11-27.png differ diff --git a/docs/development/evidence/bottom-screen-qam-performance-ingame-2026-11-27.png b/docs/development/evidence/bottom-screen-qam-performance-ingame-2026-11-27.png index 7f9a7ff10c..4d93a28f40 100644 Binary files a/docs/development/evidence/bottom-screen-qam-performance-ingame-2026-11-27.png and b/docs/development/evidence/bottom-screen-qam-performance-ingame-2026-11-27.png differ diff --git a/docs/development/evidence/bottom-screen-qam-settings-2026-11-27.png b/docs/development/evidence/bottom-screen-qam-settings-2026-11-27.png index 8ab41fda99..df0e579684 100644 Binary files a/docs/development/evidence/bottom-screen-qam-settings-2026-11-27.png and b/docs/development/evidence/bottom-screen-qam-settings-2026-11-27.png differ diff --git a/docs/development/evidence/bottom-screen-qam-top-ingame-2026-11-27.png b/docs/development/evidence/bottom-screen-qam-top-ingame-2026-11-27.png index 198ddb41ad..01869fe49d 100644 Binary files a/docs/development/evidence/bottom-screen-qam-top-ingame-2026-11-27.png and b/docs/development/evidence/bottom-screen-qam-top-ingame-2026-11-27.png differ diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-park b/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-park deleted file mode 100755 index b736ebe010..0000000000 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-park +++ /dev/null @@ -1,159 +0,0 @@ -#!/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 prints the relay port -# droiddeck-qam-park size 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 | size | 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()) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay b/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay new file mode 100755 index 0000000000..a76763563b --- /dev/null +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-qam-relay @@ -0,0 +1,96 @@ +#!/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 +# droiddeck-qam-relay stop + +import os +import socket +import sys +import threading +import time + +FLAG = "/tmp/.dd-qam-relay" +INTERVAL = 0.5 +MAX_SECONDS = 6 * 3600 + + +def owner(): + try: + with open(FLAG) as f: + return f.read().strip() + except OSError: + 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 serve(server, devtools_port, me): + threading.Thread(target=relay, args=(server, devtools_port), daemon=True).start() + started = time.monotonic() + while owner() == me and time.monotonic() - started < MAX_SECONDS: + time.sleep(INTERVAL) + server.close() + + +def main(): + command = sys.argv[1] if len(sys.argv) > 1 else "" + if command == "stop" and len(sys.argv) == 2: + try: + os.unlink(FLAG) + except FileNotFoundError: + pass + return 0 + if command != "start" or len(sys.argv) != 3: + print("usage: droiddeck-qam-relay start | 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() + me = str(os.getpid()) + with open(FLAG, "w") as f: + f.write(me) + devnull = os.open(os.devnull, os.O_RDWR) + for fd in (0, 1, 2): + os.dup2(devnull, fd) + serve(server, devtools_port, me) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tests/test_qam_park.py b/tools/tests/test_qam_park.py deleted file mode 100644 index 6ed47ede29..0000000000 --- a/tools/tests/test_qam_park.py +++ /dev/null @@ -1,76 +0,0 @@ -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() diff --git a/tools/tests/test_qam_relay.py b/tools/tests/test_qam_relay.py new file mode 100644 index 0000000000..fdf7640446 --- /dev/null +++ b/tools/tests/test_qam_relay.py @@ -0,0 +1,65 @@ +import importlib.machinery +import importlib.util +import shutil +import socket +import tempfile +import threading +import unittest +from pathlib import Path +from unittest import mock + +HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-qam-relay" + + +def load(): + loader = importlib.machinery.SourceFileLoader("qam_relay", str(HELPER)) + spec = importlib.util.spec_from_loader("qam_relay", loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +class QamRelayTest(unittest.TestCase): + def setUp(self): + self.relay = load() + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.relay.FLAG = str(self.tmp / "flag") + self.relay.INTERVAL = 0.05 + + def test_pipes_bytes_both_ways_until_stopped(self): + upstream = socket.socket() + upstream.bind(("127.0.0.1", 0)) + upstream.listen(1) + self.addCleanup(upstream.close) + + def echo(): + conn, _ = upstream.accept() + with conn: + conn.sendall(b"answer:" + conn.recv(100)) + + threading.Thread(target=echo, daemon=True).start() + server = socket.socket() + server.bind(("127.0.0.1", 0)) + server.listen(1) + port = server.getsockname()[1] + Path(self.relay.FLAG).write_text("me") + serving = threading.Thread(target=self.relay.serve, args=(server, upstream.getsockname()[1], "me"), daemon=True) + serving.start() + with socket.create_connection(("127.0.0.1", port), 2) as client: + client.sendall(b"GET /json") + client.settimeout(2) + self.assertEqual(b"answer:GET /json", client.recv(100)) + with mock.patch.object(self.relay.sys, "argv", ["x", "stop"]): + self.assertEqual(0, self.relay.main()) + serving.join(2) + self.assertFalse(serving.is_alive()) + + def test_rejects_unknown_commands(self): + for argv in (["x"], ["x", "start"], ["x", "size", "1", "2"]): + with mock.patch.object(self.relay.sys, "argv", argv), mock.patch.object(self.relay.sys, "stderr"): + self.assertEqual(2, self.relay.main()) + + +if __name__ == "__main__": + unittest.main()