feat(bottom): bottom screen research, Quick Access, game art, guides and mirror panels (#3290)

* docs: bottom screen research and proposals

* docs: expand bottom screen region mirror, guides and companion API

* feat(bottom): idle home card, per-game panel memory, Steam achievements tab and screen off

* feat(bottom): quick tiles page on the dashboard

* feat(bottom): Steam guides tab with per-game reading position

* feat(bottom): companion page with Stardew, Skyrim and Fallout 4 adapters

* docs: bottom screen implementation status

* feat(bottom): mirror a region of the game picture on the bottom screen

* fix(bottom): follow Steam's selection for any game, composite while mirroring

* docs: bottom screen hardware results and screenshots

* feat(bottom): guides wiki, fixes, maps and saved pages; hide mirrored region on top

* feat(bottom): guides, mirror and companion as their own panels in the app's settings style

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

* fix(bottom): park Steam's Quick Access through its own bounds and keep it open on a lease

* feat(bottom): align Quick Access left, centre or right; keep its tab and Decky working

* fix(bottom): quieter Quick Access move handles, instant reopen, Decky tab after a cold start

* fix(bottom): lay Quick Access out at the panel's shape so every tab keeps one size

* feat(bottom): Quick Access tabs fill the bottom screen

* fix(bottom): the Quick Access button still opens the menu on the top screen

* feat(bottom): choose Quick Access layout from the bar: full width, left, center or right

* feat(bottom): brightness slider for the bottom screen with screen off at its end

* feat(bottom): game art panel, hideable bar with a pull tab, direct guide links, centred guide tabs

* fix(bottom): mirror fills the panel, options open from the bar

* docs: drop the removed dashboard row screenshot

* refactor(bottom): split the companion panel into its own change

* fix(bottom): Steam dialogs take input over the parked Quick Access menu; review fixes

* fix(bottom): extract the Quick Access relay at session start; second review round

* fix(bottom): game art refreshes details for the same game

* fix(bottom): Quick Access retries back off; art never shows another game for the running one

* fix(bottom): Quick Access keeps its lease through retry backoff

* fix(bottom): renew the Quick Access lease apart from discovery

* fix(bottom): a Quick Access panel releases only its own lease

* fix(bottom): an older Quick Access panel cannot take back a newer panel's lease

* test(bottom): an expired Quick Access lease can be taken by any panel

* fix(bottom): only the Quick Access lease owner sets the menu's shape
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-27 05:15:57 -05:00
1 parent c0506d53c9
commit 8e25301a77
101 files changed
+6595 -40

No files matched your search

@@ -344,7 +344,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var gestureGame by mutableStateOf<String?>(null)
private var gameStarts by mutableIntStateOf(0)
private var gestureSettingsOpen by mutableStateOf(false)
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
@@ -1313,6 +1313,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (nextGame != null) gameStarts++
gestureGame = nextGame
refreshGestureConfig()
restoreGamePanel(nextGame)
}
if (
SessionState.mode == SessionService.MODE_STEAM &&
@@ -2936,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))
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")
@@ -3989,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) }
}
@@ -4428,8 +4430,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (secondScreenMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) selectSecondScreenMode(secondScreenMode)
}
private fun openingPanel() = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available())
private fun openingPanel(): SecondScreenMode {
val saved = bottomGameKey()?.let { SessionPrefs.gameSecondScreenPanel(this, it) }
// A game's own panel counts as applied, so the next game without one returns to the global choice.
if (saved != null) gamePanelApplied = true
return SecondScreenMode.opening(saved ?: SessionPrefs.secondScreenPanel(this, desktopSession), SessionState.deckPad,
bottomPages().isNotEmpty(), com.droiddeck.launcher.session.BottomDesktop.available(), SessionState.mode == SessionService.MODE_STEAM)
}
private fun openingSurface() = openingPanel().takeIf { it != SecondScreenMode.MENU } ?: SecondScreenMode.KEYBOARD_TRACKPAD
@@ -4455,9 +4462,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
@@ -4575,10 +4589,36 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
typingReturnMode = null
automaticPanel = false
SessionState.bottomMenu = false
if (mode != SecondScreenMode.NONE) SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
if (mode != SecondScreenMode.NONE) {
SessionPrefs.setSecondScreenPanel(this, desktopSession, mode.id)
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 || 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)
gamePanelApplied -> openingPanel()
else -> return
}
gamePanelApplied = remembered != null
if (wanted != SecondScreenMode.MENU && wanted != secondScreenMode) selectSecondScreenMode(wanted)
}
private fun bottomScreenPicker(mode: SecondScreenMode) = com.droiddeck.launcher.ui.ScreenPicker(
com.droiddeck.launcher.ui.secondScreenModes(false, SessionState.deckPad, bottomPages().isNotEmpty(),
com.droiddeck.launcher.session.BottomDesktop.available()),
@@ -4594,6 +4634,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onKeyboardClosed = ::bottomKeyboardClosed,
onMenu = { drawerOpen = true },
picker = ::bottomScreenPicker,
panel = ::bottomPanel,
onMenuTouched = {
if (drawerPinned) {
drawerPinned = false
@@ -4630,7 +4671,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
BottomDashboard(
bottomPages(), com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
gamePage = { bottomGameKey()?.let { SessionPrefs.gameBottomPage(this@SessionActivity, it) } },
onPage = {
com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, 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 }
},
@@ -4639,11 +4684,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}),
)
private fun bottomPages(): List<BottomPage> = sessionBottomPages(BottomPageActions(
private fun bottomPages(): List<BottomPage> = sessionBottomPages(bottomActions())
private fun bottomPanel(mode: SecondScreenMode): (@androidx.compose.runtime.Composable () -> Unit)? =
if (!mode.sessionPanel) null else ({ DroidDeckTheme { com.droiddeck.launcher.ui.BottomSessionPanel(mode, bottomActions()) } })
private fun bottomActions() = BottomPageActions(
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,
)
private fun captureScreenshot(onDone: (Boolean) -> Unit) = copyGameFrame { bitmap ->
if (bitmap == null) {
@@ -4692,6 +4747,46 @@ 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 = 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) {
onFrame(null)
return
}
val r = region ?: android.graphics.RectF(0f, 0f, 1f, 1f)
val src = android.graphics.Rect((r.left * width).toInt(), (r.top * height).toInt(), (r.right * width).toInt(), (r.bottom * height).toInt())
if (src.width() <= 0 || src.height() <= 0) {
onFrame(null)
return
}
val bitmap = try {
android.graphics.Bitmap.createBitmap(outWidth, outHeight, android.graphics.Bitmap.Config.ARGB_8888)
} catch (_: OutOfMemoryError) {
onFrame(null)
return
}
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)
}
}
}
/** PixelCopy reads the last queued buffer, which black frame insertion makes black every other refresh. */
private fun withPictureFrame(copy: (done: () -> Unit) -> Unit) {
if (!CompositorHost.holdPicture()) return copy {}
@@ -4994,7 +5089,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() {
@@ -5925,7 +6023,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(true) }
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 {
@@ -5934,6 +6038,53 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionService.pause(this)
}
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
private val maskLayout = android.view.View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> placeMirrorMask() }
private fun maskGameRegion(region: android.graphics.RectF?, dim: Boolean) {
maskedRegion = region
maskDim = dim
if (region != null && mirrorMask == null && ::sessionRoot.isInitialized && ::surfaceView.isInitialized) {
val mask = android.view.View(this).apply {
isClickable = false
isFocusable = false
importantForAccessibility = android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
sessionRoot.addView(mask, sessionRoot.indexOfChild(surfaceView) + 1, FrameLayout.LayoutParams(0, 0))
surfaceView.addOnLayoutChangeListener(maskLayout)
mirrorMask = mask
}
placeMirrorMask()
}
private fun placeMirrorMask() {
val mask = mirrorMask ?: return
val r = maskedRegion
if (r == null || glassesOutputActive || bottomOutputActive || surfaceView.width <= 0) {
mask.visibility = android.view.View.GONE
return
}
mask.setBackgroundColor(if (maskDim) 0xB3000000.toInt() else android.graphics.Color.BLACK)
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 - 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(composedOutputFree())
}
private fun zeroCopyActive(): Boolean =
CompositorHost.isStarted && !SessionState.hdr && SessionPrefs.zeroCopy(this, SessionState.mode)
@@ -6651,11 +6802,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
modifier = Modifier.fillMaxWidth().weight(1f),
)
}
secondScreenMode.sessionPanel -> androidx.compose.foundation.layout.Column(Modifier.fillMaxSize()) {
com.droiddeck.launcher.ui.BottomScreenBar(bar(getString(secondScreenMode.label)))
androidx.compose.foundation.layout.Box(Modifier.fillMaxWidth().weight(1f)) {
com.droiddeck.launcher.ui.BottomSessionPanel(secondScreenMode, bottomActions())
}
}
pages.isEmpty() -> com.droiddeck.launcher.ui.BottomScreenBar(bar(null))
else -> BottomDashboard(
pages, com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
gamePage = { bottomGameKey()?.let { SessionPrefs.gameBottomPage(this@SessionActivity, it) } },
onPage = {
com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it)
bottomGameKey()?.let { game -> SessionPrefs.setGameBottomPage(this@SessionActivity, game, it) }
},
bar = bar(getString(R.string.second_mode_dashboard)),
strip = { pageId ->
com.droiddeck.launcher.ui.SessionBottomStrip(pageId) { if (::hud.isInitialized) hud.liveFps else null }
@@ -15,17 +15,24 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls, InputStockLayouts.DECK),
CUSTOM_CONTROLS("custom-controls", R.string.input_profile_controls_mode),
DASHBOARD("dashboard", R.string.second_mode_dashboard),
GUIDES("guides", R.string.bottom_page_guides),
MIRROR("mirror", R.string.bottom_page_mirror),
STEAM_QAM("steam-qam", R.string.bottom_qam_title),
ART("art", R.string.bottom_art_title),
DESKTOP("desktop", R.string.second_mode_desktop);
val sessionPanel: Boolean get() = this == GUIDES || this == MIRROR || this == STEAM_QAM || this == ART
val controls: Boolean get() = this == CUSTOM_CONTROLS || bindings != null
fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings
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 || dashboard) &&
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD && !it.sessionPanel || dashboard) && (it != STEAM_QAM && it != ART || steam) &&
(it != DESKTOP || bottomDesktop)
} ?: MENU
}
@@ -0,0 +1,63 @@
package com.droiddeck.launcher.session
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
private val tornDown = java.util.concurrent.atomic.AtomicBoolean(false)
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) {
}
close()
}
}
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()
runCatching { 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()
runCatching { sender.execute { runCatching { ws.send(text) }.onFailure { future.complete(JSONObject()) } } }
.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
if (!tornDown.compareAndSet(false, true)) return
pending.values.forEach { it.complete(JSONObject()) }
sender.shutdown()
runCatching { ws.close() }
}
}
@@ -0,0 +1,284 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
object GameLinks {
enum class Kind { WIKI, STRATEGYWIKI, PCGAMINGWIKI, GAMEFAQS, IGN, HOWLONGTOBEAT, MAPGENIE }
data class Link(val kind: Kind, val url: String)
data class Search(val id: String, val url: String)
internal fun sparql(appId: Long): String = """
SELECT ?fandom ?pcgw ?gamefaqs ?ign ?hltb ?sw WHERE {
?g wdt:P1733 "$appId".
OPTIONAL { ?g wdt:P4073 ?fandom }
OPTIONAL { ?g wdt:P6337 ?pcgw }
OPTIONAL { ?g wdt:P4769 ?gamefaqs }
OPTIONAL { ?g wdt:P5385 ?ign }
OPTIONAL { ?g wdt:P2816 ?hltb }
OPTIONAL { ?g wdt:P9075 ?sw }
} LIMIT 50
""".trimIndent()
internal fun parse(json: String): List<Link> {
val rows = JSONObject(json).optJSONObject("results")?.optJSONArray("bindings") ?: return emptyList()
val values = HashMap<String, MutableList<String>>()
for (i in 0 until rows.length()) {
val row = rows.optJSONObject(i) ?: continue
for (key in row.keys()) {
val v = row.optJSONObject(key)?.optString("value").orEmpty()
if (v.isNotEmpty() && v !in values.getOrPut(key) { mutableListOf() }) values.getValue(key) += v
}
}
fun first(key: String) = values[key]?.firstOrNull()
// Wikidata is editable by anyone, and this id becomes a URL host.
val fandomId = Regex("[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)?")
val fandom = values["fandom"]?.filter(fandomId::matches)?.let { all -> all.firstOrNull { '.' !in it } ?: all.firstOrNull() }
return listOfNotNull(
fandom?.let { id -> if ('.' in id) id.split('.', limit = 2).let { (lang, wiki) -> "https://$wiki.fandom.com/$lang/" } else "https://$id.fandom.com/" }
?.let { Link(Kind.WIKI, it) },
first("sw")?.let { Link(Kind.STRATEGYWIKI, "https://strategywiki.org/wiki/" + path(it)) },
first("pcgw")?.let { Link(Kind.PCGAMINGWIKI, "https://www.pcgamingwiki.com/wiki/" + path(it)) },
first("gamefaqs")?.takeIf { it.all(Char::isDigit) }?.let { Link(Kind.GAMEFAQS, "https://gamefaqs.gamespot.com/-/$it-") },
first("ign")?.let { Link(Kind.IGN, "https://www.ign.com/games/" + path(it)) },
first("hltb")?.takeIf { it.all(Char::isDigit) }?.let { Link(Kind.HOWLONGTOBEAT, "https://howlongtobeat.com/game/$it") },
)
}
/** Site slugs to try for a game name, longest first: "Bully: Scholarship Edition" gives bully-scholarship-edition, then bully. */
internal fun slugs(name: String): List<String> {
fun slug(s: String) = s.lowercase().replace("&", "and").replace(Regex("['’™®©]"), "")
.replace(Regex("[^a-z0-9]+"), "-").trim('-')
val short = name.split(Regex(":| - | – |\\("), limit = 2).first()
return listOf(slug(name), slug(short)).filter { it.isNotEmpty() }.distinct()
}
/** 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<Link>, exists: (String) -> Boolean, strategyWiki: (String) -> String?): List<Link> =
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<Link>, extra: List<Link>): List<Link> =
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<Link>, exists: (String) -> Boolean, strategyWiki: (String) -> String?): List<Link> {
val have = found.map { it.kind }.toSet()
val slugs = slugs(name)
fun first(urls: List<String>) = urls.firstOrNull(exists)
val ignWiki = found.firstOrNull { it.kind == Kind.IGN }?.url?.substringAfter("/games/", "")?.takeIf { it.isNotEmpty() }
val extra = listOfNotNull(
first(slugs.map { "https://mapgenie.io/$it" })?.let { Link(Kind.MAPGENIE, it) },
first((listOfNotNull(ignWiki) + slugs).distinct().map { "https://www.ign.com/wikis/$it" })?.let { Link(Kind.IGN, it) },
// Fandom answers pages with a bot check, but its API with 200 for a wiki that exists and 404 for one that does not.
if (Kind.WIKI in have) null else slugs.map { it.replace("-", "") }.distinct()
.firstOrNull { exists("https://$it.fandom.com/api.php?action=query&meta=siteinfo&format=json") }
?.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 extra
}
internal fun parseOpenSearch(json: String, title: String): String? = runCatching {
val a = JSONArray(json)
val titles = a.getJSONArray(1)
val urls = a.getJSONArray(3)
(0 until titles.length()).firstOrNull { titles.getString(it).equals(title, ignoreCase = true) }?.let { urls.getString(it) }
}.getOrNull()
/** 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.takeIf { it < 500 }?.let { it in 200..399 } } finally { c.disconnect() }
}.getOrNull()
private fun strategyWiki(title: String): Result<String?> = runCatching {
parseOpenSearch(get("https://strategywiki.org/w/api.php?action=opensearch&namespace=0&limit=5&format=json&search=" +
URLEncoder.encode(title, "UTF-8")), title)
}
fun links(context: Context, appId: Long, name: String? = null): List<Link> {
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 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) } }
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
// 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 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<Link>): String =
JSONArray(links.map { JSONObject().put("kind", it.kind.name).put("url", it.url) }).toString()
internal fun readLinks(json: String): List<Link> = JSONArray(json).let { a ->
(0 until a.length()).map { a.getJSONObject(it) }.map { Link(Kind.valueOf(it.getString("kind")), it.getString("url")) }
}
fun protonTier(appId: Long): String? = runCatching {
parseTier(get("https://www.protondb.com/api/v1/reports/summaries/$appId.json"))
}.getOrNull()
internal fun parseTier(json: String): String? =
JSONObject(json).optString("tier").takeIf { it in TIERS }
/** Searches on the sites themselves, for what has no direct page. */
fun searches(name: String, found: List<Link>): List<Search> {
val q = URLEncoder.encode(name, "UTF-8")
return listOfNotNull(
Search("youtube", "https://m.youtube.com/results?search_query=$q+walkthrough"),
Search("gamefaqs", "https://gamefaqs.gamespot.com/search?game=$q").takeIf { found.none { it.kind == Kind.GAMEFAQS } },
)
}
private fun path(id: String) = id.replace(' ', '_')
private fun get(url: String): String {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
c.readTimeout = 15_000
c.setRequestProperty("User-Agent", "DroidDeck (bottom screen guides)")
c.setRequestProperty("Accept", "application/sparql-results+json, application/json")
try {
if (c.responseCode != 200) throw java.io.IOException("HTTP ${c.responseCode}")
return c.inputStream.bufferedReader().use { it.readText() }
} finally {
c.disconnect()
}
}
val TIERS = listOf("platinum", "gold", "silver", "bronze", "borked")
private const val CACHE_MS = 7L * 24 * 3600 * 1000
private const val BROWSER = "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Mobile Safari/537.36"
}
object GuideLibrary {
data class Saved(val file: File, val title: String, val url: String)
data class PinnedMap(val file: File, val markers: List<Pair<Float, Float>>)
private fun dir(context: Context, game: String, kind: String) =
File(context.filesDir, "guides/${game.replace(Regex("[^A-Za-z0-9._-]"), "_")}/$kind")
fun savedFile(context: Context, game: String): File = dir(context, game, "saved").apply { mkdirs() }.let { File(it, "${System.currentTimeMillis()}.mht") }
fun recordSaved(file: File, title: String, url: String) {
runCatching { File(file.path.removeSuffix(".mht") + ".json").writeText(JSONObject().put("title", title).put("url", url).toString()) }
}
fun saved(context: Context, game: String): List<Saved> = dir(context, game, "saved").listFiles { f -> f.name.endsWith(".mht") && f.length() > 0 }
.orEmpty().sortedByDescending { it.lastModified() }.map { f ->
val meta = runCatching { JSONObject(File(f.path.removeSuffix(".mht") + ".json").readText()) }.getOrNull()
Saved(f, meta?.optString("title").orEmpty().ifEmpty { f.nameWithoutExtension }, meta?.optString("url").orEmpty())
}
fun isSaved(context: Context, file: File): Boolean =
file.canonicalPath.startsWith(File(context.filesDir, "guides").canonicalPath + File.separator) && file.name.endsWith(".mht")
fun delete(file: File) {
file.delete()
File(file.path.removeSuffix(".mht") + ".json").delete()
File(file.path + ".markers.json").delete()
}
fun maps(context: Context, game: String): List<PinnedMap> = dir(context, game, "maps")
.listFiles { f -> f.extension in IMAGE_TYPES.values }.orEmpty().sortedByDescending { it.lastModified() }
.map { PinnedMap(it, markers(it)) }
fun markers(map: File): List<Pair<Float, Float>> = runCatching {
val arr = JSONArray(File(map.path + ".markers.json").readText())
List(arr.length()) { i -> arr.getJSONArray(i).let { it.getDouble(0).toFloat() to it.getDouble(1).toFloat() } }
}.getOrDefault(emptyList())
fun saveMarkers(map: File, markers: List<Pair<Float, Float>>) {
runCatching { File(map.path + ".markers.json").writeText(JSONArray(markers.map { JSONArray(listOf(it.first.toDouble(), it.second.toDouble())) }).toString()) }
}
/** Follows redirects itself so the page's cookies reach only the host they were read for. */
private const val MAX_REDIRECTS = 5
private fun openMap(url: String, cookies: String?): HttpURLConnection? {
val home = URL(url).host
var target = URL(url)
repeat(MAX_REDIRECTS + 1) {
val c = target.openConnection() as HttpURLConnection
c.instanceFollowRedirects = false
c.connectTimeout = 10_000
c.readTimeout = 30_000
c.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android) DroidDeck")
if (target.host.equals(home, ignoreCase = true)) cookies?.takeIf { it.isNotEmpty() }?.let { c.setRequestProperty("Cookie", it) }
if (c.responseCode !in 300..399) return c
val next = c.getHeaderField("Location")?.let { runCatching { URL(target, it) }.getOrNull() }
c.disconnect()
if (next == null || (next.protocol != "https" && next.protocol != "http")) return null
target = next
}
return null
}
fun pin(context: Context, game: String, url: String, cookies: String?): File? = runCatching {
if (!url.startsWith("https://") && !url.startsWith("http://")) return null
val c = openMap(url, cookies) ?: return null
try {
if (c.responseCode != 200) return null
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")
// 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)
}
}
}
if (!part.renameTo(out)) return null
} finally {
part.delete()
}
out
} finally {
c.disconnect()
}
}.getOrNull()
fun clear(context: Context, game: String) {
File(context.filesDir, "guides/${game.replace(Regex("[^A-Za-z0-9._-]"), "_")}").deleteRecursively()
}
private val IMAGE_TYPES = mapOf("image/png" to "png", "image/jpeg" to "jpg", "image/webp" to "webp", "image/gif" to "gif")
private const val MAX_MAP_BYTES = 40L * 1024 * 1024
}
@@ -22,6 +22,11 @@ object GameProfileManager {
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
clear("bottom screen") { SessionPrefs.clearGameBottomScreen(context, scope) }
clear("guides") {
SteamGuides.clear(context, scope)
GuideLibrary.clear(context, scope)
}
if (failures.isNotEmpty()) {
val names = failures.joinToString { it.first }
@@ -0,0 +1,135 @@
package com.droiddeck.launcher.session
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.IOException
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
class LoopbackWebSocket(port: Int, path: String = "/", connectTimeoutMs: Int = 1_000, readTimeoutMs: Int = 0) : AutoCloseable {
private val socket = Socket()
private val out: OutputStream
private val input: DataInputStream
private val random = SecureRandom()
init {
try {
socket.connect(InetSocketAddress("127.0.0.1", port), connectTimeoutMs)
socket.soTimeout = UPGRADE_TIMEOUT_MS
socket.tcpNoDelay = true
out = socket.getOutputStream()
input = DataInputStream(socket.getInputStream().buffered())
val key = Base64.getEncoder().encodeToString(ByteArray(16).also(random::nextBytes))
out.write(("GET $path HTTP/1.1\r\nHost: 127.0.0.1:$port\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
"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.split(' ').getOrNull(1) != "101") throw IOException("upgrade refused: $status")
val headers = HashMap<String, String>()
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
}
}
@Synchronized
fun send(text: String) = frame(0x1, text.toByteArray())
fun receive(): String? {
val message = ByteArrayOutputStream()
while (true) {
val b0 = input.read().takeIf { it >= 0 } ?: return null
val b1 = input.read().takeIf { it >= 0 } ?: return null
var length = (b1 and 0x7F).toLong()
if (length == 126L) length = input.readUnsignedShort().toLong() else if (length == 127L) length = input.readLong()
if (length < 0 || length > MAX_FRAME) throw IOException("frame too large")
val mask = if (b1 and 0x80 != 0) ByteArray(4).also(input::readFully) else null
val data = ByteArray(length.toInt()).also(input::readFully)
if (mask != null) for (i in data.indices) data[i] = (data[i].toInt() xor mask[i % 4].toInt()).toByte()
when (b0 and 0x0F) {
0x8 -> {
sendClose(data.copyOf(minOf(2, data.size)))
return null
}
0x9 -> synchronized(this) { frame(0xA, data) }
0x0, 0x1, 0x2 -> {
message.write(data)
if (message.size() > MAX_FRAME) throw IOException("message too large")
if (b0 and 0x80 != 0) return message.toString(Charsets.UTF_8.name())
}
}
}
}
private fun frame(opcode: Int, payload: ByteArray) {
val mask = ByteArray(4).also(random::nextBytes)
val frame = ByteArrayOutputStream(payload.size + 14)
frame.write(0x80 or opcode)
when {
payload.size < 126 -> frame.write(0x80 or payload.size)
payload.size < 65536 -> {
frame.write(0x80 or 126)
frame.write(payload.size ushr 8)
frame.write(payload.size and 0xFF)
}
else -> {
frame.write(0x80 or 127)
for (k in 7 downTo 0) frame.write(((payload.size.toLong() ushr (8 * k)) and 0xFF).toInt())
}
}
frame.write(mask)
for (i in payload.indices) frame.write((payload[i].toInt() xor mask[i % 4].toInt()) and 0xFF)
out.write(frame.toByteArray())
out.flush()
}
private fun line(s: InputStream): String? {
val buf = ByteArrayOutputStream()
while (true) {
val b = s.read()
if (b < 0) return if (buf.size() == 0) null else buf.toString(Charsets.UTF_8.name())
if (b == '\n'.code) return buf.toString(Charsets.UTF_8.name()).trimEnd('\r')
if (buf.size() > 8192) throw IOException("header line too long")
buf.write(b)
}
}
private var closeSent = false
private fun sendClose(payload: ByteArray) {
synchronized(this) {
if (closeSent) return
closeSent = true
runCatching { frame(0x8, payload) }
}
}
override fun close() {
sendClose(ByteArray(0))
runCatching { socket.close() }
}
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()))
}
}
@@ -147,6 +147,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
"usr/local/bin/droiddeck-documents" to "usr/local/bin/droiddeck-documents",
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-qam-relay" to "usr/local/bin/droiddeck-qam-relay",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
"usr/local/bin/droiddeck-desktop-bookmarks" to "usr/local/bin/droiddeck-desktop-bookmarks",
@@ -142,6 +142,55 @@ object SessionPrefs {
private fun secondScreenPanelKey(desktop: Boolean) = if (desktop) "secondScreenPanel.desktop" else "secondScreenPanel.game"
fun gameSecondScreenPanel(context: Context, game: String): String? = prefs(context).getString("secondScreenPanel.app.$game", null)
fun setGameSecondScreenPanel(context: Context, game: String, mode: String) {
prefs(context).edit().putString("secondScreenPanel.app.$game", mode).apply()
}
fun gameBottomPage(context: Context, game: String): String? = prefs(context).getString("bottomPage.app.$game", null)
fun setGameBottomPage(context: Context, game: String, page: String) {
prefs(context).edit().putString("bottomPage.app.$game", page).apply()
}
/** The bottom screen's brightness in percent, or null to follow the system. */
fun bottomBrightness(context: Context): Int? = prefs(context).getInt("bottomBrightness", -1).takeIf { it >= 0 }
fun setBottomBrightness(context: Context, percent: Int) {
prefs(context).edit().putInt("bottomBrightness", percent).apply()
}
fun bottomAutoDim(context: Context): Boolean = prefs(context).getBoolean("bottomAutoDim", true)
fun setBottomAutoDim(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("bottomAutoDim", on).apply()
}
fun mirrorRegion(context: Context, game: String): String? = prefs(context).getString("mirrorRegion.app.$game", null)
fun setMirrorRegion(context: Context, game: String, region: String) {
prefs(context).edit().putString("mirrorRegion.app.$game", region).apply()
}
fun mirrorHide(context: Context, game: String): String = prefs(context).getString("mirrorHide.app.$game", null) ?: "off"
fun setMirrorHide(context: Context, game: String, mode: String) {
prefs(context).edit().putString("mirrorHide.app.$game", mode).apply()
}
/** How Steam's Quick Access menu sits on the bottom screen: full, left, center or right. */
fun quickAccessLayout(context: Context): String? = prefs(context).getString("bottomQamLayout", null)
fun setQuickAccessLayout(context: Context, id: String) {
prefs(context).edit().putString("bottomQamLayout", id).apply()
}
fun clearGameBottomScreen(context: Context, game: String) {
prefs(context).edit().remove("secondScreenPanel.app.$game").remove("bottomPage.app.$game").remove("mirrorRegion.app.$game")
.remove("mirrorHide.app.$game").apply()
}
/** The bottom-screen desktop takes touch as a trackpad unless the user switched it to direct touch. */
fun bottomDesktopDirectTouch(context: Context): Boolean = prefs(context).getBoolean("bottomDesktopDirectTouch", false)
@@ -0,0 +1,98 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.text.Html
import java.net.HttpURLConnection
import java.net.URL
object SteamGuides {
class Guide(val id: String, val title: String, val author: String, val summary: String, val preview: String?, val stars: Int) {
val url: String get() = "https://steamcommunity.com/sharedfiles/filedetails/?id=$id"
}
class Place(val url: String, val scroll: Float)
val TAGS = listOf("Walkthroughs", "Achievements", "Secrets", "Maps or Levels")
internal fun listUrl(appId: Long, tag: String?, language: String? = null): String =
"https://steamcommunity.com/app/$appId/guides/?browsefilter=toprated&browsesort=toprated" +
listOfNotNull(tag, language).joinToString("") { "&requiredtags%5B%5D=" + java.net.URLEncoder.encode(it, "UTF-8") }
internal fun language(locale: java.util.Locale): String {
val tag = locale.toLanguageTag()
return when {
tag.startsWith("zh-Hant") || locale.country in setOf("TW", "HK", "MO") && locale.language == "zh" -> "tchinese"
locale.language == "zh" -> "schinese"
locale.language == "pt" && locale.country == "BR" -> "brazilian"
locale.language == "es" && locale.country.isNotEmpty() && locale.country != "ES" -> "latam"
else -> LANGUAGES[locale.language] ?: "english"
}
}
fun list(appId: Long, cookies: String?, tag: String? = null, language: String? = language(java.util.Locale.getDefault())): List<Guide>? {
val found = fetch(appId, cookies, tag, language)
return if (language != null && found != null && found.isEmpty()) fetch(appId, cookies, tag, null) else found
}
private fun fetch(appId: Long, cookies: String?, tag: String?, language: String?): List<Guide>? = runCatching {
val connection = URL(listUrl(appId, tag, language)).openConnection() as HttpURLConnection
connection.connectTimeout = 10_000
connection.readTimeout = 15_000
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) DroidDeck")
cookies?.takeIf { it.isNotEmpty() }?.let { connection.setRequestProperty("Cookie", it) }
try {
if (connection.responseCode != 200) return null
parse(connection.inputStream.bufferedReader().use { it.readText() })
} finally {
connection.disconnect()
}
}.getOrNull()
internal fun parse(html: String): List<Guide> = html.split("class=\"workshopItemCollectionContainer\"").drop(1).mapNotNull { card ->
val id = ID.find(card)?.groupValues?.get(1) ?: return@mapNotNull null
val title = TITLE.find(card)?.groupValues?.get(1)?.let(::text)?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
Guide(
id, title,
AUTHOR.find(card)?.groupValues?.get(1)?.let(::text).orEmpty(),
SUMMARY.find(card)?.groupValues?.get(1)?.let(::text).orEmpty(),
PREVIEW.find(card)?.groupValues?.get(1)?.let { Html.fromHtml(it, Html.FROM_HTML_MODE_LEGACY).toString() },
STARS.find(card)?.groupValues?.get(1)?.toIntOrNull() ?: 0,
)
}.distinctBy { it.id }
fun place(context: Context, game: String): Place? {
val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
val url = prefs.getString("$game.url", null)?.takeIf(::isGuide) ?: return null
return Place(url, prefs.getFloat("$game.scroll", 0f))
}
fun savePlace(context: Context, game: String, url: String, scroll: Float) {
if (!isGuide(url)) return
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
.putString("$game.url", url).putFloat("$game.scroll", scroll.coerceIn(0f, 1f)).apply()
}
fun clear(context: Context, game: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().remove("$game.url").remove("$game.scroll").apply()
}
internal fun isGuide(url: String): Boolean = GUIDE_URL.matches(url)
private fun text(html: String): String = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY).toString().trim().replace(Regex("\\s+"), " ")
private val LANGUAGES = mapOf(
"en" to "english", "de" to "german", "fr" to "french", "it" to "italian", "es" to "spanish", "pt" to "portuguese",
"ru" to "russian", "pl" to "polish", "ja" to "japanese", "ko" to "koreana", "tr" to "turkish", "uk" to "ukrainian",
"nl" to "dutch", "sv" to "swedish", "da" to "danish", "fi" to "finnish", "nb" to "norwegian", "no" to "norwegian",
"cs" to "czech", "hu" to "hungarian", "ro" to "romanian", "bg" to "bulgarian", "el" to "greek", "th" to "thai",
"vi" to "vietnamese", "id" to "indonesian", "in" to "indonesian", "ar" to "arabic",
)
private const val PREFS = "steam_guides"
private val GUIDE_URL = Regex("https://steamcommunity\\.com/sharedfiles/filedetails/\\?id=\\d+(#[\\w-]*)?")
private val ID = Regex("""filedetails/\?id=(\d+)""")
private val TITLE = Regex("""class="workshopItemTitle">(.*?)</div>""", RegexOption.DOT_MATCHES_ALL)
private val AUTHOR = Regex("""class="workshopItemAuthorName">(.*?)</span>""", RegexOption.DOT_MATCHES_ALL)
private val SUMMARY = Regex("""class="workshopItemShortDesc">(.*?)</div>""", RegexOption.DOT_MATCHES_ALL)
private val PREVIEW = Regex("""class="workshopItemPreviewImage" src="([^"]+)"""")
private val STARS = Regex("""/(\d)-star\.png""")
}
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
object SteamLocalConfig {
class AppStats(val playtimeMinutes: Long, val lastPlayed: Long)
fun appStats(steamRoot: File, appId: Int): AppStats? {
val config = AddedGames.accountConfig(steamRoot) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
return appStats(text, appId)
}
internal fun appStats(text: String, appId: Int): AppStats? {
val apps = blocks(text, "apps").firstNotNullOfOrNull { blocks(it, appId.toString(), topLevel = true).firstOrNull() } ?: return null
val minutes = PLAYTIME.find(apps)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
val last = LAST_PLAYED.find(apps)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
return AppStats(minutes, last)
}
private fun blocks(text: String, key: String, topLevel: Boolean = false): List<String> {
val out = mutableListOf<String>()
val quoted = "\"$key\""
var depth = 0
var i = 0
while (i < text.length) {
when (val c = text[i]) {
'{' -> depth++
'}' -> depth--
'"' -> {
val end = text.indexOf('"', i + 1).takeIf { it > 0 } ?: return out
if ((!topLevel || depth == 0) && text.regionMatches(i, quoted, 0, quoted.length) && end == i + quoted.length - 1) {
val open = text.indexOfFirst(end + 1) { !it.isWhitespace() }
if (open >= 0 && text[open] == '{') {
val close = matching(text, open)
if (close > open) out += text.substring(open + 1, close)
}
}
i = end
}
else -> if (c == '/' && text.startsWith("//", i)) i = text.indexOf('\n', i).takeIf { it > 0 } ?: text.length
}
i++
}
return out
}
private fun matching(text: String, open: Int): Int {
var depth = 0
var i = open
while (i < text.length) {
when (text[i]) {
'{' -> depth++
'}' -> if (--depth == 0) return i
'"' -> i = text.indexOf('"', i + 1).takeIf { it > 0 } ?: return -1
}
i++
}
return -1
}
private inline fun String.indexOfFirst(from: Int, predicate: (Char) -> Boolean): Int {
for (i in from until length) if (predicate(this[i])) return i
return -1
}
private val PLAYTIME = Regex(""""Playtime"\s*"(\d+)"""")
private val LAST_PLAYED = Regex(""""LastPlayed"\s*"(\d+)"""")
}
@@ -0,0 +1,249 @@
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. 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
private val owners = java.util.concurrent.atomic.AtomicLong(0)
/** A new panel's lease owner: later panels get larger numbers, also across app restarts. */
fun newOwner(): Long = owners.updateAndGet { maxOf(it + 1, System.currentTimeMillis()) }
/**
* Takes or renews the lease for [owner], or releases it. A live lease held by a newer panel is never taken back by an
* older one, so a late request from a panel being torn down cannot end its replacement's lease or change its layout.
*/
internal fun leaseScript(on: Boolean, owner: Long, aspect: Float = 0f): String =
if (on) "if (!(g.__ddQamUntil > Date.now()) || !(g.__ddQamOwner > $owner)) { g.__ddQamOwner = $owner; g.__ddQamUntil = Date.now() + $LEASE_MS;" +
(if (aspect > 0f) " g.__ddQamAspect = $aspect;" else "") + " }"
else "if (g.__ddQamOwner === $owner) g.__ddQamUntil = 0;"
/** [aspect] is the panel's width over height: the menu is laid out at that shape so every tab shows at one scale. */
internal fun script(on: Boolean, aspect: Float = 0f, owner: Long = 0): String = """(() => {
const g = globalThis, QAM = 2;
const W = SteamUIStore.WindowStore.SteamUIWindows[0];
const m = W.MenuStore, c = W.m_CompositionStateStore;
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 && !g.__ddQamTop;
const width = (h) => g.__ddQamAspect > 0 ? Math.round(h * g.__ddQamAspect) : 0;
if (!c.__ddQam) {
c.__ddQam = c.ComputeOverallMinimumRequestedComposition;
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;
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");
}
}
};
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; w = width(h) || w; }
v.__ddAt = x;
v.__ddW = w;
return v.__ddQam.call(this, x, y, w, h, ...r);
};
}
if (!held()) {
const parked = !g.__ddQamTop;
g.__ddQamTop = false;
g.__ddQamPress = undefined;
if (!g.__ddQamOn) return;
g.__ddQamOn = false;
backdrop(false);
if (parked && m.m_eOpenSideMenu === QAM) m.CloseSideMenus();
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;
if (press !== g.__ddQamPress) {
g.__ddQamPress = press;
g.__ddQamTop = !g.__ddQamTop;
if (!g.__ddQamTop) { if (m.m_eOpenSideMenu === QAM) m.CloseSideMenus(); return; }
backdrop(false);
if (m.m_eOpenSideMenu !== QAM) m.OpenQuickAccessMenu(g.__ddQamTab ?? undefined);
for (const v of views()) if (v.__ddAsked?.[2] > 0) { v.__ddAt = v.__ddAsked[0]; v.__ddW = v.__ddAsked[2]; v.__ddQam.call(v, ...v.__ddAsked); }
c.EnsureCorrectComposition?.();
return;
}
if (g.__ddQamTop) {
if (m.m_eOpenSideMenu === QAM) {
if (m.m_eQuickAccessTab != null) g.__ddQamTab = m.m_eQuickAccessTab;
return;
}
g.__ddQamTop = false;
}
const decky = !!g.DeckyPluginLoader?.tabsHook?.qamBrowserViewPatch;
// Decky hooks the menu after Steam starts; the menu has to unmount for its tab to appear, so reopen on the next tick.
if (m.m_eOpenSideMenu === QAM && decky && !g.__ddQamDecky) { g.__ddQamDecky = true; m.CloseSideMenus(); return; }
if (m.m_eOpenSideMenu === 0) {
m.OpenQuickAccessMenu(g.__ddQamTab ?? undefined);
g.__ddQamDecky = decky;
c.EnsureCorrectComposition?.();
}
if (m.m_eOpenSideMenu !== QAM) return;
if (m.m_eQuickAccessTab != null) g.__ddQamTab = m.m_eQuickAccessTab;
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; v.__ddW = b.width; }
}
const a = v.__ddAsked;
if (a?.[2] > 0 && (v.__ddAt < popup.m_popup.innerWidth || (width(a[3]) && v.__ddW !== width(a[3])))) v.SetBounds(...a);
}
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);
};
${leaseScript(on, owner, aspect)}
keep();
if (held() && !g.__ddQamTimer) {
g.__ddQamTimer = setInterval(() => {
keep();
if (!held() && !g.__ddQamOn) { clearInterval(g.__ddQamTimer); g.__ddQamTimer = 0; }
}, 250);
}
return JSON.stringify([m.m_eOpenSideMenu, g.__ddQamTop ? 1 : 0]);
})()"""
/** [open] is Steam's open side menu; [top] is true while the menu is shown on the top screen. */
data class Hold(val open: Int, val top: Boolean)
fun hold(context: Context, aspect: Float, owner: Long): Hold? = eval(context, script(true, aspect, owner))?.let(::parseHold)
internal fun parseHold(text: String): Hold? = runCatching {
val a = JSONArray(text)
Hold(a.getInt(0), a.getInt(1) == 1)
}.getOrNull()
fun release(context: Context, relayPort: Int, owner: Long) {
eval(context, script(false, owner = owner))
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, 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<Int, String>? {
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)
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()
}
httpBody(s.getInputStream())
}
/** Reads one response, by its Content-Length when it has one: DevTools does not always close the connection. */
internal fun httpBody(input: java.io.InputStream): String {
val head = StringBuilder()
while (!head.endsWith("\r\n\r\n")) {
val b = input.read()
check(b >= 0 && head.length < 16_384) { "devtools answered ${head.take(80)}" }
head.append(b.toChar())
}
check(head.startsWith("HTTP/1.1 200")) { "devtools answered ${head.take(80)}" }
val length = Regex("(?im)^content-length:\\s*(\\d+)").find(head)?.groupValues?.get(1)?.toInt()
val body = if (length == null) input.readBytes() else ByteArray(length).also { buf ->
var read = 0
while (read < length) {
val n = input.read(buf, read, length - read)
check(n > 0) { "devtools closed after $read of $length bytes" }
read += n
}
}
return body.toString(Charsets.UTF_8)
}
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()
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.stores
import android.content.Context
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONObject
object SteamAchievements : StoreAchievements("steam", "Steam") {
fun game(appId: Long) = Game(source, appId.toString())
override fun request(context: Context, game: Game): Result {
val appId = game.id.toLongOrNull()?.takeIf { it in 1..4_294_967_295L } ?: return Result.Failed(Reason.NO_SERVICE)
if (!SessionState.running || SessionState.mode != SessionService.MODE_STEAM) return Result.Failed(Reason.UNREACHABLE)
val answer = AgentGuest.steamEval(context, expression(appId), EVAL_TIMEOUT_MS)
if (!answer.optBoolean("ok")) return Result.Failed(Reason.UNREACHABLE)
val value = answer.opt("value")?.takeIf { it != JSONObject.NULL }?.toString() ?: return Result.Failed(Reason.UNREACHABLE)
return parse(appId, value)
}
internal fun expression(appId: Long) = """(async () => {
const r = await SteamClient.Apps.GetMyAchievementsForApp('$appId');
return typeof r === 'string' ? r : JSON.stringify(r);
})()"""
internal fun parse(appId: Long, json: String): Result {
val root = runCatching { JSONObject(json) }.getOrNull() ?: return Result.Failed(Reason.UNREACHABLE)
if (root.optInt("result", 1) != 1) return Result.Found(emptyList())
val items = root.optJSONObject("data")?.optJSONArray("rgAchievements") ?: return Result.Found(emptyList())
val out = ArrayList<Achievement>(items.length())
for (i in 0 until items.length()) {
val a = items.optJSONObject(i) ?: continue
val id = a.optString("strID")
if (id.isEmpty()) continue
val unlocked = a.optBoolean("bAchieved")
out += Achievement(
id = id,
name = a.optString("strName").ifEmpty { id },
description = a.optString("strDescription"),
hidden = a.optBoolean("bHidden"),
unlocked = unlocked,
unlockedAt = if (unlocked) a.optLong("rtUnlocked") else 0,
icon = image(appId, a.optString("strImage")),
iconLocked = null,
)
}
return Result.Found(out)
}
private fun image(appId: Long, value: String): String? = when {
value.isEmpty() -> null
value.startsWith("https://") -> value
value.startsWith("http://") -> "https://" + value.removePrefix("http://")
else -> "https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/$appId/${value.substringAfterLast('/')}"
}
private const val EVAL_TIMEOUT_MS = 8_000L
}
@@ -95,7 +95,7 @@ abstract class StoreAchievements(val source: String, val label: String) {
private set
fun invalidate() { revision++ }
private val all: List<StoreAchievements> by lazy { listOf(GogAchievements, EpicAchievements) }
private val all: List<StoreAchievements> by lazy { listOf(GogAchievements, EpicAchievements, SteamAchievements) }
fun forSource(source: String?): StoreAchievements? = all.firstOrNull { it.source == source }
}
@@ -0,0 +1,129 @@
package com.droiddeck.launcher.ui
import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.Library
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
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. */
@Composable
internal fun ArtPanel(runningGame: () -> String?) {
val context = LocalContext.current.applicationContext
var game by remember { mutableStateOf<IdleGame?>(null) }
var playing by remember { mutableStateOf(false) }
FullScreenChrome()
LaunchedEffect(Unit) {
var games = emptyList<Library.SteamGame>()
var scanned = 0L
while (isActive) {
val running = runningGame()?.toLongOrNull()
val shown = running ?: withContext(Dispatchers.IO) { runCatching { AgentGuest.selectedSteamAppId(context) }.getOrNull() }
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.
// A running game that cannot be loaded is not stood in for by another game's art.
val loaded = withContext(Dispatchers.IO) { IdleHome.load(context, games, shown) }
?.takeIf { running == null || (it.appId.toLong() and 0xFFFFFFFFL) == running }
if (loaded != game) game = loaded
playing = running != null && running == game?.appId?.toLong()
delay(ART_POLL_MS)
}
}
Box(Modifier.fillMaxSize().background(Color.Black).testTag("bottom-art")) {
// Keyed by app id so a refreshed game keeps its pan; the fading-out scene keeps its last details.
val seen = remember { HashMap<Int, IdleGame>() }
game?.let { seen[it.appId] = it }
Crossfade(game?.appId, label = "art") { id ->
// Read from state here, so refreshed details for the same game recompose this scene.
val shown = game?.takeIf { it.appId == id } ?: seen[id]
if (shown != null) ArtScene(shown, playing)
}
}
}
@Composable
private fun ArtScene(game: IdleGame, playing: Boolean) {
val drift = rememberInfiniteTransition(label = "drift")
val t by drift.animateFloat(0f, 1f, infiniteRepeatable(tween(DRIFT_MS, easing = LinearEasing), RepeatMode.Reverse), label = "t")
val eased = t * t * (3 - 2 * t)
BoxWithConstraints(Modifier.fillMaxSize()) {
if (game.art != null) AsyncImage(
model = game.art, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize().graphicsLayer {
val scale = 1.08f + 0.14f * eased
scaleX = scale
scaleY = scale
translationX = (eased - 0.5f) * size.width * (scale - 1f)
translationY = (0.5f - eased) * size.height * (scale - 1f) * 0.5f
},
)
Box(
Modifier.fillMaxSize().background(
Brush.verticalGradient(0.55f to Color.Transparent, 1f to Color.Black.copy(alpha = 0.78f)),
),
)
Column(Modifier.align(Alignment.BottomStart).padding(28.dp).fillMaxWidth(0.6f)) {
Text(
stringResource(if (playing) R.string.bottom_art_playing else if (game.highlighted) R.string.bottom_idle_selected
else R.string.bottom_idle_recent).uppercase(),
fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.4.sp, color = Color.White.copy(alpha = 0.7f),
)
if (game.logo != null) AsyncImage(
model = game.logo, contentDescription = game.name, contentScale = ContentScale.Fit, alignment = Alignment.BottomStart,
modifier = Modifier.padding(top = 10.dp).widthIn(max = 460.dp).height(128.dp),
) else Text(
game.name, fontSize = 34.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 2,
overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 4.dp),
)
Text(idleDetails(game), fontSize = 14.sp, color = Color.White.copy(alpha = 0.75f), maxLines = 1,
modifier = Modifier.padding(top = 8.dp))
}
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.provider.Settings
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.outlined.LightMode
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** The bottom screen's own brightness, in percent. It never goes below [MIN] so the slider cannot leave the screen dark. */
internal object BottomBrightness {
const val MIN = 5
const val STEP = 5
/** The window brightness to use while the screen is on, or null to follow the system. */
fun level(context: Context): Float? = SessionPrefs.bottomBrightness(context)?.let { clamp(it) / 100f }
fun clamp(percent: Int): Int = percent.coerceIn(MIN, 100)
/** Where the slider starts: the saved level, else the system brightness as a percentage. */
fun initial(context: Context): Int = clamp(SessionPrefs.bottomBrightness(context) ?: runCatching {
Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS) * 100 / 255
}.getOrDefault(60))
/** 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. */
@Composable
internal fun BrightnessDrop(percent: Int, onChange: (Int) -> Unit, onScreenOff: () -> Unit, onDismiss: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(16.dp)
Box(
Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, indication = null, onClick = onDismiss)
.padding(top = BAR_HEIGHT, start = 12.dp, end = 12.dp),
) {
Row(
Modifier.fillMaxWidth().testTag("bottom-brightness").clip(shape).background(colors.surface).border(1.dp, pal.line, shape)
.clickable(remember { MutableInteractionSource() }, indication = null) {}
.padding(horizontal = 12.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(Icons.Outlined.LightMode, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
ValueSlider(
percent, BottomBrightness.MIN..100, BottomBrightness.STEP, true, stringResource(R.string.bottom_brightness), { "$it%" },
modifier = Modifier.weight(1f), track = 32.dp, onChange = onChange,
)
BarButton(stringResource(R.string.bottom_screen_off), Modifier.testTag("bottom-brightness-off"), vector = Icons.Filled.DarkMode,
onClick = onScreenOff)
}
}
}
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
/** Whether the bottom screen's bar is shown. Panels that need the whole screen ask for it hidden; a pull tab brings it back. */
internal object BottomChrome {
private val requests = mutableIntStateOf(0)
/** The user's choice, which wins until a panel's request changes; null follows the requests. */
private val chosen = mutableStateOf<Boolean?>(null)
val barShown: Boolean get() = chosen.value ?: (requests.intValue == 0)
fun show(shown: Boolean) {
chosen.value = shown
}
fun reset() {
chosen.value = null
}
internal fun request(on: Boolean) {
requests.intValue = (requests.intValue + if (on) 1 else -1).coerceAtLeast(0)
chosen.value = null
}
}
/** Asks for the bar hidden while this is composed, as art, a page being read or a map being viewed do. */
@Composable
internal fun FullScreenChrome() {
DisposableEffect(Unit) {
BottomChrome.request(true)
onDispose { BottomChrome.request(false) }
}
}
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() {
val description = stringResource(R.string.bottom_bar_show)
val shape = RoundedCornerShape(bottomStart = 14.dp, bottomEnd = 14.dp)
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
Box(
contentAlignment = Alignment.Center,
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) {
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))
}
}
}
@@ -68,7 +68,8 @@ internal object SessionBottomTab {
}
}
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
internal fun pageForGameStart(ids: List<String>, remembered: String? = null): String? =
remembered?.takeIf { it in ids } ?: GAME_PAGE.takeIf { it in ids }
private const val DEFAULT_PAGE = "telemetry"
private const val GAME_PAGE = "telemetry"
@@ -81,13 +82,14 @@ internal fun BottomDashboard(
onPage: (String) -> Unit,
bar: BottomBarModel? = null,
gameStarts: Int = 0,
gamePage: () -> String? = { null },
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 })?.let { current = it }
if (gameStarts != startsWhenOpened) pageForGameStart(pages.map { it.id }, gamePage())?.let { current = it }
}
val page = pages.firstOrNull { it.id == current } ?: pages.firstOrNull()
Column(Modifier.fillMaxSize().background(colors.background)) {
@@ -0,0 +1,585 @@
package com.droiddeck.launcher.ui
import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.net.Uri
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
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
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import coil.compose.AsyncImage
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.SteamAchievements
import androidx.compose.foundation.verticalScroll
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameLinks
import com.droiddeck.launcher.session.GuideLibrary
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SteamGuides
import com.droiddeck.launcher.session.SteamWebLogin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.coroutines.resume
private sealed class GuideList {
object Loading : GuideList()
object Failed : GuideList()
class Found(val guides: List<SteamGuides.Guide>) : GuideList()
}
internal enum class GuideSection(val label: Int) {
GUIDES(R.string.bottom_page_guides),
ACHIEVEMENTS(R.string.achievements_title),
WIKI(R.string.bottom_guides_wiki),
MAPS(R.string.bottom_guides_maps),
SAVED(R.string.bottom_guides_saved),
}
private val TAG_LABELS = listOf(
null to R.string.bottom_guides_tag_all,
"Walkthroughs" to R.string.bottom_guides_tag_walkthroughs,
"Achievements" to R.string.achievements_title,
"Secrets" to R.string.bottom_guides_tag_secrets,
"Maps or Levels" to R.string.bottom_guides_maps,
)
@Composable
internal fun GuidesPanel(runningGame: () -> String?) {
val context = LocalContext.current
val id = rememberShownGame(runningGame)
if (id == null) {
PanelNote(stringResource(R.string.bottom_guides_no_game))
return
}
val game = id.toString()
val scope = rememberCoroutineScope()
val host = rememberMenuHost()
val firstGame = remember { id }
var reading by remember(id) { mutableStateOf(if (id == firstGame) SteamGuides.place(context, game)?.url else null) }
var section by remember(id) { mutableStateOf(GuideSection.GUIDES) }
var tag by remember(id) { mutableStateOf<String?>(null) }
var list by remember(id) { mutableStateOf<GuideList>(GuideList.Loading) }
var cookieHeader by remember(id) { mutableStateOf<String?>(null) }
var name by remember(id) { mutableStateOf<String?>(null) }
var openMap by remember(id) { mutableStateOf<File?>(null) }
if (reading != null || openMap != null) FullScreenChrome()
var libraryRevision by remember(id) { mutableIntStateOf(0) }
var note by remember(id) { mutableStateOf<String?>(null) }
LaunchedEffect(id) {
val cookies = withContext(Dispatchers.IO) {
runCatching {
SteamWebLogin.read(LinuxRuntime.rootDir(context), SessionState.steamClientArch, File(context.cacheDir, "steam-web-login"))
}.getOrDefault(emptyList())
}
val manager = CookieManager.getInstance()
for (c in cookies) suspendCancellableCoroutine { cont -> manager.setCookie("https://${c.host}", c.header) { cont.resume(Unit) } }
cookieHeader = cookies.filter { steamChatAllows(it.host) }.joinToString("; ") { it.header.substringBefore(';') }
name = withContext(Dispatchers.IO) { IdleHome.overview(context, id)?.name }
}
LaunchedEffect(id, tag, cookieHeader) {
val header = cookieHeader ?: return@LaunchedEffect
list = GuideList.Loading
list = withContext(Dispatchers.IO) { SteamGuides.list(id, header, tag) }?.let { GuideList.Found(it) } ?: GuideList.Failed
}
val pinnedMsg = stringResource(R.string.bottom_guides_pinned)
val pinFailedMsg = stringResource(R.string.bottom_guides_pin_failed)
val savedMsg = stringResource(R.string.bottom_guides_saved_note)
openMap?.let { map ->
MapViewer(map, onBack = { openMap = null; libraryRevision++ }, onDelete = {
GuideLibrary.delete(map)
openMap = null
libraryRevision++
})
return
}
reading?.let { open ->
// 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++
}
},
onStopped = { reading = null },
)
}
return
}
PanelColumn {
TabStrip(GuideSection.entries.map { stringResource(it.label) }, section.ordinal, { section = GuideSection.entries[it] },
modifier = Modifier.fillMaxWidth(), compact = true, centered = true)
Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {
when (section) {
GuideSection.GUIDES -> GuidesSection(host, list, tag, SteamGuides.place(context, game), onTag = { tag = it }, onOpen = { reading = it })
GuideSection.ACHIEVEMENTS -> AchievementsSection(id)
GuideSection.WIKI -> WikiSection(id, name, onOpen = { reading = it })
GuideSection.MAPS -> MapsSection(id, game, name, libraryRevision, onOpenMap = { openMap = it }, onOpen = { reading = it })
GuideSection.SAVED -> SavedSection(game, libraryRevision, onOpen = { reading = Uri.fromFile(it).toString() }, onDelete = {
GuideLibrary.delete(it)
libraryRevision++
})
}
}
}
}
@Composable
private fun GuidesSection(
host: MenuHost, list: GuideList, tag: String?, last: SteamGuides.Place?, onTag: (String?) -> Unit, onOpen: (String) -> Unit,
) {
SettingsGroup(stringResource(R.string.bottom_guides_steam)) {
if (last != null) PanelRow(stringResource(R.string.bottom_guides_continue), onClick = { onOpen(last.url) }, tag = "bottom-guides-continue",
trailing = { SecondaryButton(stringResource(R.string.store_open), compact = true) { onOpen(last.url) } })
ChoiceRow(host, "guides-tag", stringResource(R.string.bottom_guides_category), null,
TAG_LABELS.map { (value, label) -> value to stringResource(label) }, tag) { onTag(it) }
when (list) {
GuideList.Loading -> PanelRow(stringResource(R.string.achievements_reading))
GuideList.Failed -> PanelRow(stringResource(R.string.bottom_guides_failed))
is GuideList.Found ->
if (list.guides.isEmpty()) PanelRow(stringResource(R.string.bottom_guides_empty))
else for (guide in list.guides) GuideRow(guide) { onOpen(guide.url) }
}
}
}
@Composable
private fun AchievementsSection(appId: Long) {
val game = remember(appId) { SteamAchievements.game(appId) }
val state = rememberAchievements(game) ?: return
Box(Modifier.padding(top = 8.dp)) { AchievementsTab(SteamAchievements.label, state) }
}
@Composable
private fun WikiSection(appId: Long, name: String?, onOpen: (String) -> Unit) {
val context = LocalContext.current
var links by remember(appId) { mutableStateOf<List<GameLinks.Link>?>(null) }
var tier by remember(appId) { mutableStateOf<String?>(null) }
LaunchedEffect(appId, name) {
val (found, t) = withContext(Dispatchers.IO) {
val pending = async { GameLinks.protonTier(appId) }
GameLinks.links(context, appId, name) to pending.await()
}
tier = t
links = found
}
val open = stringResource(R.string.store_open)
val found = links
if (found == null) {
SettingsGroup(stringResource(R.string.bottom_guides_wiki)) { PanelRow(stringResource(R.string.achievements_reading)) }
return
}
tier?.let { t ->
SettingsGroup(stringResource(R.string.fex_compatibility_label)) {
PanelRow(stringResource(R.string.bottom_guides_protondb), tag = "guides-protondb", onClick = { onOpen("https://www.protondb.com/app/$appId") },
trailing = { PanelValue(stringResource(tierLabel(t)), tierColor(t)) })
}
}
SettingsGroup(stringResource(R.string.bottom_guides_wiki)) {
for (link in found.filter { it.kind != GameLinks.Kind.MAPGENIE }) PanelRow(stringResource(linkLabel(link.kind)), Uri.parse(link.url).host.orEmpty().removePrefix("www."),
onClick = { onOpen(link.url) },
trailing = { SecondaryButton(open, compact = true, modifier = Modifier.testTag("guides-link-${link.kind.name.lowercase()}")) { onOpen(link.url) } })
}
name?.let { n ->
SettingsGroup(stringResource(R.string.bottom_guides_search)) {
for (s in GameLinks.searches(n, found)) PanelRow(stringResource(searchLabel(s.id)), n, onClick = { onOpen(s.url) },
trailing = { SecondaryButton(open, compact = true, modifier = Modifier.testTag("guides-search-${s.id}")) { onOpen(s.url) } })
}
}
}
@Composable
private fun MapsSection(appId: Long, game: String, name: String?, revision: Int, onOpenMap: (File) -> Unit, onOpen: (String) -> Unit) {
val context = LocalContext.current
var maps by remember(game) { mutableStateOf<List<GuideLibrary.PinnedMap>>(emptyList()) }
LaunchedEffect(game, revision) { maps = withContext(Dispatchers.IO) { GuideLibrary.maps(context, game) } }
SettingsGroup(stringResource(R.string.bottom_guides_maps)) {
if (maps.isEmpty()) PanelRow(stringResource(R.string.bottom_guides_maps_empty), stringResource(R.string.bottom_guides_pin_hint))
maps.forEachIndexed { i, map ->
PanelRow(
stringResource(R.string.bottom_guides_map_name, i + 1), stringResource(R.string.bottom_guides_markers, map.markers.size),
tag = "guides-map", onClick = { onOpenMap(map.file) },
leading = {
AsyncImage(model = map.file, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.size(64.dp, 40.dp).clip(RoundedCornerShape(6.dp)))
},
)
}
}
var mapSite by remember(name) { mutableStateOf<GameLinks.Link?>(null) }
LaunchedEffect(name) {
if (name != null) mapSite = withContext(Dispatchers.IO) { GameLinks.links(context, appId, name) }.firstOrNull { it.kind == GameLinks.Kind.MAPGENIE }
}
mapSite?.let { link ->
val open = stringResource(R.string.store_open)
SettingsGroup(stringResource(R.string.bottom_guides_find_maps)) {
PanelRow(stringResource(R.string.bottom_guides_search_mapgenie), Uri.parse(link.url).run { host.orEmpty() + path.orEmpty() },
onClick = { onOpen(link.url) },
trailing = { SecondaryButton(open, compact = true, modifier = Modifier.testTag("guides-maps-mapgenie")) { onOpen(link.url) } })
}
}
}
@Composable
private fun SavedSection(game: String, revision: Int, onOpen: (File) -> Unit, onDelete: (File) -> Unit) {
val context = LocalContext.current
var saved by remember(game) { mutableStateOf<List<GuideLibrary.Saved>>(emptyList()) }
LaunchedEffect(game, revision) { saved = withContext(Dispatchers.IO) { GuideLibrary.saved(context, game) } }
val delete = stringResource(R.string.common_delete)
SettingsGroup(stringResource(R.string.bottom_guides_saved)) {
if (saved.isEmpty()) PanelRow(stringResource(R.string.bottom_guides_saved_empty), stringResource(R.string.bottom_guides_saved_hint))
for (page in saved) PanelRow(page.title, Uri.parse(page.url).host.orEmpty().removePrefix("www."), tag = "guides-saved",
onClick = { onOpen(page.file) },
trailing = { SecondaryButton(delete, compact = true, modifier = Modifier.testTag("guides-saved-delete")) { onDelete(page.file) } })
}
}
@Composable
private fun GuideReaderPanel(
url: String,
scroll: Float,
note: String?,
onBack: () -> Unit,
onPlace: (String, Float) -> Unit,
onSave: (WebView) -> Unit,
onPin: (String) -> Unit,
onStopped: () -> Unit,
) {
val pal = LocalPalette.current
var view by remember { mutableStateOf<WebView?>(null) }
var image by remember(url) { mutableStateOf<String?>(null) }
val local = url.startsWith("file:")
PanelColumn {
Row(Modifier.fillMaxWidth().padding(bottom = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
Text(note ?: stringResource(R.string.bottom_guides_pin_hint), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
image?.let { img -> SecondaryButton(stringResource(R.string.bottom_guides_pin), compact = true, modifier = Modifier.testTag("bottom-guides-pin")) { onPin(img); image = null } }
if (!local) SecondaryButton(stringResource(R.string.game_env_save), compact = true, modifier = Modifier.testTag("bottom-guides-save")) { view?.let(onSave) }
}
Box(Modifier.weight(1f).fillMaxWidth().padding(bottom = 6.dp).clip(RoundedCornerShape(14.dp)).border(1.dp, pal.line, RoundedCornerShape(14.dp))) {
GuideReader(url, scroll, onPlace, onStopped, onView = { view = it }, onImage = { image = it })
}
}
}
@Composable
internal fun GuideRow(guide: SteamGuides.Guide, onOpen: () -> Unit) {
val pal = LocalPalette.current
PanelRow(
guide.title,
listOfNotNull(guide.author.takeIf { it.isNotEmpty() }, "★".repeat(guide.stars).takeIf { it.isNotEmpty() }).joinToString(" · "),
tag = "guide-${guide.id}", onClick = onOpen,
leading = {
Box(Modifier.size(40.dp).clip(RoundedCornerShape(6.dp)).background(pal.line)) {
if (guide.preview != null) AsyncImage(model = guide.preview, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
}
},
)
}
internal object ReaderAds {
private val HOSTS = setOf(
"doubleclick.net", "googlesyndication.com", "googleadservices.com", "adservice.google.com", "google-analytics.com",
"googletagservices.com", "googletagmanager.com", "amazon-adsystem.com", "adnxs.com", "criteo.com", "criteo.net",
"taboola.com", "outbrain.com", "pubmatic.com", "rubiconproject.com", "casalemedia.com", "openx.net", "moatads.com",
"scorecardresearch.com", "quantserve.com", "adsafeprotected.com", "3lift.com", "sharethrough.com", "teads.tv",
"yieldmo.com", "media.net", "smartadserver.com", "adform.net", "bidswitch.net", "lijit.com", "sonobi.com",
"indexww.com", "gumgum.com", "nativo.com", "zemanta.com", "primis.tech", "connatix.com", "playwire.com",
"fandomadtags.com", "kargo.com", "33across.com", "onetag-sys.com", "adsrvr.org", "id5-sync.com", "ezoic.net",
"ezojs.com", "mediavine.com", "intergient.com", "nitropay.com", "freestar.io", "pbxai.com",
)
fun blocks(host: String?): Boolean {
var h = host?.lowercase() ?: return false
while (true) {
if (h in HOSTS) return true
val dot = h.indexOf('.')
if (dot < 0 || h.indexOf('.', dot + 1) < 0) return false
h = h.substring(dot + 1)
}
}
}
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
if (steamChatAllows(host) || userInitiated) return true
val home = Uri.parse(start).host?.let(::siteOf) ?: return false
return siteOf(host) == home
}
private fun siteOf(host: String): String = host.split('.').takeLast(2).joinToString(".")
@SuppressLint("SetJavaScriptEnabled")
@Composable
private fun GuideReader(
url: String, scroll: Float, onPlace: (String, Float) -> Unit, onStopped: () -> Unit,
onView: (WebView?) -> Unit, onImage: (String) -> Unit,
) {
val context = LocalContext.current
AndroidView(factory = { ctx ->
WebView(ctx).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
isFocusable = false
isFocusableInTouchMode = false
setBackgroundColor(0xFF1B2838.toInt())
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
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 {
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)))
else null
override fun onPageFinished(view: WebView, url: String) {
if (restore > 0f) {
val ratio = restore
restore = 0f
view.postDelayed({ view.scrollTo(0, (view.contentHeight * view.scale * ratio).toInt()) }, 400)
}
}
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
onStopped()
return true
}
}
setOnLongClickListener { v ->
val hit = (v as WebView).hitTestResult
val src = hit.extra
if ((hit.type == WebView.HitTestResult.IMAGE_TYPE || hit.type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) &&
src != null && src.startsWith("http")) {
onImage(src)
true
} else false
}
setOnScrollChangeListener { v, _, y, _, _ ->
val web = v as WebView
val height = web.contentHeight * web.scale
val current = web.url ?: return@setOnScrollChangeListener
if (height > 0) onPlace(current, y / height)
}
onView(this)
loadUrl(url)
}
}, modifier = Modifier.fillMaxSize(), onRelease = { view ->
view.url?.let { current -> onPlace(current, view.scrollY / (view.contentHeight * view.scale).coerceAtLeast(1f)) }
onView(null)
view.destroy()
})
}
@Composable
private fun MapViewer(file: File, onBack: () -> Unit, onDelete: () -> Unit) {
var image by remember(file) { mutableStateOf<ImageBitmap?>(null) }
var markers by remember(file) { mutableStateOf(GuideLibrary.markers(file)) }
var scale by remember(file) { mutableFloatStateOf(1f) }
var offset by remember(file) { mutableStateOf(Offset.Zero) }
LaunchedEffect(file) { image = withContext(Dispatchers.IO) { decodeMap(file) } }
val pal = LocalPalette.current
PanelColumn {
Row(Modifier.fillMaxWidth().padding(bottom = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
BackLink(stringResource(R.string.mode_back), compact = true, onClick = onBack)
Text(stringResource(R.string.bottom_guides_marker_hint), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis)
SecondaryButton(stringResource(R.string.common_delete), compact = true, modifier = Modifier.testTag("guides-map-delete"), onClick = onDelete)
}
Box(
Modifier.weight(1f).fillMaxWidth().padding(bottom = 6.dp).clip(RoundedCornerShape(14.dp)).background(Color.Black)
.border(1.dp, pal.line, RoundedCornerShape(14.dp))
.pointerInput(file) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(1f, MAX_ZOOM)
offset = if (scale == 1f) Offset.Zero else offset + pan
}
},
contentAlignment = Alignment.Center,
) {
val img = image ?: return@Box
Box(
Modifier.aspectRatio(img.width.toFloat() / img.height)
.graphicsLayer(scaleX = scale, scaleY = scale, translationX = offset.x, translationY = offset.y)
.pointerInput(file) {
detectTapGestures(
onDoubleTap = { p ->
if (scale > 1f) {
scale = 1f
offset = Offset.Zero
} else {
scale = DOUBLE_TAP_ZOOM
offset = Offset((size.width / 2f - p.x) * DOUBLE_TAP_ZOOM, (size.height / 2f - p.y) * DOUBLE_TAP_ZOOM)
}
},
onLongPress = { p ->
markers = markers + (p.x / size.width to p.y / size.height)
GuideLibrary.saveMarkers(file, markers)
},
onTap = { p ->
val hit = markers.minByOrNull { (x, y) -> MapMarkers.distance(x * size.width, y * size.height, p.x, p.y) }
if (hit != null && MapMarkers.distance(hit.first * size.width, hit.second * size.height, p.x, p.y) < MARKER_HIT_PX * density / scale) {
markers = markers - hit
GuideLibrary.saveMarkers(file, markers)
}
},
)
},
) {
Image(img, null, Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds)
Canvas(Modifier.fillMaxSize()) {
for ((x, y) in markers) {
val c = Offset(x * size.width, y * size.height)
drawCircle(Color.Black.copy(alpha = 0.6f), radius = 9.dp.toPx() / scale, center = c)
drawCircle(pal.signal, radius = 6.dp.toPx() / scale, center = c)
}
}
}
}
}
}
internal object MapMarkers {
fun distance(x0: Float, y0: Float, x1: Float, y1: Float): Float = kotlin.math.hypot(x0 - x1, y0 - y1)
fun sampleSize(width: Int, height: Int, longest: Int): Int {
var sample = 1
while (maxOf(width, height) / sample > longest) sample *= 2
return sample
}
}
private fun decodeMap(file: File): ImageBitmap? = runCatching {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.path, bounds)
val opts = BitmapFactory.Options().apply { inSampleSize = MapMarkers.sampleSize(bounds.outWidth, bounds.outHeight, MAP_LONGEST) }
BitmapFactory.decodeFile(file.path, opts)?.asImageBitmap()
}.getOrNull()
private const val MAX_ZOOM = 8f
private const val DOUBLE_TAP_ZOOM = 2.5f
private const val MARKER_HIT_PX = 20f
private const val MAP_LONGEST = 4096
private fun linkLabel(kind: GameLinks.Kind): Int = when (kind) {
GameLinks.Kind.WIKI -> R.string.bottom_guides_link_wiki
GameLinks.Kind.STRATEGYWIKI -> R.string.bottom_guides_link_strategywiki
GameLinks.Kind.PCGAMINGWIKI -> R.string.bottom_guides_link_pcgw
GameLinks.Kind.GAMEFAQS -> R.string.bottom_guides_link_gamefaqs
GameLinks.Kind.IGN -> R.string.bottom_guides_link_ign
GameLinks.Kind.HOWLONGTOBEAT -> R.string.bottom_guides_link_hltb
GameLinks.Kind.MAPGENIE -> R.string.bottom_guides_search_mapgenie
}
private fun searchLabel(id: String): Int = when (id) {
"youtube" -> R.string.bottom_guides_search_youtube
else -> R.string.bottom_guides_link_gamefaqs
}
private fun tierLabel(tier: String): Int = when (tier) {
"platinum" -> R.string.bottom_guides_tier_platinum
"gold" -> R.string.bottom_guides_tier_gold
"silver" -> R.string.bottom_guides_tier_silver
"bronze" -> R.string.bottom_guides_tier_bronze
else -> R.string.bottom_guides_tier_borked
}
private fun tierColor(tier: String): Color = when (tier) {
"platinum" -> Color(0xFFB4C7DC)
"gold" -> Color(0xFFCFB53B)
"silver" -> Color(0xFFA6A6A6)
"bronze" -> Color(0xFFCD7F32)
else -> Color(0xFFFF6B6B)
}
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.text.format.DateUtils
import androidx.compose.runtime.Composable
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamLocalConfig
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
data class IdleGame(
val appId: Int,
val name: String,
val art: File?,
val playtimeMinutes: Long,
val lastPlayed: Long,
val highlighted: Boolean,
val logo: File? = null,
)
internal object IdleHome {
fun pick(games: List<Library.SteamGame>, selected: Long?): Pair<Library.SteamGame, Boolean>? {
games.firstOrNull { selected != null && it.appId.toLong() == selected }?.let { return it to true }
return games.filter { it.lastPlayed > 0 }.maxByOrNull { it.lastPlayed }?.let { it to false }
}
class Overview(val name: String, val minutes: Long, val lastPlayed: Long)
fun overviewExpression(appId: Long): String = "(() => { const o = globalThis.appStore?.GetAppOverviewByAppID?.($appId); " +
"return o ? JSON.stringify({name: o.display_name, minutes: o.minutes_playtime_forever, last: o.rt_last_time_played}) : null; })()"
fun parseOverview(json: String?): Overview? = runCatching {
val o = org.json.JSONObject(json ?: return null)
Overview(o.optString("name").ifEmpty { return null }, o.optLong("minutes"), o.optLong("last"))
}.getOrNull()
internal fun overview(context: Context, appId: Long): Overview? = runCatching {
val answer = AgentGuest.steamEval(context, overviewExpression(appId), 4_000)
if (!answer.optBoolean("ok")) null else parseOverview(answer.opt("value")?.takeIf { it != org.json.JSONObject.NULL }?.toString())
}.getOrNull()
fun load(context: Context, games: List<Library.SteamGame>, selected: Long?): IdleGame? {
if (selected != null) overview(context, selected)?.let { o ->
val id = selected.toInt()
val known = games.firstOrNull { it.appId == id }
val cache = File(SessionPrefs.activeSteamRoot(context), "appcache/librarycache")
val art = known?.let { it.hero ?: it.art } ?: runCatching {
Library.steamCacheImage(cache, id, listOf("library_hero.jpg", "library_600x900.jpg", "header.jpg"))
}.getOrNull()
val logo = known?.logo ?: runCatching { Library.steamCacheImage(cache, id, Library.STEAM_LOGOS) }.getOrNull()
return IdleGame(id, o.name, art, o.minutes, o.lastPlayed, highlighted = true, logo = logo)
}
val (game, highlighted) = pick(games, selected) ?: return null
val stats = runCatching { SteamLocalConfig.appStats(SessionPrefs.activeSteamRoot(context), game.appId) }.getOrNull()
return IdleGame(
game.appId, game.name, game.hero ?: game.art, stats?.playtimeMinutes ?: 0L,
maxOf(stats?.lastPlayed ?: 0L, game.lastPlayed), highlighted, game.logo,
)
}
}
private const val SELECTION_MS = 2_000L
@Composable
internal fun rememberShownGame(runningGame: () -> String?): Long? {
val context = LocalContext.current
var appId by remember { mutableStateOf(runningGame()?.toLongOrNull()) }
LaunchedEffect(Unit) {
while (isActive) {
appId = runningGame()?.toLongOrNull()
?: withContext(Dispatchers.IO) { runCatching { AgentGuest.selectedSteamAppId(context) }.getOrNull() }
delay(SELECTION_MS)
}
}
return appId
}
@Composable
internal fun idleDetails(game: IdleGame): String {
val hours = game.playtimeMinutes / 60
val played = when {
game.playtimeMinutes <= 0 -> stringResource(R.string.bottom_idle_never)
hours == 0L -> stringResource(R.string.bottom_idle_minutes, game.playtimeMinutes.toInt())
else -> stringResource(R.string.bottom_idle_hours, hours.toInt())
}
if (game.lastPlayed <= 0) return played
val last = DateUtils.getRelativeTimeSpanString(game.lastPlayed * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS)
return stringResource(R.string.bottom_idle_details, played, last)
}
@@ -0,0 +1,285 @@
package com.droiddeck.launcher.ui
import android.graphics.Bitmap
import android.graphics.RectF
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
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
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.coroutines.resume
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.suspendCancellableCoroutine
internal enum class MirrorHide(val id: String, val label: Int) {
OFF("off", R.string.bottom_mirror_hide_off),
BLACK("black", R.string.bottom_mirror_hide_black),
DIM("dim", R.string.bottom_mirror_hide_dim);
fun next(): MirrorHide = entries[(ordinal + 1) % entries.size]
companion object {
fun from(id: String?): MirrorHide = entries.firstOrNull { it.id == id } ?: OFF
}
}
internal object MirrorRegion {
const val MIN_SIZE = 0.02f
fun parse(text: String?): RectF? {
val v = text?.split(',')?.mapNotNull { it.trim().toFloatOrNull() }?.takeIf { it.size == 4 } ?: return null
return normalize(v[0], v[1], v[2], v[3])
}
fun format(r: RectF): String = listOf(r.left, r.top, r.right, r.bottom).joinToString(",") { it.toString() }
fun normalize(x0: Float, y0: Float, x1: Float, y1: Float): RectF? {
val r = RectF(min(x0, x1).coerceIn(0f, 1f), min(y0, y1).coerceIn(0f, 1f), max(x0, x1).coerceIn(0f, 1f), max(y0, y1).coerceIn(0f, 1f))
return r.takeIf { it.width() >= MIN_SIZE && it.height() >= MIN_SIZE }
}
fun outputSize(r: RectF, sourceAspect: Float, longest: Int): Pair<Int, Int> {
val w = r.width() * sourceAspect
val h = r.height()
return if (w >= h) longest to max(1, (longest * h / w).roundToInt()) else max(1, (longest * w / h).roundToInt()) to longest
}
}
private const val FRAME_MS = 66L
private const val COMPOSED_SETTLE_MS = 250L
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
internal fun MirrorPanel(actions: BottomPageActions) {
val context = LocalContext.current
val copy = actions.copyRegion
if (copy == null) {
MirrorNote(stringResource(R.string.bottom_mirror_no_frame))
return
}
DisposableEffect(Unit) {
actions.holdComposed(true)
onDispose { actions.holdComposed(false) }
}
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) {
// 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
var hide by remember(game) { mutableStateOf(MirrorHide.from(SessionPrefs.mirrorHide(context, game))) }
DisposableEffect(r, hide) {
actions.maskRegion(r.takeIf { hide != MirrorHide.OFF }, hide == MirrorHide.DIM)
onDispose { actions.maskRegion(null, false) }
}
var frame by remember(r) { mutableStateOf<ImageBitmap?>(null) }
var failed by remember(r) { mutableStateOf(false) }
LaunchedEffect(r) {
while (isActive) {
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()
delay(FRAME_MS)
}
}
val pal = LocalPalette.current
DisposableEffect(Unit) { onDispose { MirrorOptions.open.value = false } }
Box(Modifier.fillMaxSize().background(Color.Black), contentAlignment = Alignment.Center) {
val f = frame
if (f != null) Image(f, null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit,
filterQuality = if (sharp) FilterQuality.None else FilterQuality.Medium)
else if (failed) MirrorNote(stringResource(R.string.bottom_mirror_no_frame))
if (MirrorOptions.open.value) Box(
Modifier.fillMaxSize().clickable(remember { MutableInteractionSource() }, indication = null) { MirrorOptions.open.value = false },
contentAlignment = Alignment.TopEnd,
) {
val shape = RoundedCornerShape(16.dp)
Column(
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),
) {
SettingsGroup(stringResource(R.string.bottom_page_mirror)) {
ActionRow(stringResource(R.string.bottom_mirror_region), null, stringResource(R.string.game_env_edit),
onClick = { MirrorOptions.open.value = false; editing = true },
modifier = Modifier.testTag("bottom-mirror-edit"))
ChoiceRow(host, "mirror-hide", stringResource(R.string.bottom_mirror_top), null,
MirrorHide.entries.map { it to stringResource(it.label) }, hide) {
hide = it
SessionPrefs.setMirrorHide(context, game, it.id)
}
ChoiceRow(host, "mirror-scaling", stringResource(R.string.bottom_mirror_scaling), null,
listOf(true to stringResource(R.string.bottom_mirror_sharp), false to stringResource(R.string.bottom_mirror_smooth)), sharp) {
sharp = it
}
}
}
}
}
}
/** Whether the mirror's options card is open, toggled from the bar so the mirror keeps the whole panel. */
internal object MirrorOptions {
val open = androidx.compose.runtime.mutableStateOf(false)
}
@Composable
private fun MirrorEditor(
copy: (RectF?, Int, Int, (Bitmap?) -> Unit) -> Unit,
current: RectF?,
sourceAspect: Float,
onSave: (RectF) -> Unit,
onCancel: (() -> Unit)?,
) {
val pal = LocalPalette.current
var still by remember { mutableStateOf<ImageBitmap?>(null) }
var failed by remember { mutableStateOf(false) }
var start by remember { mutableStateOf<Offset?>(null) }
var end by remember { mutableStateOf<Offset?>(null) }
var picked by remember { mutableStateOf(current) }
var attempt by remember { mutableIntStateOf(0) }
LaunchedEffect(attempt) {
delay(COMPOSED_SETTLE_MS)
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()
}
PanelColumn {
Row(Modifier.fillMaxWidth().padding(bottom = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
onCancel?.let { BackLink(stringResource(R.string.common_cancel), compact = true, onClick = it) }
Text(stringResource(R.string.bottom_mirror_pick), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
SecondaryButton(stringResource(R.string.bottom_mirror_save), enabled = picked != null, compact = true,
modifier = Modifier.testTag("bottom-mirror-save")) { picked?.let(onSave) }
}
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth().padding(bottom = 6.dp), contentAlignment = Alignment.Center) {
val image = still
if (image == null) {
if (failed) Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(stringResource(R.string.bottom_mirror_no_frame), fontSize = 15.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center, modifier = Modifier.padding(24.dp))
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))) {
Image(image, null, Modifier.fillMaxSize(), contentScale = ContentScale.FillBounds)
Canvas(Modifier.fillMaxSize().pointerInput(Unit) {
detectDragGestures(
onDragStart = { start = it; end = it },
onDrag = { change, _ -> end = change.position },
onDragEnd = {
val a = start
val b = end
if (a != null && b != null) MirrorRegion.normalize(a.x / size.width, a.y / size.height, b.x / size.width, b.y / size.height)
?.let { picked = it }
start = null
end = null
},
)
}) {
val a = start
val b = end
val shown = if (a != null && b != null) RectF(min(a.x, b.x), min(a.y, b.y), max(a.x, b.x), max(a.y, b.y))
else picked?.let { RectF(it.left * size.width, it.top * size.height, it.right * size.width, it.bottom * size.height) }
if (shown != null) {
val veil = Color.Black.copy(alpha = 0.5f)
drawRect(veil, Offset.Zero, Size(size.width, shown.top))
drawRect(veil, Offset(0f, shown.bottom), Size(size.width, size.height - shown.bottom))
drawRect(veil, Offset(0f, shown.top), Size(shown.left, shown.height()))
drawRect(veil, Offset(shown.right, shown.top), Size(size.width - shown.right, shown.height()))
drawRect(pal.signal, Offset(shown.left, shown.top), Size(shown.width(), shown.height()), style = Stroke(3.dp.toPx()))
}
}
}
}
}
}
@Composable
private fun MirrorNote(text: String) {
Box(Modifier.fillMaxSize()) {
Text(text, fontSize = 15.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center,
modifier = Modifier.align(Alignment.Center).padding(24.dp))
}
}
private suspend fun capture(copy: (RectF?, Int, Int, (Bitmap?) -> Unit) -> Unit, region: RectF?, width: Int, height: Int): Bitmap? =
suspendCancellableCoroutine { cont -> copy(region, width, height) { if (cont.isActive) cont.resume(it) else it?.recycle() } }
@@ -27,6 +27,11 @@ class BottomPageActions(
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
val fps: () -> Float? = { null },
val runningGame: () -> String? = { 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 = { _, _ -> },
)
internal const val BOTTOM_PAGE_TELEMETRY = "telemetry"
@@ -25,6 +25,11 @@ import androidx.compose.foundation.shape.RoundedCornerShape
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.Wallpaper
import androidx.compose.material.icons.outlined.CropFree
import androidx.compose.material.icons.outlined.MenuBook
import androidx.compose.material.icons.outlined.DesktopAccessDisabled
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.ExpandLess
@@ -236,6 +241,10 @@ internal val SecondScreenMode.icon: ImageVector get() = when (this) {
SecondScreenMode.DECK_CONTROLS -> Icons.Outlined.SportsEsports
SecondScreenMode.CUSTOM_CONTROLS -> Icons.Outlined.Tune
SecondScreenMode.DASHBOARD -> Icons.Outlined.Dashboard
SecondScreenMode.GUIDES -> Icons.Outlined.MenuBook
SecondScreenMode.MIRROR -> Icons.Outlined.CropFree
SecondScreenMode.STEAM_QAM -> Icons.Outlined.ViewSidebar
SecondScreenMode.ART -> Icons.Outlined.Wallpaper
SecondScreenMode.DESKTOP -> Icons.Outlined.DesktopWindows
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.input.SecondScreenMode
@Composable
internal fun BottomSessionPanel(mode: SecondScreenMode, actions: BottomPageActions) {
val colors = MaterialTheme.colorScheme
Box(Modifier.fillMaxSize().background(colors.background)) {
CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) {
when (mode) {
SecondScreenMode.GUIDES -> GuidesPanel(actions.runningGame)
SecondScreenMode.MIRROR -> MirrorPanel(actions)
SecondScreenMode.STEAM_QAM -> SteamQamPanel()
SecondScreenMode.ART -> ArtPanel(actions.runningGame)
else -> Unit
}
}
}
}
@Composable
internal fun PanelColumn(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
Column(modifier.fillMaxSize().padding(horizontal = 14.dp, vertical = 6.dp), verticalArrangement = Arrangement.spacedBy(2.dp), content = content)
}
@Composable
internal fun PanelRow(
title: String,
hint: String? = null,
tag: String? = null,
selected: Boolean = false,
leading: (@Composable () -> Unit)? = null,
trailing: (@Composable () -> Unit)? = null,
onClick: (() -> Unit)? = null,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
Modifier.fillMaxWidth()
.background(if (selected) pal.signal.copy(alpha = 0.10f) else Color.Transparent)
.then(if (onClick != null) Modifier.clickable(role = Role.Button, onClick = onClick) else Modifier)
.then(if (tag != null) Modifier.testTag(tag) else Modifier)
.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
leading?.invoke()
Column(Modifier.weight(1f)) {
Text(title, fontSize = 13.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold,
color = if (selected) pal.signal else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!hint.isNullOrEmpty()) Text(hint, fontSize = 11.sp, lineHeight = 14.sp, color = colors.onSurfaceVariant,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(top = 2.dp))
}
trailing?.invoke()
}
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
internal fun PanelValue(text: String, color: Color = MaterialTheme.colorScheme.onBackground) {
Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = color, maxLines = 1)
}
@Composable
internal fun PanelNote(text: String, modifier: Modifier = Modifier) {
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center,
modifier = Modifier.padding(24.dp))
}
}
@@ -0,0 +1,302 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.BitmapFactory
import android.util.Base64
import androidx.annotation.StringRes
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.material.icons.Icons
import androidx.compose.material.icons.outlined.AlignHorizontalCenter
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
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.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
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.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.math.min
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.json.JSONArray
import org.json.JSONObject
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)
}
/** How Steam's Quick Access menu sits on the bottom screen. */
internal enum class QamFit(val id: String, @StringRes val label: Int, val icon: ImageVector, val align: Int) {
FULL("full", R.string.bottom_qam_layout_full, Icons.Outlined.WidthFull, 0),
LEFT("left", R.string.bottom_qam_layout_left, Icons.Outlined.AlignHorizontalLeft, -1),
CENTER("center", R.string.bottom_qam_layout_center, Icons.Outlined.AlignHorizontalCenter, 0),
RIGHT("right", R.string.bottom_qam_layout_right, Icons.Outlined.AlignHorizontalRight, 1);
val next: QamFit get() = entries[(ordinal + 1) % entries.size]
companion object {
fun from(id: String?): QamFit = entries.firstOrNull { it.id == id } ?: FULL
private val state = mutableStateOf<QamFit?>(null)
fun current(context: Context): QamFit = state.value ?: from(SessionPrefs.quickAccessLayout(context)).also { state.value = it }
fun choose(context: Context, fit: QamFit) {
state.value = fit
SessionPrefs.setQuickAccessLayout(context, fit.id)
}
}
}
internal object QamLayout {
private const val WIDE_CSS = "div.BasicUI { width: 100% !important; } div[class*=\\\"tab_\\\"] { max-width: none !important; }"
/** Scale and left edge of the menu in a box; [align] -1, 0 or 1 places a narrower menu left, centred or right. */
fun fit(boxWidth: Float, boxHeight: Float, contentRight: Float, cssHeight: Float, align: Int = 0): Pair<Float, Float> {
val scale = min(boxWidth / contentRight, boxHeight / cssHeight)
return scale to (boxWidth - contentRight * scale) * (align.coerceIn(-1, 1) + 1) / 2f
}
fun toCss(x: Float, y: Float, scale: Float, left: Float): Pair<Float, Float> = (x - left) / scale to y / scale
/** Makes the menu follow the panel-shaped view (Steam sizes it once, on open) and lifts each tab's 300 px cap, then measures where the content ends. */
/** [wide] is false while the menu is shown on the top screen, where it keeps Steam's own layout. */
fun contentScript(wide: Boolean): String = "(() => { let s = document.getElementById('dd-qam-wide'); " +
"if (!s) { s = document.createElement('style'); s.id = 'dd-qam-wide'; document.head.appendChild(s); } " +
"const css = '${if (wide) WIDE_CSS else ""}'; " +
"if (s.textContent !== css) s.textContent = css; if (document.scrollingElement.scrollLeft) document.scrollingElement.scrollLeft = 0; " +
"const w = innerWidth; let right = 0; for (const e of document.body.querySelectorAll('*')) { " +
"const r = e.getBoundingClientRect(); const tab = /(^| )tab_/.test(String(e.className)); " +
"if (r.width > 0 && r.height > 0 && (tab || 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
private const val FAST_TICK_MS = 150L
private const val MAX_RETRY_MS = 4_000L
/** The last frame shown, so returning to the panel shows the menu at once while the live stream reconnects. */
private object QamCache {
@Volatile var image: ImageBitmap? = null
@Volatile var shape: FloatArray? = null
}
@Composable
internal fun SteamQamPanel() {
val context = LocalContext.current.applicationContext
var image by remember { mutableStateOf(QamCache.image) }
var shape by remember { mutableStateOf(QamCache.shape) }
var failed by remember { mutableStateOf(false) }
var slow by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
delay(2_500)
slow = true
}
val fit = QamFit.current(context)
val holder = remember { arrayOfNulls<CdpPage>(1) }
val owner = remember { SteamQam.newOwner() }
val relay = remember { intArrayOf(0) }
val live = remember { java.util.concurrent.atomic.AtomicBoolean(false) }
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) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
var misses = 0
// The lease is renewed on its own, so slow discovery or a retry backoff never lets the held menu lapse.
val renew = launch {
while (isActive) {
if (SessionState.phase == SessionPhase.READY && aspect[0] > 0f) SteamQam.hold(context, aspect[0], owner)
delay(TICK_MS)
}
}
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], owner)
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()
}
holder[0] = page
ensureActive()
page?.send("Page.enable")
val started = page?.call("Page.startScreencast", JSONObject().put("format", "jpeg").put("quality", 85)
.put("maxWidth", 1920).put("maxHeight", 1440))
if (page != null && (started == null || started.has("error") || !started.has("result"))) {
page.close()
page = null
holder[0] = null
}
}
// 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
// With no menu page to reach, retries slow down instead of starting guest processes several times a second.
misses = if (reached) 0 else misses + 1
val wait = when {
!reached -> minOf(TICK_MS shl minOf(misses - 1, 2), MAX_RETRY_MS)
live.get() -> TICK_MS
else -> FAST_TICK_MS
}
val used = QamFit.current(context)
withTimeoutOrNull(wait) {
snapshotFlow { QamFit.current(context) }.first { it != used }
}
}
} finally {
withContext(NonCancellable) {
renew.cancelAndJoin()
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], owner)
}
}
}
}
val img = image
val l = shape
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) {
Box(measure) {
if (slow) PanelNote(stringResource(if (failed) R.string.bottom_qam_unavailable else R.string.achievements_reading))
}
return
}
BoxWithConstraints(measure.background(f.fill)) {
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, fit.align)
Canvas(
Modifier.fillMaxSize().pointerInput(f.cssWidth, f.contentRight, boxW, boxH, fit) {
var touching = false
var target: CdpPage? = null
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
if (type == "touchStart") target = holder[0]
touching = type != "touchEnd"
val points = if (type == "touchEnd") JSONArray()
else JSONArray().put(JSONObject().put("x", x.toDouble()).put("y", y.toDouble()))
target?.send("Input.dispatchTouchEvent", JSONObject().put("type", type).put("touchPoints", points))
if (!touching) target = null
change.consume()
}
}
} finally {
if (touching) target?.send("Input.dispatchTouchEvent",
JSONObject().put("type", "touchCancel").put("touchPoints", JSONArray()))
}
},
) {
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,
)
}
}
}
private fun decodeFrame(data: String): ImageBitmap? = runCatching {
val bytes = Base64.decode(data, Base64.DEFAULT)
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.asImageBitmap()
}.getOrNull()
@@ -15,6 +15,10 @@ import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ExpandLess
import androidx.compose.material.icons.outlined.LightMode
import androidx.compose.material.icons.outlined.Tune
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
@@ -43,6 +47,7 @@ class SecondScreenPresentation(
private val onMenuTouched: () -> Unit = {},
private val onDeckPanel: (DeckPanel) -> Unit = { SessionPrefs.setDeckPanel(sessionActivity, it) },
private val picker: ((SecondScreenMode) -> ScreenPicker?)? = null,
private val panel: (SecondScreenMode) -> (@androidx.compose.runtime.Composable () -> Unit)? = { null },
) : Presentation(sessionActivity, display) {
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
@@ -67,6 +72,19 @@ class SecondScreenPresentation(
var controlsView: InputSurfaceView? = null
private set
private var created = false
private val brightnessOpen = androidx.compose.runtime.mutableStateOf(false)
private val brightness = androidx.compose.runtime.mutableIntStateOf(BottomBrightness.MIN)
private val brightnessView by lazy {
androidx.compose.ui.platform.ComposeView(context).apply {
setContent {
DroidDeckTheme {
if (!BottomChrome.barShown && currentMode.hasBar) PullTab()
if (brightnessOpen.value) BrightnessDrop(brightness.intValue, ::setBrightness,
onScreenOff = { brightnessOpen.value = false; screenOff() }, onDismiss = { brightnessOpen.value = false })
}
}
}
}
init {
setCancelable(false)
@@ -80,6 +98,9 @@ class SecondScreenPresentation(
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
frame.addView(root, FrameLayout.LayoutParams(-1, -1))
frame.addView(brightnessView, FrameLayout.LayoutParams(-1, -1))
frame.addView(sleepView, FrameLayout.LayoutParams(-1, -1))
light(BottomScreenLight.ON)
setContentView(frame)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
root.setOnApplyWindowInsetsListener { view, insets ->
@@ -94,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()
@@ -127,6 +149,8 @@ class SecondScreenPresentation(
fun showMode(mode: SecondScreenMode) {
if (currentMode == mode && isShowing) return
currentMode = mode
brightnessOpen.value = false
BottomChrome.reset()
if (created) renderMode()
}
@@ -136,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
@@ -174,6 +199,7 @@ class SecondScreenPresentation(
val content = menu ?: return
menuShown = on
if (on) {
wake()
keyboardHost?.takeIf { it.shown }?.hide()
keyboardShown.value = false
ownComposeViews()
@@ -192,6 +218,7 @@ class SecondScreenPresentation(
menuView?.let { frame.removeView(it); it.disposeComposition() }
menuView = null
root.visibility = View.VISIBLE
scheduleDim()
}
}
@@ -223,21 +250,93 @@ class SecondScreenPresentation(
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD ||
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)
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN && screen == BottomScreenLight.ON) waking = false
if (screen != BottomScreenLight.ON || waking) {
// The touch that wakes the screen is swallowed whole, so its release does not click what is under it.
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> if (screen != BottomScreenLight.ON) { waking = true; wake() }
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> waking = false
}
return true
}
scheduleDim()
if (menuShown && event.actionMasked == MotionEvent.ACTION_DOWN) onMenuTouched()
return super.dispatchTouchEvent(event)
}
private val sleepView = View(context).apply {
setBackgroundColor(Color.BLACK)
visibility = View.GONE
}
private var screen = BottomScreenLight.ON
private var waking = false
private val dim = Runnable { if (screen == BottomScreenLight.ON) light(BottomScreenLight.DIM) }
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)
scheduleDim()
}
private fun light(state: BottomScreenLight) {
screen = state
sleepView.visibility = if (state == BottomScreenLight.OFF) View.VISIBLE else View.GONE
sleepView.alpha = 1f
val w = window ?: return
w.attributes = w.attributes.apply {
screenBrightness = when (state) {
BottomScreenLight.ON -> BottomBrightness.level(context) ?: state.brightness
BottomScreenLight.DIM -> BottomBrightness.dimmed(context, state.brightness)
BottomScreenLight.OFF -> state.brightness
}
}
}
private fun toggleBrightness() {
if (!brightnessOpen.value) brightness.intValue = BottomBrightness.initial(context)
brightnessOpen.value = !brightnessOpen.value
}
private fun setBrightness(percent: Int) {
val value = BottomBrightness.clamp(percent)
brightness.intValue = value
SessionPrefs.setBottomBrightness(context, value)
if (screen == BottomScreenLight.ON) light(BottomScreenLight.ON)
}
private fun scheduleDim() {
frame.removeCallbacks(dim)
if (!menuShown && BottomScreenLight.autoDims(currentMode) && SessionPrefs.bottomAutoDim(context)) frame.postDelayed(dim, BottomScreenLight.DIM_AFTER_MS)
}
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)
}
@@ -266,6 +365,7 @@ class SecondScreenPresentation(
}
private fun renderMode() {
if (created) wake()
dropChat()
fieldKeyboard = false
keyboardHost?.hide()
@@ -282,6 +382,7 @@ class SecondScreenPresentation(
val mode = when {
requested == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> SecondScreenMode.NONE
requested == SecondScreenMode.DASHBOARD && dashboard == null -> SecondScreenMode.NONE
requested.sessionPanel && panel(requested) == null -> SecondScreenMode.NONE
requested == SecondScreenMode.DESKTOP && !BottomDesktop.available() -> SecondScreenMode.NONE
else -> requested
}
@@ -300,6 +401,7 @@ class SecondScreenPresentation(
attachKeyboard()
}
SecondScreenMode.DASHBOARD -> renderDashboard()
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,
@@ -314,21 +416,47 @@ class SecondScreenPresentation(
private fun bar(mode: SecondScreenMode) {
val first = barModel(mode) ?: return
root.addView(bottomScreenBarView(context) { barModel(mode) ?: first }, LinearLayout.LayoutParams(-1, -2))
root.addView(androidx.compose.ui.platform.ComposeView(context).apply {
setContent {
DroidDeckTheme {
androidx.compose.animation.AnimatedVisibility(BottomChrome.barShown,
enter = androidx.compose.animation.expandVertically(), exit = androidx.compose.animation.shrinkVertically()) {
BottomScreenBar(barModel(mode) ?: first)
}
}
}
}, LinearLayout.LayoutParams(-1, -2))
}
internal fun barModel(mode: SecondScreenMode): BottomBarModel? {
val swap = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
val extras = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) }) +
BarExtra(context.getString(R.string.bottom_brightness), vector = Icons.Outlined.LightMode, active = brightnessOpen.value,
tag = "bottom-brightness-toggle", onClick = ::toggleBrightness) +
BarExtra(context.getString(R.string.bottom_bar_hide), vector = Icons.Outlined.ExpandLess, tag = "bottom-bar-hide") {
brightnessOpen.value = false
BottomChrome.show(false)
}
fun model(extras: List<BarExtra>, tabs: BarTabs? = null) =
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs, picker?.invoke(mode))
return when (mode) {
SecondScreenMode.KEYBOARD_TRACKPAD -> model(listOf(BarExtra(
context.getString(if (keyboardShown.value) R.string.second_hide_keyboard else R.string.second_show_keyboard),
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }) + swap)
SecondScreenMode.DECK_CONTROLS -> model(swap, deckPanelTabs(context, deckPanel.value, ::selectDeckPanel))
SecondScreenMode.DASHBOARD, SecondScreenMode.CUSTOM_CONTROLS -> model(swap)
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.STEAM_QAM -> {
val fit = QamFit.current(context)
model(listOf(BarExtra(context.getString(R.string.bottom_qam_layout, context.getString(fit.label)), vector = fit.icon,
tag = "bottom-qam-layout") { QamFit.choose(context, fit.next) }) + extras)
}
SecondScreenMode.MIRROR -> model(listOf(BarExtra(context.getString(R.string.bottom_mirror_options), vector = Icons.Outlined.Tune,
active = MirrorOptions.open.value, tag = "bottom-mirror-options-toggle") {
brightnessOpen.value = false
MirrorOptions.open.value = !MirrorOptions.open.value
}) + extras)
SecondScreenMode.DASHBOARD, SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.GUIDES,
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() }) + swap)
tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }) + extras)
else -> null
}
}
@@ -348,6 +476,14 @@ class SecondScreenPresentation(
root.addView(view, weightParams())
}
private fun renderPanel(mode: SecondScreenMode) {
val content = panel(mode) ?: return
bar(mode)
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { PresentationWindows(content) } }
dashboardView = view
root.addView(view, weightParams())
}
private fun closeDashboard() {
dashboardView?.disposeComposition()
dashboardView = null
@@ -396,3 +532,17 @@ class SecondScreenPresentation(
private fun PresentationWindows(content: @androidx.compose.runtime.Composable () -> Unit) {
androidx.compose.runtime.CompositionLocalProvider(LocalPresentationWindow provides true) { content() }
}
internal enum class BottomScreenLight(val brightness: Float) {
ON(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE),
DIM(0.05f),
OFF(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF);
companion object {
const val DIM_AFTER_MS = 60_000L
fun autoDims(mode: SecondScreenMode) = mode == SecondScreenMode.DASHBOARD
}
}
/** Modes drawn with the bottom bar, which the pull tab can bring back. */
internal val SecondScreenMode.hasBar: Boolean get() = this != SecondScreenMode.NONE && this != SecondScreenMode.MENU && this != SecondScreenMode.DESKTOP
@@ -1433,10 +1433,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) else emptyList()) +
(if (dashboard && steam) listOf(SecondScreenMode.STEAM_QAM, SecondScreenMode.ART) else emptyList()) +
(if (dashboard) listOf(SecondScreenMode.GUIDES, SecondScreenMode.MIRROR) else emptyList()) +
(if (desktop) listOf(SecondScreenMode.DESKTOP) else emptyList())
private val DRAWER_MIN_WIDTH = 300.dp
@@ -170,7 +170,7 @@ internal val LocalRevealChecked = androidx.compose.runtime.compositionLocalOf {
internal fun TabStrip(
tabs: List<String>, selected: Int, onSelect: (Int) -> Unit,
modifier: Modifier = Modifier, focusRequesters: List<FocusRequester>? = null,
bumpers: Boolean = true, compact: Boolean = false,
bumpers: Boolean = true, compact: Boolean = false, centered: Boolean = false,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
@@ -181,8 +181,9 @@ internal fun TabStrip(
val tabPadding = if (compact) 10.dp else if (tight) 10.dp else 16.dp
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {
if (bumpers) BumperKey("LB", stringResource(R.string.widgets_prev_tab)) { onSelect((selected + tabs.size - 1) % tabs.size) }
Row(
modifier = Modifier.weight(1f, fill = false).clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape)
// Centred, the bumpers sit at the edges and the tabs in the middle, as in the bottom bar.
Box(if (centered) Modifier.weight(1f) else Modifier.weight(1f, fill = false), contentAlignment = Alignment.Center) { Row(
modifier = Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, pal.line2, shape)
.horizontalScroll(scroll).selectableGroup().padding(3.dp),
) {
tabs.forEachIndexed { i, label ->
@@ -208,7 +209,7 @@ internal fun TabStrip(
.padding(horizontal = tabPadding, vertical = if (compact) 6.dp else 12.dp),
)
}
}
} }
if (bumpers) BumperKey("RB", stringResource(R.string.widgets_next_tab)) { onSelect((selected + 1) % tabs.size) }
}
}