Compare commits

..
Author SHA1 Message Date
xXJsonDeruloXx 05cb4de6ba feat: install GOG games from the Store into Steam via gogdl 2026-10-04 13:25:43 -04:00
56 changed files with 2048 additions and 2334 deletions

No files matched your search

+1
View File
@@ -348,6 +348,7 @@ jobs:
done
test -f "$D/usr/local/bin/droiddeck-session"
test -f "$D/usr/local/bin/droiddeck-proton-extra"
test -f "$D/usr/local/bin/droiddeck-gog"
- name: Cache the CMake build tree
uses: actions/cache@v4
+2 -2
View File
@@ -79,8 +79,8 @@ android {
// file out of its own data directory, and this app's entire job is to exec a rootfs:
// proot, gamescope, the Steam client and everything it launches all live under files/.
targetSdkVersion 28
versionCode 11
versionName "0.3.1"
versionCode 10
versionName "0.3.0"
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}"
+4
View File
@@ -148,6 +148,10 @@
<service
android:name=".runtime.RuntimeInstallService"
android:exported="false" />
<!-- Holds the process in the foreground while a GOG game downloads. -->
<service
android:name=".store.gog.GogInstallService"
android:exported="false" />
<service
android:name=".core.WirelessAdbPairingService"
android:exported="false" />
@@ -7,7 +7,6 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.session.SessionState
import java.io.File
/**
* Decky Loader's state in the launcher: what is installed, the releases on offer and an install
@@ -52,21 +51,4 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
}
}, "install-decky").start()
}
fun importPluginZip(archive: File) {
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
deckyStage = "Starting plugin import…"; deckyPercent = -1
Thread({
val problem = runCatching {
DeckyManager.installPluginZip(activity, archive) { label, value ->
ui.post { deckyStage = label; deckyPercent = value }
}
}.getOrElse { error -> "Plugin import failed: ${error.message ?: error.javaClass.simpleName}" }
ui.post {
deckyStage = null; deckyPercent = -1
val message = problem ?: "Plugin installed. Restart Steam to load it."
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
}
}, "import-decky-plugin").start()
}
}
@@ -42,7 +42,6 @@ import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.ui.ProtonPage
import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.core.PhantomProcessLimit
@@ -111,7 +110,6 @@ class MainActivity : ComponentActivity() {
private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true)
private var steamDeckMode by mutableStateOf(false)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var showProtons by mutableStateOf(false)
@@ -188,9 +186,6 @@ class MainActivity : ComponentActivity() {
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) }
}
private val pickDeckyPluginZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { decky.importPluginZip(it) }
}
private val pickAnyDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = null) }
}
@@ -306,11 +301,13 @@ class MainActivity : ComponentActivity() {
}
// The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings().
private var settingsMode by mutableStateOf<String?>(null)
private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION)
private var resolutionCap by mutableStateOf(1080)
private var customResolution by mutableStateOf<Pair<Int, Int>?>(null)
private var fexPreset by mutableStateOf("")
private var steamChannel by mutableStateOf("steamdeck_publicbeta")
private var runSteamAtStartup by mutableStateOf(false)
private var theme by mutableStateOf("graphite")
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var hdrOn by mutableStateOf(false)
private var fpsLimit by mutableStateOf(0)
private var upscaler by mutableStateOf(0)
@@ -1117,8 +1114,7 @@ class MainActivity : ComponentActivity() {
private fun ModeSettingsHost(mode: String) {
ModeSettingsPage(
ModeSettings(
mode = mode, resolution = resolution,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode,
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(),
@@ -1141,7 +1137,6 @@ class MainActivity : ComponentActivity() {
syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null,
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
@@ -1174,7 +1169,9 @@ class MainActivity : ComponentActivity() {
}
},
onWifiDiscoverySettings = { openWifiDiscoverySettings() },
onResolution = { value -> SessionPrefs.setResolutionChoice(this, mode, value); resolution = value },
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size },
onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape },
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
@@ -1218,7 +1215,6 @@ class MainActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this)
},
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) },
onSteamDeckMode = { on ->
SessionPrefs.setSteamDeckMode(this, on)
steamDeckMode = on
@@ -1246,9 +1242,6 @@ class MainActivity : ComponentActivity() {
decky.deckyInstalled = null
decky.deckySupervisor = false
},
onPickDeckyPluginZip = {
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Decky plugin ZIP"))
},
onDismiss = { settingsMode = null },
),
)
@@ -1330,18 +1323,19 @@ class MainActivity : ComponentActivity() {
showProtons = false
showComponents = false
showMapping = false
resolution = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
resolutionCap = SessionPrefs.resolutionCap(this, mode)
customResolution = SessionPrefs.customResolution(this, mode)
fexPreset = SessionPrefs.fexPreset(this)
fastSync = SessionPrefs.fastSync(this)
fsyncFirst = SessionPrefs.fsyncFirst(this)
syncFallback = SessionPrefs.syncFallback(this)
steamChannel = SessionPrefs.steamChannel(this)
steamDeckMode = SessionPrefs.steamDeckMode(this)
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
shapeMode = SessionPrefs.shapeMode(this)
hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode)
upscaler = SessionPrefs.upscaler(this)
@@ -59,7 +59,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.PerfHud
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionEvents
@@ -83,9 +82,7 @@ import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.SessionDrawerPage
import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.step
import com.droiddeck.launcher.ui.DRAWER_PAGES
import kotlin.math.abs
/**
@@ -161,21 +158,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val cursorBuf = IntArray(WaylandCompositor.CURSOR_BUF_INTS)
private var cursorSerial = 0
private var clientHidesCursor = false
/**
* A program holds a pointer lock (zwp_locked_pointer_v1: a mouse-look game, through gamescope).
* While it does, a physical mouse is captured and its raw deltas go to the program as relative
* motion. Without capture the deltas are worked out from Android's pointer position, which stops
* at the screen edge, and so did the camera (#153).
*/
private var pointerLocked = false
private val pointerLockListener = WaylandCompositor.PointerLockListener { locked, _, _ ->
uiHandler.post {
if (pointerLocked == locked) return@post
pointerLocked = locked
Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released")
updatePointerCapture()
}
}
private var cursorImage by mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null)
private var cursorHotX by mutableStateOf(0)
private var cursorHotY by mutableStateOf(0)
@@ -223,7 +205,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var closeAtOnce = false
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerPage by mutableIntStateOf(0)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
/** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */
@@ -243,7 +225,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var onScreenButtonsVisible by mutableStateOf(false)
private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO)
private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode)
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
@@ -285,12 +267,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onInputDeviceAdded(deviceId: Int) {
logInputDevice("connected", deviceId)
updateOnScreenControls()
updatePointerCapture()
}
override fun onInputDeviceRemoved(deviceId: Int) {
Log.i(TAG, "input device $deviceId disconnected")
updateOnScreenControls()
updatePointerCapture()
}
override fun onInputDeviceChanged(deviceId: Int) = updateOnScreenControls()
}
@@ -341,16 +321,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// below) and the session starts when it is in.
if (!LinuxRuntime.isInstalled(this)) Log.i(TAG, "the Linux runtime is not installed; the loading screen installs it")
// Captured mouse events go down the focus chain, and focus sits somewhere in the overlay:
// the root sees every one of them whichever view that is.
val root = object : FrameLayout(this) {
override fun dispatchCapturedPointerEvent(event: MotionEvent): Boolean =
onCapturedPointer(event) || super.dispatchCapturedPointerEvent(event)
override fun dispatchPointerCaptureChanged(hasCapture: Boolean) {
super.dispatchPointerCaptureChanged(hasCapture)
Log.i(TAG, "pointer capture " + if (hasCapture) "on" else "off")
}
}
val root = FrameLayout(this)
surfaceView = SurfaceView(this)
surfaceView.holder.addCallback(this)
root.addView(surfaceView)
@@ -413,7 +384,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
updateOnScreenControls()
WaylandCompositor.setFirstFrameListener(firstFrameListener)
WaylandCompositor.setPointerLockListener(pointerLockListener)
SessionEvents.markReadyIfPossible()
SessionState.endListener = endListener
// A single Back opens the session menu; two quick presses/swipes send the Steam QAM chord.
@@ -444,8 +414,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// this full-screen host and remain as a white veil after the drawer closes.
defaultFocusHighlightEnabled = false
setContent {
// The drawer, the PC keyboard and picture in picture take the mouse back.
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, pipUi) { updatePointerCapture() }
DroidDeckTheme {
if (pipUi) {
if (SessionState.suspended) androidx.compose.foundation.layout.Box(
@@ -506,9 +474,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
frameGen = frameGen,
lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy, touchMode = touchMode,
oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode,
touchAuto = if (usingTouchpad()) "touchpad" else "direct",
fexPreset = fexPreset,
shapeMode = shapeMode, fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
@@ -560,6 +528,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onShape = { v -> SessionPrefs.setShapeMode(this@SessionActivity, v); readPrefs() },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay,
@@ -787,6 +756,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
oscMode = SessionPrefs.oscMode(this)
shapeMode = SessionPrefs.shapeMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
}
@@ -1042,15 +1012,38 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun outputSize(): Pair<Int, Int> {
val bounds = panelBounds()
val panelW = maxOf(bounds.width(), bounds.height()).toFloat()
val panelH = minOf(bounds.width(), bounds.height()).toFloat()
// Never narrower than 16:9. A foldable's inner panel is nearly square, and a game handed a
// square display draws for the frame it was made for and cuts the sides off itself.
// Wider than 16:9 is fine - games and the client cope with a phone's 20:9 - so the
// panel's aspect is kept above that, unless the user pinned 16:9 for a foldable, and the
// compositor letterboxes onto a squarer panel.
// "Match screen" drops that floor, for a 4:3 or 3:2 handheld whose games should
// fill it.
val aspect = when (SessionPrefs.shapeMode(this)) {
SessionPrefs.SHAPE_WIDE -> 16f / 9f
SessionPrefs.SHAPE_EXACT -> panelW / panelH
else -> maxOf(panelW / panelH, 16f / 9f)
}
// 720 tall at most by default, client and desktop alike: the client's CEF is the heaviest
// thing in the session, and pixels above that cost frames for nothing anyone can see on a
// handheld panel. The mode's settings (the cog beside Play / Desktop) can change
// the cap or lift it to the panel.
val mode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM)
val panel = com.droiddeck.launcher.session.SessionDisplay.panelSize(this)
// A custom resolution is taken as given; the compositor fits it to the panel.
SessionPrefs.customResolution(this, mode)?.let { return it }
// An emulator whose frames cost next to nothing (Library.drawsAtPanel) gets the panel,
// unless the user chose a resolution for the mode.
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
// Lightweight emulators keep their panel-sized default until a resolution is chosen.
val choice = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode))
com.droiddeck.launcher.session.SessionDisplay.MATCH_SCREEN
else SessionPrefs.resolutionChoice(this, mode, panel)
return com.droiddeck.launcher.session.SessionDisplay.resolveChoice(panel, choice)
val cap = if (intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_RUN &&
Library.drawsAtPanel(program) && !SessionPrefs.resolutionChosen(this, mode)) 0
else SessionPrefs.resolutionCap(this, mode)
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
val width = (height * aspect).toInt()
// Odd sizes upset the scaler; both dimensions even is what every mode here would be.
return Pair(width and 1.inv(), height and 1.inv())
}
/**
@@ -1268,8 +1261,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
drawerPage = sessionDrawerPages(SessionState.mode == SessionService.MODE_STEAM && secondScreenDisplays.isNotEmpty())
.step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
drawerPage = (drawerPage + if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else DRAWER_PAGES - 1) % DRAWER_PAGES
releaseDrawerDirection()
}
return true
@@ -1356,10 +1348,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchGenericMotionEvent(event)
}
/** With no view focused, captured mouse events skip the root and arrive here as trackball events. */
override fun dispatchTrackballEvent(event: MotionEvent): Boolean =
onCapturedPointer(event) || super.dispatchTrackballEvent(event)
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (pipUi) return true
if (event.actionMasked == MotionEvent.ACTION_DOWN && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) {
@@ -1710,55 +1698,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
/** A physical mouse, not a touchscreen, stylus or the system's own virtual devices. */
private fun mouseAttached(): Boolean = InputDevice.getDeviceIds().any { id ->
val d = InputDevice.getDevice(id)
d != null && !d.isVirtual && d.supportsSource(InputDevice.SOURCE_MOUSE)
}
/** Capture the mouse exactly while a program holds a lock and the session has the mouse. */
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
val want = pointerLocked && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !pipUi && mouseAttached()
if (want == view.hasPointerCapture()) return
if (want) view.requestPointerCapture() else view.releasePointerCapture()
}
/**
* A captured mouse: raw motion as relative pointer deltas, buttons and the wheel as on the
* uncaptured path. Anything else (a captured touchpad's absolute fingers) is left alone.
*/
private fun onCapturedPointer(event: MotionEvent): Boolean {
if (!pointerLocked || !event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) return false
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
var dx = event.x
var dy = event.y
for (i in 0 until event.historySize) {
dx += event.getHistoricalX(i)
dy += event.getHistoricalY(i)
}
WaylandCompositor.sendPointerDelta(dx, dy)
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
val button = when (event.actionButton) {
MotionEvent.BUTTON_SECONDARY -> PointerGestures.BTN_RIGHT
MotionEvent.BUTTON_TERTIARY -> PointerGestures.BTN_MIDDLE
else -> PointerGestures.BTN_LEFT
}
WaylandCompositor.nativeSendSceneInput(3, button, if (event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) 1 else 0)
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) WaylandCompositor.nativeSendSceneInput(4, -Math.round(v), 0)
}
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP -> {} // the BUTTON_* events carry these
else -> return false
}
return true
}
/** The mode decides which controls appear; `droiddeck-osc` in Downloads still overrides. */
/** Which controller the session has, so a pad report says what was plugged in and when. */
private fun logInputDevice(what: String, deviceId: Int) {
@@ -1775,7 +1714,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
?: SessionPrefs.oscMode(this)
val controls = onScreenControls ?: return
if (pipUi) {
onScreenButtonsVisible = false
controls.releaseAll()
controls.visibility = View.GONE
return
@@ -1791,7 +1729,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// started from the rail, or Steam, gets it; the drawer turns it on anywhere.
else -> !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
}
onScreenButtonsVisible = show
if (show == (controls.visibility == View.VISIBLE)) return
if (!show) controls.releaseAll()
controls.visibility = if (show) View.VISIBLE else View.GONE
@@ -1930,7 +1867,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
controllerSettings = ControllerPrefs.read(this)
updateOnScreenControls()
resumed = true
updatePointerCapture()
if (!pipUi) sessionClipboard.start()
updatePadMotion()
readPrefs()
@@ -1950,7 +1886,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// A button held when the app goes away would stay held in the ring for the whole session.
onScreenControls?.releaseAll()
resumed = false
updatePointerCapture()
updatePadMotion()
keyboard?.takeIf { it.shown }?.hide()
super.onPause()
@@ -1971,8 +1906,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
goFullscreen()
refreshClipboard()
}
// Android drops a capture with the focus; a lock still held takes it again on return.
updatePointerCapture()
}
/** The keyboard/trackpad presentation can own focus instead of the main display. */
@@ -2000,7 +1933,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private val endListener: (Int) -> Unit = { status -> onSessionEnded(status) }
private val firstFrameListener = Runnable {
SessionEvents.firstFrame()
if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this)
runOnUiThread {
loading.visible = false
hud.start()
@@ -2023,7 +1955,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (SessionState.deckPadListener === deckPadListener) SessionState.deckPadListener = null
if (SessionState.endListener === endListener) SessionState.endListener = null
WaylandCompositor.clearFirstFrameListener(firstFrameListener)
WaylandCompositor.clearPointerLockListener(pointerLockListener)
super.onDestroy()
}
@@ -108,9 +108,9 @@ object DeviceReport {
h("Display")
k("Session output", SessionState.outputSize?.let { "${it.first}x${it.second}" })
k("Session refresh", String.format(Locale.US, "%.2f Hz", SessionState.refreshHz))
val panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(context)
k("Resolution (Steam)", SessionPrefs.resolutionChoice(context, SessionService.MODE_STEAM, panelSize))
k("Resolution (Desktop)", SessionPrefs.resolutionChoice(context, SessionService.MODE_DESKTOP, panelSize))
k("Shape setting", SessionPrefs.shapeMode(context))
k("Custom resolution (Steam)", SessionPrefs.customResolution(context, SessionService.MODE_STEAM)?.let { "${it.first}x${it.second}" } ?: "off")
k("Custom resolution (Desktop)", SessionPrefs.customResolution(context, SessionService.MODE_DESKTOP)?.let { "${it.first}x${it.second}" } ?: "off")
k("Foldable", context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle"))
h("Drivers")
@@ -6,6 +6,8 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.store.gog.GogGameInfo
import com.droiddeck.launcher.store.gog.GogManager
import java.io.File
import java.util.zip.CRC32
@@ -23,6 +25,10 @@ object AddedGames {
val gameId: Long,
val candidates: List<File>,
val steamAppId: Int? = null,
/** Launch arguments the game's store gives (a GOG play task's); empty for most games. */
val args: String = "",
/** The store a game was installed from ("gog"), or null for a folder the user added. */
val store: String? = null,
) {
fun folderName(): String = folder.name
}
@@ -69,6 +75,9 @@ object AddedGames {
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
}
// The runtime's own disk (the store's internal GOG folder) is the session's root.
val rootfs = LinuxRuntime.rootDir(context).absolutePath
if (path.startsWith("$rootfs/")) return "/" + path.removePrefix("$rootfs/")
return null
}
@@ -90,15 +99,17 @@ object AddedGames {
fun scan(context: Context): List<Game> {
val out = ArrayList<Game>()
val stores = GogManager.bases(context).map { it.host }
val folders = roots(context).map { it.host } + listOfNotNull(
GameStorage.effective(context)?.let { File(it.path) },
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
)
) + stores.filter { it.isDirectory }
val storePaths = stores.map { it.absolutePath }.toSet()
for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
val steamInstalls = steamInstallDirs(dir)
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
if (folder.name.lowercase() in steamInstalls) continue
if (folder.name.lowercase() in steamInstalls || folder.absolutePath in storePaths) continue
scanGame(context, folder, out)
}
}
@@ -125,12 +136,19 @@ object AddedGames {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
run {
// A store download still running (or stopped partway) is not a game yet.
if (GogManager.incomplete(folder)) return
// A game the store installed says which exe it is, where it starts and with what
// arguments. Folders the user added keep the guess: changing their exe would change
// their shortcut id, and with it the prefix their saves are in.
val task = if (File(folder, GogManager.MARKER).isFile) GogGameInfo.read(folder)?.task else null
val candidates = candidates(folder)
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val exe = chosen ?: candidates.firstOrNull() ?: return
val exe = chosen ?: task?.exe ?: candidates.firstOrNull() ?: return
val guestExe = guestPath(context, exe)
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
val startDir = if (chosen == null && task != null) task.workingDir else exe.parentFile ?: folder
val guestDir = guestPath(context, startDir) ?: return
val name = folder.name
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
@@ -138,7 +156,8 @@ object AddedGames {
val steamRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val steamId = steamRoute(steamRoot, appId)
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId))
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
args = if (chosen == null) task?.arguments.orEmpty() else "", store = if (task != null) "gog" else null))
}
}
@@ -161,6 +180,8 @@ object AddedGames {
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
.append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
if (g.args.isNotEmpty()) json.append(",\"args\":").append(quote(g.args))
g.store?.let { json.append(",\"store\":").append(quote(it)) }
// The art, as the session sees it: the app's cache is bound at its own path, a file in
// the game's folder at the folder's guest path.
val art = AddedGameArt.resolve(context, g)
@@ -1,39 +0,0 @@
package com.droiddeck.launcher.input;
import java.io.File;
/**
* Where the fake input rings live and how the guest is told about them. Kept apart from
* {@link FakeInputWriter}, which loads native code, so it can be tested on the JVM.
*/
final class FakeInputRingPaths {
static final String RING_DIR_NAME = "fakeinput-rings";
private FakeInputRingPaths() {}
/** The rings sit beside the fake evdev nodes: session/dev/input -> session/dev/fakeinput-rings. */
static File ringDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
}
File inputDir = fakeInputDir.getAbsoluteFile();
File parent = inputDir.getParentFile();
return new File(parent != null ? parent : inputDir, RING_DIR_NAME);
}
static File ringFile(File fakeInputDir, int slot) {
File ringDir = ringDir(fakeInputDir);
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
/**
* The ring's path as the guest opens it. The session tree is bound into the guest at its own
* host path, spelled the way {@code Context.getFilesDir()} spells it (LinuxRuntime.binds), so
* the export has to use that same spelling. A canonical path is not that: where
* /data/user/0 is a link, or a separate mount, onto /data/data (ColorOS 16, #166) it resolves
* to a prefix nothing is bound at, and every pad, physical and on-screen, goes dead.
*/
static String exportPath(File ringFile) {
return ringFile.getAbsolutePath();
}
}
@@ -94,6 +94,7 @@ public class FakeInputWriter {
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
private static final String RING_DIR_NAME = "fakeinput-rings";
// After the events - MUST match the block in fakeinput_steam.cpp (DeckImu): what a Deck has and
// an Xbox pad does not - motion, back grips, trackpads - in the Steam Deck controller's axes and
// units, under a seqlock like the snapshot's. Only libfakeinput's Deck controller reads it.
@@ -197,8 +198,26 @@ public class FakeInputWriter {
return builder.toString();
}
private static File getRingDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
}
File inputDir = fakeInputDir.getAbsoluteFile();
File parent = inputDir.getParentFile();
return new File(parent != null ? parent : inputDir, RING_DIR_NAME);
}
private static File getRingFile(File fakeInputDir, int slot) {
return FakeInputRingPaths.ringFile(fakeInputDir, slot);
File ringDir = getRingDir(fakeInputDir);
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
private static String getCanonicalOrAbsolutePath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
}
private static void initializeRingHeader(ByteBuffer data) {
@@ -306,7 +325,7 @@ public class FakeInputWriter {
ringSlot.ringFile = ringFile.getAbsoluteFile();
ringSlot.ringRaf = raf;
ringSlot.ringChannel = channel;
ringSlot.exportPath = FakeInputRingPaths.exportPath(ringFile);
ringSlot.exportPath = getCanonicalOrAbsolutePath(ringFile);
Log.i(TAG, "Created fake input file ring for slot " + slot + ": " + ringSlot.exportPath);
return ringSlot;
} catch (IOException e) {
@@ -76,17 +76,6 @@ public final class PadBridge {
private final java.util.Set<Integer> seenDevices = new java.util.HashSet<>();
private int lastDeviceId = Integer.MIN_VALUE;
/** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */
public static final int NO_CONTROLLER = -1;
/**
* The Android input device id of the physical controller that last drove the pad, or
* {@link #NO_CONTROLLER}. Every pad feeds the one exported slot, so this is how a game's rumble
* on that slot finds the motors in the player's hands (RumbleComponent).
*/
private static volatile int activeControllerId = NO_CONTROLLER;
public static int activeControllerId() { return activeControllerId; }
public PadBridge(File fakeInputDir) {
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
}
@@ -101,7 +90,6 @@ public final class PadBridge {
}
public synchronized void stop() {
activeControllerId = NO_CONTROLLER;
systemGuidePressed = false;
systemQamPressed = false;
qamChordActive = false;
@@ -230,7 +218,6 @@ public final class PadBridge {
*/
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
mutation.accept(state);
activeControllerId = NO_CONTROLLER;
notePlayerInput();
statOnScreen++;
scheduleStats();
@@ -312,7 +299,6 @@ public final class PadBridge {
/** Per event, so the common case - the same pad as last time - is a single compare. */
private void noteDevice(InputDevice device) {
activeControllerId = device.getId();
if (device.getId() == lastDeviceId) return;
lastDeviceId = device.getId();
statDevice = device.getName();
@@ -5,15 +5,8 @@ import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.core.ArchivePaths
import java.io.BufferedInputStream
import java.io.FileOutputStream
import java.io.File
import java.io.FileInputStream
import java.util.UUID
import java.util.zip.ZipInputStream
import org.json.JSONArray
import org.json.JSONObject
/** Optional Decky Loader installation for the ARM64 Linux guest. */
object DeckyManager {
@@ -143,123 +136,6 @@ object DeckyManager {
return null
}
/** Imports a Decky distribution ZIP into homebrew/plugins for the next Steam session. */
fun installPluginZip(context: Context, archive: File, progress: (String, Int) -> Unit): String? {
if (SessionState.running) return "Stop the active session before installing a plugin"
if (installed(context) == null) return "Install Decky Loader before importing a plugin"
if (!archive.isFile || !archive.canRead()) return "Could not read the selected ZIP file"
val plugins = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
if (!plugins.exists() && !plugins.mkdirs()) return "Could not create the Decky plugins directory"
val staging = File(plugins, ".droiddeck-import-${UUID.randomUUID()}")
val backupSuffix = ".droiddeck-backup-${UUID.randomUUID()}"
try {
staging.mkdirs()
progress("Extracting plugin ZIP", -1)
extractPluginZip(archive, staging)
val roots = staging.listFiles()?.filter { it.isDirectory } ?: emptyList()
if (roots.size != 1 || staging.listFiles()?.size != 1) return "Plugin ZIP must contain one top-level plugin folder"
val plugin = roots.single()
if (!File(plugin, "plugin.json").isFile || !File(plugin, "package.json").isFile || !File(plugin, "dist/index.js").isFile) {
return "Plugin ZIP is missing plugin.json, package.json, or dist/index.js"
}
val name = JSONObject(File(plugin, "plugin.json").readText()).getString("name")
require(name.isNotBlank()) { "Plugin name is missing" }
val metadata = JSONObject(File(plugin, "package.json").readText())
downloadRemoteBinaries(metadata, plugin, progress)
if (SessionState.running) return "A session started during installation; stop it before installing a plugin"
DeckyPluginInstall.activate(plugin, plugins, name,
File(plugins.parentFile, "settings/loader.json"), backupSuffix)
progress("Plugin installed · restart Steam to load it", 100)
return null
} catch (e: Exception) {
Log.w(TAG, "plugin ZIP import", e)
return e.message?.takeIf { it.isNotBlank() } ?: "Plugin ZIP installation failed"
} finally {
staging.deleteRecursively()
}
}
private fun extractPluginZip(archive: File, destination: File) {
var totalBytes = 0L
var entries = 0
val seen = HashSet<String>()
ZipInputStream(BufferedInputStream(FileInputStream(archive))).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
entries++
require(entries <= 10_000) { "Plugin ZIP contains too many entries" }
val relative = entry.name.replace('\\', '/')
require(relative.isNotBlank() && !relative.startsWith('/')) { "Plugin ZIP contains an invalid path" }
require(seen.add(relative)) { "Plugin ZIP contains duplicate paths" }
val output = ArchivePaths.inside(destination, relative)
?: throw IllegalArgumentException("Plugin ZIP contains an unsafe path")
if (entry.isDirectory) {
require(output.mkdirs() || output.isDirectory) { "Could not create plugin folder" }
} else {
require(output.parentFile?.let { it.mkdirs() || it.isDirectory } == true) { "Could not create plugin folder" }
FileOutputStream(output).use { out ->
val buffer = ByteArray(64 * 1024)
while (true) {
val read = zip.read(buffer)
if (read < 0) break
totalBytes += read
require(totalBytes <= MAX_PLUGIN_ZIP_BYTES) { "Plugin ZIP expands beyond the 1 GiB limit" }
out.write(buffer, 0, read)
}
}
// Decky distributions place plugin executables under bin/. Java's ZIP reader
// does not expose Unix mode bits, so restore execution on those payload files.
if (relative.split('/').dropLast(1).any { it == "bin" } && !output.setExecutable(true, false)) {
throw IllegalStateException("Could not mark bundled plugin binary executable")
}
}
zip.closeEntry()
}
}
}
private fun downloadRemoteBinaries(metadata: JSONObject, plugin: File, progress: (String, Int) -> Unit) {
val binaries = metadata.optJSONArray("remote_binary") ?: return
val bin = File(plugin, "bin")
for (i in 0 until binaries.length()) {
val binary = binaries.optJSONObject(i) ?: throw IllegalArgumentException("Invalid remote_binary entry")
val name = binary.optString("name")
val url = binary.optString("url")
val hash = binary.optString("sha256hash")
require(name.isNotBlank() && name != "." && name != ".." && !name.contains('/') && !name.contains('\\')) { "Invalid remote binary name" }
require(url.startsWith("https://")) { "Remote binary URL must use HTTPS" }
require(hash.matches(Regex("(?i)[0-9a-f]{64}"))) { "Remote binary $name has an invalid SHA-256 hash" }
require(bin.mkdirs() || bin.isDirectory) { "Could not create plugin bin directory" }
val temp = File(bin, ".$name.download")
progress("Downloading plugin binary · $name", -1)
if (!Downloader.downloadFile(url, temp, false) { fraction ->
progress("Downloading plugin binary · $name", if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
}) {
temp.delete()
throw IllegalStateException("Could not download plugin binary $name")
}
if (!hash.equals(Hashes.sha256(temp), ignoreCase = true)) {
temp.delete()
throw IllegalStateException("Plugin binary checksum mismatch · $name")
}
if (!temp.setExecutable(true, false)) {
temp.delete()
throw IllegalStateException("Could not mark plugin binary executable · $name")
}
val target = File(bin, name)
if (target.exists() && !target.delete()) {
temp.delete()
throw IllegalStateException("Could not replace plugin binary · $name")
}
if (!temp.renameTo(target)) {
temp.delete()
throw IllegalStateException("Could not install plugin binary · $name")
}
}
}
fun uninstall(context: Context, wipeData: Boolean) {
val root = LinuxRuntime.rootDir(context)
setSupervisorEnabled(context, false)
@@ -278,6 +154,4 @@ object DeckyManager {
h[4] == 2.toByte() && h[5] == 1.toByte() && (h[18].toInt() and 255) + ((h[19].toInt() and 255) shl 8) == machine
}
}.getOrDefault(false)
private const val MAX_PLUGIN_ZIP_BYTES = 1024L * 1024L * 1024L
}
@@ -1,52 +0,0 @@
package com.droiddeck.launcher.runtime
import java.io.File
import org.json.JSONArray
import org.json.JSONObject
/** Offline equivalent of Decky's identity-based replacement and loader settings update. */
internal object DeckyPluginInstall {
fun activate(staged: File, plugins: File, name: String, settingsFile: File, backupSuffix: String) {
val settings = if (settingsFile.exists()) JSONObject(settingsFile.readText()) else JSONObject()
val existing = plugins.listFiles().orEmpty().filter { folder ->
folder.isDirectory && !folder.name.startsWith(".droiddeck-") && runCatching {
JSONObject(File(folder, "plugin.json").readText()).getString("name") == name
}.getOrDefault(false)
}
val target = File(plugins, staged.name)
require(!target.exists() || target in existing) { "Plugin folder belongs to another plugin" }
val order = settings.optJSONArray("pluginOrder") ?: JSONArray(plugins.listFiles().orEmpty()
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
.mapNotNull { runCatching { JSONObject(File(it, "plugin.json").readText()).getString("name") }.getOrNull() }
.distinct())
if ((0 until order.length()).none { order.optString(it) == name }) order.put(name)
settings.put("pluginOrder", order)
// Decky's reinstall removes these flags while retaining the plugin's order and data.
for (key in listOf("frozenPlugins", "hiddenPlugins", "disabled_plugins")) {
val values = settings.optJSONArray(key) ?: continue
settings.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != name }))
}
settingsFile.parentFile?.mkdirs()
val pending = File(settingsFile.parentFile, "loader.json$backupSuffix")
val backups = mutableListOf<Pair<File, File>>()
var activated = false
try {
pending.writeText(settings.toString(4))
for (old in existing) {
val backup = File(plugins, ".droiddeck-backup-${old.name}$backupSuffix")
check(old.renameTo(backup)) { "Could not preserve the existing plugin" }
backups.add(old to backup)
}
check(staged.renameTo(target)) { "Could not activate the imported plugin" }
activated = true
check(pending.renameTo(settingsFile)) { "Could not update Decky plugin settings" }
} catch (error: Exception) {
if (activated) target.deleteRecursively()
for ((old, backup) in backups.asReversed()) check(backup.renameTo(old)) { "Could not restore the existing plugin" }
throw error
} finally {
pending.delete()
}
backups.forEach { (_, backup) -> backup.deleteRecursively() }
}
}
@@ -19,10 +19,12 @@ object GuestCommand {
* for the package tools, which refuse any uid but 0. With [logName], everything the command
* says also goes to Download/DroidDeck/tools/<logName>.log beside the session logs, so a problem can
* be handed over like a session's. With [linkDir], hard links (which Android denies apps)
* become symlinks to files proot keeps there (its link2symlink).
* become symlinks to files proot keeps there (its link2symlink). [extraBinds] adds library
* mounts, and [onProcess] lets a caller stop its command.
*/
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
linkDir: File? = null, onLine: (String) -> Unit): Int {
linkDir: File? = null, extraBinds: List<String> = emptyList(),
onProcess: ((Process) -> Unit)? = null, onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
@@ -30,13 +32,14 @@ object GuestCommand {
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
try {
return runLogged(context, argv, fakeRoot, linkDir) { line -> log?.println(line); log?.flush(); onLine(line) }
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, onProcess) { line -> log?.println(line); log?.flush(); onLine(line) }
} finally {
log?.close()
}
}
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, onLine: (String) -> Unit): Int {
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>,
onProcess: ((Process) -> Unit)?, onLine: (String) -> Unit): Int {
val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root)
@@ -47,6 +50,7 @@ object GuestCommand {
if (linkDir != null) cmd.add(1, "--link2symlink")
LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), null)
.forEach { cmd.add("-b"); cmd.add(it) }
extraBinds.forEach { cmd.add("-b"); cmd.add(it) }
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
"PATH=/usr/local/bin:/usr/bin:/bin", "XDG_RUNTIME_DIR=${LinuxRuntime.GUEST_RUNTIME_DIR}",
@@ -65,6 +69,7 @@ object GuestCommand {
val process = builder.start()
val pid = HostProcess.pidOf(process)
OrphanReaper.keep(pid)
onProcess?.invoke(process)
try {
process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) }
return process.waitFor()
@@ -3,58 +3,43 @@ package com.droiddeck.launcher.session
import android.net.LocalServerSocket
import android.content.SharedPreferences
import android.os.Build
import android.os.CombinedVibration
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
import android.view.InputDevice
import androidx.annotation.RequiresApi
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.PadBridge
import java.io.DataInputStream
import kotlin.math.max
/**
* Rumble for the pad, on the motors in the player's hands.
* Rumble for the on-screen pad, on the phone itself.
*
* When a game plays a force-feedback effect on the fake pad (or Steam Input sends the Deck's
* rumble report), the fake evdev layer inside the guest connects to the abstract socket [NAME]
* and sends one packet: strong, weak, duration in ms and the pad slot, four little-endian 16-bit
* values. This listens for those and plays the effect on the physical controller that last drove
* the pad (PadBridge.activeControllerId) when Android exposes its motors - strong and weak
* separately where it has two - and otherwise on the device's own vibrator, with the stronger
* motor's strength: the on-screen pad, or a controller without rumble. Best effort both ways: a
* missing listener costs the guest nothing, and a bad packet is dropped.
* When a game plays a force-feedback effect on the fake pad, the fake evdev layer inside the guest
* connects to the abstract socket [NAME] and sends one packet: strong, weak, duration in ms and
* the pad slot, four little-endian 16-bit values. This listens for those and drives the device's
* vibrator with the stronger motor's strength for the effect's duration. Best effort both ways:
* a missing listener costs the guest nothing, and a bad packet is dropped.
*/
class RumbleComponent : SessionPart() {
@Volatile private var server: LocalServerSocket? = null
private var phone: Motors? = null
/** Where the last effect went, so the next one (or a stop) can end it there. */
private var playing: Motors? = null
private var controllerId = PadBridge.NO_CONTROLLER
private var controller: Motors? = null
private var vibrator: Vibrator? = null
private var preferences: SharedPreferences? = null
private var enabled = false
private val preferenceListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == null || key == "rumble") refreshEnabled()
}
/** The motors of the controller with this input device id, or null when it has none. Tests swap it. */
internal var controllerMotors: (Int) -> Motors? = ::lookupController
@Synchronized private fun refreshEnabled() {
enabled = app()?.let { ControllerPrefs.rumbleEnabled(it) } == true
if (!enabled) { playing?.cancel(); playing = null }
if (!enabled) vibrator?.cancel()
}
override fun start() {
val ctx = app() ?: return
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "rumble: no listener ($e)"); return }
val vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator
vibrator = if (Build.VERSION.SDK_INT >= 31) ctx.getSystemService(VibratorManager::class.java)?.defaultVibrator
else @Suppress("DEPRECATION") ctx.getSystemService(Vibrator::class.java)
phone = vibrator?.takeIf { it.hasVibrator() }?.let { PhoneMotors(it) }
preferences = ControllerPrefs.prefs(ctx).also { it.registerOnSharedPreferenceChangeListener(preferenceListener) }
refreshEnabled()
server = s
@@ -64,7 +49,8 @@ class RumbleComponent : SessionPart() {
try {
val bytes = ByteArray(8)
DataInputStream(client.inputStream).readFully(bytes)
buzz(u16(bytes, 0), u16(bytes, 2), u16(bytes, 4))
val strong = u16(bytes, 0); val weak = u16(bytes, 2); val ms = u16(bytes, 4)
buzz(max(strong, weak), ms)
} catch (e: Exception) {
// A partial packet or a closed peer: nothing to play.
} finally {
@@ -79,11 +65,8 @@ class RumbleComponent : SessionPart() {
preferences?.unregisterOnSharedPreferenceChangeListener(preferenceListener)
preferences = null
enabled = false
playing?.cancel()
playing = null
phone = null
controller = null
controllerId = PadBridge.NO_CONTROLLER
vibrator?.cancel()
vibrator = null
val s = server
server = null
try { s?.close() } catch (e: Exception) { /* the accept loop ends on the next wake */ }
@@ -91,91 +74,24 @@ class RumbleComponent : SessionPart() {
private fun u16(b: ByteArray, at: Int): Int = (b[at].toInt() and 0xFF) or ((b[at + 1].toInt() and 0xFF) shl 8)
@Synchronized private fun buzz(strong: Int, weak: Int, ms: Int) {
@Synchronized private fun buzz(strength: Int, ms: Int) {
if (!enabled) return
val target = target()
if (target !== playing) {
playing?.cancel()
playing = target
target?.let { Log.i(TAG, "rumble: playing on ${it.name}") }
}
if (target == null) return
if ((strong == 0 && weak == 0) || ms == 0) { target.cancel(); return }
val vibrator = vibrator ?: return
if (!vibrator.hasVibrator()) return
if (strength == 0 || ms == 0) { vibrator.cancel(); return }
val amplitude = (strength * 255L / 65535L).toInt().coerceIn(1, 255)
val duration = ms.toLong().coerceIn(1L, 5000L)
try {
target.play(strong, weak, ms.toLong().coerceIn(1L, 5000L))
if (vibrator.hasAmplitudeControl()) vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))
else vibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE))
} catch (e: Exception) {
Log.w(TAG, "rumble: ${target.name}: $e")
Log.w(TAG, "rumble: $e")
}
}
/** The active controller's motors when it has any, else the phone's. */
private fun target(): Motors? {
val id = PadBridge.activeControllerId()
if (id != controllerId) {
controllerId = id
controller = if (id == PadBridge.NO_CONTROLLER) null else try { controllerMotors(id) } catch (e: Exception) { null }
}
return controller ?: phone
}
/** One place an effect can play. Strengths are the evdev 0..65535 magnitudes. */
internal interface Motors {
val name: String
fun play(strong: Int, weak: Int, ms: Long)
fun cancel()
}
private class PhoneMotors(private val vibrator: Vibrator) : Motors {
override val name = "the device's vibrator"
override fun play(strong: Int, weak: Int, ms: Long) = vibrator.vibrate(oneShot(vibrator, max(strong, weak), ms))
override fun cancel() = vibrator.cancel()
}
/** Android 12+: each of the pad's motors on its own, the lower id being the strong one. */
@RequiresApi(31)
private class PadMotors(override val name: String, private val manager: VibratorManager, private val ids: IntArray) : Motors {
override fun play(strong: Int, weak: Int, ms: Long) {
val combined = CombinedVibration.startParallel()
var any = false
fun add(id: Int, strength: Int) {
if (strength == 0) return
combined.addVibrator(id, oneShot(manager.getVibrator(id), strength, ms))
any = true
}
if (ids.size >= 2) { add(ids[0], strong); add(ids[1], weak) } else add(ids[0], max(strong, weak))
if (any) manager.vibrate(combined.combine()) else manager.cancel()
}
override fun cancel() = manager.cancel()
}
/** Before Android 12 a pad has one vibrator. */
private class LegacyPadMotors(override val name: String, private val vibrator: Vibrator) : Motors {
override fun play(strong: Int, weak: Int, ms: Long) = vibrator.vibrate(oneShot(vibrator, max(strong, weak), ms))
override fun cancel() = vibrator.cancel()
}
companion object {
private const val TAG = "SessionService"
/** Must match the fake evdev layer (fakeinput_steam.cpp). */
const val NAME = "droiddeck-rumble"
private fun oneShot(vibrator: Vibrator, strength: Int, ms: Long): VibrationEffect {
val amplitude = if (vibrator.hasAmplitudeControl()) (strength * 255L / 65535L).toInt().coerceIn(1, 255)
else VibrationEffect.DEFAULT_AMPLITUDE
return VibrationEffect.createOneShot(ms, amplitude)
}
private fun lookupController(id: Int): Motors? {
val device = InputDevice.getDevice(id) ?: return null
val name = "\"${device.name}\""
if (Build.VERSION.SDK_INT >= 31) {
val manager = device.vibratorManager
val ids = manager.vibratorIds.sortedArray()
return if (ids.isEmpty()) null else PadMotors(name, manager, ids)
}
@Suppress("DEPRECATION")
val vibrator = device.vibrator
return if (vibrator.hasVibrator()) LegacyPadMotors(name, vibrator) else null
}
}
}
@@ -1,53 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.view.WindowManager
/** The virtual display advertised to the guest, before it is fitted onto the Android panel. */
object SessionDisplay {
const val MATCH_SCREEN = "screen"
const val DEFAULT_RESOLUTION = "1280x720"
fun screenSize(panel: Pair<Int, Int>): Pair<Int, Int> =
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
fun resolveChoice(panel: Pair<Int, Int>, choice: String): Pair<Int, Int> =
if (choice == MATCH_SCREEN) screenSize(panel) else {
// Legacy displays may exceed the custom dialog's size limit. Keep their exact size.
val parts = choice.split('x').map { it.toIntOrNull() }
if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
else 1280 to 720
}
/** Fixed dimensions and the current panel, with no duplicate panel-size preset. */
fun resolutionOptions(panel: Pair<Int, Int>): List<String> =
listOf(DEFAULT_RESOLUTION, "1600x900", "1920x1080")
.filter { resolveChoice(panel, it) != screenSize(panel) } + MATCH_SCREEN
fun panelSize(context: Context): Pair<Int, Int> {
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
@Suppress("DEPRECATION")
val mode = manager.defaultDisplay.mode
return maxOf(mode.physicalWidth, mode.physicalHeight) to minOf(mode.physicalWidth, mode.physicalHeight)
}
/** Interpret an older cap/aspect combination without altering the saved picture size. */
fun resolve(panel: Pair<Int, Int>, cap: Int, shape: String, custom: Pair<Int, Int>? = null): Pair<Int, Int> {
custom?.let { return it }
val panelW = maxOf(panel.first, panel.second).toFloat()
val panelH = minOf(panel.first, panel.second).toFloat().coerceAtLeast(1f)
// Auto retains wide panels but floors squarer ones at 16:9 for game compatibility.
// Match screen removes that floor; fixed 16:9 also keeps foldable sessions stable.
val aspect = when (shape) {
SessionPrefs.SHAPE_WIDE -> 16f / 9f
SessionPrefs.SHAPE_EXACT -> panelW / panelH
else -> maxOf(panelW / panelH, 16f / 9f)
}
val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt()
return ((height * aspect).toInt() and 1.inv()) to (height and 1.inv())
}
/** Mirrors gamescope's even-width 16:9 calculation, including near-16:9 rounding. */
fun canStretch16x9(size: Pair<Int, Int>): Boolean =
(size.second * 16 + 4) / 9 / 2 * 2 > size.first
}
@@ -53,6 +53,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-steam-games" to "usr/local/bin/droiddeck-steam-games",
"usr/local/bin/droiddeck-pad-defaults" to "usr/local/bin/droiddeck-pad-defaults",
"usr/local/bin/droiddeck-gog" to "usr/local/bin/droiddeck-gog",
// Flatpak: the bwrap stand-in, the store's helper and setup, and the front end's launcher.
"usr/local/bin/droiddeck-bwrap" to "usr/local/bin/droiddeck-bwrap",
"usr/local/bin/droiddeck-flatpak" to "usr/local/bin/droiddeck-flatpak",
@@ -88,16 +88,27 @@ object SessionPrefs {
const val SHAPE_WIDE = "16:9"
const val SHAPE_EXACT = "exact"
/** The choices the settings offer, in order. */
val shapeChoices = listOf(
SHAPE_AUTO to "Auto (16:9+)",
SHAPE_EXACT to "Match screen",
SHAPE_WIDE to "Always 16:9",
)
/**
* The shape of the display the session presents: the panel's own (never narrower than 16:9),
* exactly the panel's (a 4:3 or 3:2 handheld, drawn edge to edge), or a fixed 16:9. A foldable defaults to 16:9, which sits with modest bars on either of its
* panels; the panel's own shape would fit one and leave a strip on the other, and gamescope's
* display cannot change size once the session is up.
*/
private fun shapeMode(context: Context): String =
fun shapeMode(context: Context): String =
prefs(context).getString("shape", null)
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
fun setShapeMode(context: Context, mode: String) {
prefs(context).edit().putString("shape", mode).apply()
}
fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO
fun setOscMode(context: Context, mode: String) {
@@ -501,33 +512,11 @@ object SessionPrefs {
* and the emulators under it get the same GPU headroom. Read once, when the session's display
* is sized; a cap the user chose wins over the default.
*/
private fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 720)
fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", defaultResolutionCap(mode))
/** Whether the user chose the mode's resolution (a cap or a custom size) rather than the default. */
fun resolutionChosen(context: Context, mode: String): Boolean =
prefs(context).contains("displayResolution.$mode") ||
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
/** One per-mode choice now owns both dimensions; old caps/shapes are read only for migration. */
fun resolutionChoice(context: Context, mode: String, panel: Pair<Int, Int>): String {
val saved = prefs(context)
saved.getString("displayResolution.$mode", null)?.let { value ->
if (value == SessionDisplay.MATCH_SCREEN) return value
parseResolution(value)?.let { return "${it.first}x${it.second}" }
}
if (!resolutionChosen(context, mode) && !saved.contains("shape")) return SessionDisplay.DEFAULT_RESOLUTION
val legacy = SessionDisplay.resolve(panel, resolutionCap(context, mode), shapeMode(context), customResolution(context, mode))
return if (legacy == SessionDisplay.screenSize(panel)) SessionDisplay.MATCH_SCREEN
else "${legacy.first}x${legacy.second}"
}
fun setResolutionChoice(context: Context, mode: String, choice: String) {
val value = if (choice == SessionDisplay.MATCH_SCREEN) choice else {
val size = requireNotNull(parseResolution(choice)) { "Invalid resolution" }
"${size.first}x${size.second}"
}
prefs(context).edit().putString("displayResolution.$mode", value).apply()
}
prefs(context).contains("resolutionCap.$mode") || customResolution(context, mode) != null
/**
* The FEXCore preset for the games the client launches (core/FexPreset ids); "" = FEX's defaults.
@@ -607,13 +596,25 @@ object SessionPrefs {
prefs(context).edit().putString("theme", id).apply()
}
/** What a mode gets when nothing was chosen. */
@Suppress("UNUSED_PARAMETER")
fun defaultResolutionCap(mode: String): Int = 720
fun setResolutionCap(context: Context, mode: String, cap: Int) {
prefs(context).edit().putInt("resolutionCap.$mode", cap).apply()
}
/**
* A fixed size for the session's display, per mode, or null. When set it replaces both the
* cap and the shape: the compositor fits it to the panel with bars where the shapes differ.
*/
private fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
fun customResolution(context: Context, mode: String): Pair<Int, Int>? =
parseResolution(prefs(context).getString("customRes.$mode", null))
fun setCustomResolution(context: Context, mode: String, size: Pair<Int, Int>?) {
prefs(context).edit().putString("customRes.$mode", size?.let { "${it.first}x${it.second}" }).apply()
}
/** "1024x768" (or ×, or *) to an even size inside 320x240..3840x2160; anything else is null. */
fun parseResolution(text: String?): Pair<Int, Int>? {
val parts = text?.trim()?.split('x', 'X', '×', '*')?.map { it.trim() } ?: return null
@@ -668,27 +669,20 @@ object SessionPrefs {
/**
* How the compositor resizes the session onto the panel (WaylandCompositor.nativeSetUpscaler's
* modes). Linear is the default; Nearest preserves hard pixel edges. Spatial filters work
* when enlarged; Sharpen only works at any size. The old Off/Linear and FSR/FSR Fit pairs
* are equivalent on Wayland, so saved aliases resolve to one choice.
* modes): Off and Linear both filter bilinearly, Nearest keeps pixels square for 2D and old
* titles, the rest sharpen where the picture is enlarged; FSR (fit) rounds the picture to
* FSR's preferred size first. Sharpen only works at any size.
*/
val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
0 to "Off", 1 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 5 to "AMD FSR 1 (fit)", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
)
fun canonicalUpscaler(mode: Int): Int = when (mode) {
1 -> 0
5 -> 4
else -> mode.takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0
}
fun upscalerHasSharpness(mode: Int): Boolean = canonicalUpscaler(mode) in 3..8
fun upscaler(context: Context): Int = canonicalUpscaler(prefs(context).getInt("upscaler", 0))
fun upscaler(context: Context): Int =
prefs(context).getInt("upscaler", 0).takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0
fun setUpscaler(context: Context, mode: Int) {
prefs(context).edit().putInt("upscaler", canonicalUpscaler(mode)).apply()
prefs(context).edit().putInt("upscaler", mode).apply()
}
fun upscaleSharpness(context: Context): Int = prefs(context).getInt("upscaleSharpness", 75).coerceIn(0, 100)
@@ -1,21 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
object SteamRepair {
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun request(context: Context) = File(home(context), ".bl-steam-repair")
private fun unconfirmed(context: Context) = File(home(context), ".local/share/Steam/package/droiddeck-unconfirmed")
fun queued(context: Context): Boolean = request(context).exists()
fun queue(context: Context): Boolean = runCatching {
request(context).apply { parentFile?.mkdirs() }.writeText("1\n")
}.isSuccess
fun clientShown(context: Context) {
unconfirmed(context).delete()
}
}
@@ -0,0 +1,117 @@
package com.droiddeck.launcher.store.gog
import android.util.Log
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
/**
* GOG's web APIs, as Heroic uses them: the signed-in account's games (embed.gog.com, with the
* token gogdl keeps) and a game's art (gamesdb.gog.com, public). Downloads are gogdl's.
*/
object GogApi {
private const val TAG = "GogApi"
private const val TIMEOUT_MS = 20_000
private const val LIBRARY = "https://embed.gog.com/account/getFilteredProducts?mediaType=1&sortBy=title&page="
private const val GAMESDB = "https://gamesdb.gog.com/platforms/gog/external_releases/"
/** An owned game; [image] is the store's wide tile. Only games with a Windows build are listed. */
class Game(val id: String, val title: String, val image: String?)
class Art(val cover: String?, val header: String?, val hero: String?, val logo: String?)
/** Every game the account owns that runs on Windows, by title; null when GOG could not be asked. */
fun library(token: String): List<Game>? {
val games = ArrayList<Game>()
var page = 1
var pages = 1
while (page <= pages) {
val body = get(LIBRARY + page, token) ?: return null
val (items, total) = parseLibraryPage(body) ?: return null
games += items
pages = total.coerceAtMost(100)
page++
}
return games.distinctBy { it.id }.sortedBy { it.title.lowercase() }
}
/** One page: its games and how many pages there are. */
internal fun parseLibraryPage(body: String): Pair<List<Game>, Int>? = runCatching {
val o = JSONObject(body)
val products = o.optJSONArray("products")
val games = (0 until (products?.length() ?: 0)).mapNotNull { i ->
val p = products!!.optJSONObject(i) ?: return@mapNotNull null
val windows = p.optJSONObject("worksOn")?.optBoolean("Windows") ?: false
val id = p.opt("id")?.toString()?.takeIf { it.isNotEmpty() && it != "null" } ?: return@mapNotNull null
if (!windows) return@mapNotNull null
Game(id, p.optString("title").ifEmpty { id }, image(p.optString("image")))
}
games to o.optInt("totalPages", 1).coerceAtLeast(1)
}.getOrNull()
/** The store's image ids come protocol-relative and without a size; 392 is its wide tile. */
internal fun image(raw: String): String? {
if (raw.isBlank()) return null
val url = if (raw.startsWith("//")) "https:$raw" else raw
return if (url.endsWith(".jpg") || url.endsWith(".png")) url else "${url}_392.jpg"
}
/** The game's art from GOG's games database, or null when it has none. */
fun art(id: String): Art? = get(GAMESDB + id, null)?.let(::parseArt)
internal fun parseArt(body: String): Art? = runCatching {
val game = JSONObject(body).optJSONObject("game") ?: return@runCatching null
fun url(key: String, ext: String) = game.optJSONObject(key)?.optString("url_format")
?.takeIf { it.isNotEmpty() }?.replace("{formatter}", "")?.replace("{ext}", ext)
Art(url("vertical_cover", "jpg"), url("horizontal_artwork", "jpg"), url("background", "jpg"), url("logo", "png"))
}.getOrNull()
/**
* Puts the game's art into its folder's .art/ under the names the Added Games art reader looks
* for first (cover, header, hero, logo), so Steam shows GOG's own art for it. Best effort.
*/
fun saveArt(id: String, dir: File) {
val art = art(id) ?: return
val target = File(dir, ".art").apply { mkdirs() }
listOf("cover.jpg" to art.cover, "header.jpg" to art.header, "hero.jpg" to art.hero, "logo.png" to art.logo)
.forEach { (name, url) ->
val file = File(target, name)
if (url != null && !file.isFile) download(url, file)
}
}
private fun download(url: String, file: File) {
var c: HttpURLConnection? = null
try {
c = (URL(url).openConnection() as HttpURLConnection).apply { connectTimeout = TIMEOUT_MS; readTimeout = TIMEOUT_MS }
if (c.responseCode / 100 != 2) return
val part = File(file.path + ".part")
c.inputStream.use { input -> part.outputStream().use { input.copyTo(it) } }
part.renameTo(file)
} catch (e: Exception) {
Log.w(TAG, "$url: $e")
} finally {
c?.disconnect()
}
}
private fun get(url: String, token: String?): String? {
var c: HttpURLConnection? = null
return try {
c = (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = TIMEOUT_MS
readTimeout = TIMEOUT_MS
setRequestProperty("Accept", "application/json")
if (token != null) setRequestProperty("Authorization", "Bearer $token")
}
// The URL is logged; the token never is.
if (c.responseCode / 100 != 2) { Log.w(TAG, "${url.substringBefore('?')} -> HTTP ${c.responseCode}"); null }
else c.inputStream.bufferedReader().use { it.readText() }
} catch (e: Exception) {
Log.w(TAG, "${url.substringBefore('?')}: ${e.javaClass.simpleName}"); null
} finally {
c?.disconnect()
}
}
}
@@ -0,0 +1,56 @@
package com.droiddeck.launcher.store.gog
import org.json.JSONObject
import java.io.File
/**
* What an installed GOG game says about itself: goggame-<id>.info in its folder, the file GOG Galaxy
* and Heroic launch from. Its primary play task names the exe, the folder to start in and the
* arguments, so a store-installed game needs no guessing at which .exe is the game.
*/
object GogGameInfo {
class Task(val exe: File, val workingDir: File, val arguments: String)
class Info(val id: String, val name: String, val task: Task?)
/** The root game's info in [folder] (DLCs add their own files beside it), or null. */
fun read(folder: File): Info? {
val files = folder.listFiles { f -> f.isFile && f.name.startsWith("goggame-") && f.name.endsWith(".info") } ?: return null
val parsed = files.sortedBy { it.name }.mapNotNull { f -> runCatching { JSONObject(f.readText()) }.getOrNull() }
val root = parsed.firstOrNull { it.optString("gameId").let { id -> id.isNotEmpty() && id == it.optString("rootGameId") } }
?: parsed.singleOrNull() ?: return null
return parse(folder, root)
}
internal fun parse(folder: File, json: JSONObject): Info? {
val id = json.optString("gameId").ifEmpty { return null }
val name = json.optString("name").ifEmpty { folder.name }
val tasks = json.optJSONArray("playTasks")
val files = (0 until (tasks?.length() ?: 0)).mapNotNull { tasks!!.optJSONObject(it) }
.filter { it.optString("type") == "FileTask" && it.optString("path").isNotEmpty() }
// Galaxy's own choice: the primary game task; else the first game task; else the first at all.
val chosen = files.firstOrNull { it.optBoolean("isPrimary") && it.optString("category", "game") == "game" }
?: files.firstOrNull { it.optString("category", "game") == "game" }
?: files.firstOrNull()
val task = chosen?.let { t ->
val exe = resolve(folder, t.optString("path")) ?: return@let null
val dir = t.optString("workingDir").takeIf { it.isNotBlank() }?.let { resolve(folder, it) } ?: folder
Task(exe, dir, t.optString("arguments").trim())
}
return Info(id, name, task)
}
/**
* [relative] (a Windows path, backslashes and all) under [base], matched case-insensitively as
* Windows would; null when no such file or folder exists.
*/
internal fun resolve(base: File, relative: String): File? {
var at = base
for (part in relative.replace('\\', '/').split('/').filter { it.isNotEmpty() && it != "." }) {
// The name as the folder lists it: a caseless filesystem (an SD card) would accept any
// spelling, but the session sees the game through proot, where only the real one works.
val names = at.listFiles().orEmpty()
at = names.firstOrNull { it.name == part } ?: names.firstOrNull { it.name.equals(part, ignoreCase = true) } ?: return null
}
return at
}
}
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.store.gog
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.droiddeck.launcher.MainActivity
import com.droiddeck.launcher.R
/**
* Keeps the process in the foreground while a GOG game downloads: games run to tens of gigabytes,
* and without a foreground service Android may kill the app (and the download's proot with it) the
* moment the user switches away. A killed or stopped download resumes when installed again.
*/
class GogInstallService : Service() {
/** One download: [kind] is "install" or "update"; [base] a [GogManager.Base] id; [dir] the game's folder for an update. */
class Job(val kind: String, val id: String, val title: String, val base: String, val dir: String?)
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == ACTION_CANCEL) {
GogState.cancel()
return START_NOT_STICKY
}
val job = intent?.let(::jobFrom)
startForeground(NOTIFICATION_ID, notification(job?.title ?: "GOG", "Starting…", -1))
if (job == null) {
stopSelf(startId)
return START_NOT_STICKY
}
Thread({
val manager = getSystemService(NotificationManager::class.java)
var shown = Int.MIN_VALUE
GogState.run(applicationContext, job) { stage, percent ->
// Every percent at most once: a notification per line would flood the system.
if (percent != shown) {
shown = percent
manager?.notify(NOTIFICATION_ID, notification(job.title, stage, percent))
}
}
@Suppress("DEPRECATION")
stopForeground(true)
stopSelf(startId)
}, "gog-${job.kind}").start()
return START_NOT_STICKY
}
private fun notification(title: String, stage: String, percent: Int): Notification {
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, "GOG downloads",
NotificationManager.IMPORTANCE_LOW).apply {
description = "Shows while a GOG game downloads"
setShowBadge(false)
setSound(null, null)
enableVibration(false)
})
val open = PendingIntent.getActivity(this, 0,
Intent(this, MainActivity::class.java).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE)
val cancel = PendingIntent.getService(this, 1,
Intent(this, GogInstallService::class.java).setAction(ACTION_CANCEL), PendingIntent.FLAG_IMMUTABLE)
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(title)
.setContentText(stage)
.setProgress(100, percent.coerceIn(0, 100), percent < 0)
.setContentIntent(open)
.addAction(Notification.Action.Builder(null, "Stop", cancel).build())
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false)
.build()
}
companion object {
private const val CHANNEL_ID = "gog-download"
private const val NOTIFICATION_ID = 4
private const val ACTION_CANCEL = "com.droiddeck.launcher.gog.CANCEL"
fun start(context: Context, job: Job) {
val intent = Intent(context, GogInstallService::class.java)
.putExtra("kind", job.kind).putExtra("id", job.id).putExtra("title", job.title)
.putExtra("base", job.base).putExtra("dir", job.dir)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
private fun jobFrom(intent: Intent): Job? {
val kind = intent.getStringExtra("kind") ?: return null
val id = intent.getStringExtra("id") ?: return null
return Job(kind, id, intent.getStringExtra("title") ?: id, intent.getStringExtra("base") ?: "internal", intent.getStringExtra("dir"))
}
}
}
@@ -0,0 +1,235 @@
package com.droiddeck.launcher.store.gog
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.Hashes
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import org.json.JSONObject
import java.io.File
/**
* GOG in the Linux runtime, through Heroic's gogdl (GOG's own download protocol, sign-in tokens,
* resumable installs): putting gogdl there, signing in, and installing, updating and removing
* games. A game lands in a GOG folder the Added Games scan reads, so the session puts it in Steam
* as a shortcut like any other added game - the store only fetches; Steam still launches.
*
* Each command runs in a proot of its own (GuestCommand), so a download carries on whether or
* not a session is up.
*/
object GogManager {
private const val TAG = "GogManager"
/** Heroic's gogdl release the app puts in the runtime: a Python zipapp, so any architecture. */
const val GOGDL_VERSION = "1.3.0"
private const val GOGDL_URL = "https://github.com/Heroic-Games-Launcher/heroic-gogdl/releases/download/v$GOGDL_VERSION/gogdl_linux_arm64"
private const val GOGDL_SHA256 = "c49e1519146523ec94f33e2d21eedcc9a167004d7da218621e6d5fb84a7a0f4c"
/** Where gogdl lives in the runtime (droiddeck-gog runs it from there). */
private const val GOGDL = "opt/droiddeck/gogdl/gogdl"
private const val HELPER = "/usr/local/bin/droiddeck-gog"
/** The folder, in each place games can go, that store installs live under. */
const val FOLDER = "GOG"
/** Written by the helper into a game's folder before its download starts. */
const val MARKER = ".droiddeck-gog.json"
private const val RESUME = ".gogdl-resume"
/** One store operation at a time. */
@Volatile var busy: String? = null
private set
/** One place games can go: internal (the runtime's own disk) or the SD card's game library. */
class Base(val id: String, val label: String, val host: File, val guest: String, val binds: List<String>)
/** A GOG game in one of the [bases]; [complete] is false for a download that stopped partway. */
class Installed(val id: String, val name: String, val dir: File, val base: Base, val complete: Boolean)
/** The sign-in gogdl keeps (tokens), in the app's private files - never on shared storage. */
fun authFile(context: Context) = File(context.filesDir, "gog/auth.json")
private fun gogdl(context: Context) = File(LinuxRuntime.rootDir(context), GOGDL)
private fun stamp(context: Context) = File(LinuxRuntime.rootDir(context), "$GOGDL.version")
fun ready(context: Context): Boolean =
gogdl(context).isFile && runCatching { stamp(context).readText().trim() }.getOrNull() == GOGDL_VERSION
fun signedIn(context: Context): Boolean = authFile(context).isFile
fun bases(context: Context): List<Base> {
val internal = Base("internal", "Internal storage", File(LinuxRuntime.rootDir(context), "root/$FOLDER"), "/root/$FOLDER", emptyList())
val sd = GameStorage.effective(context)?.let { lib ->
Base("sd", lib.label, File(lib.path, FOLDER), "/mnt/droiddeck-sd/$FOLDER", listOf("${lib.path}:/mnt/droiddeck-sd"))
}
return listOfNotNull(internal, sd)
}
fun installed(context: Context): List<Installed> = bases(context).flatMap { base ->
base.host.listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { dir -> installedAt(dir, base) }
}.sortedBy { it.name.lowercase() }
private fun installedAt(dir: File, base: Base): Installed? {
val marker = runCatching { JSONObject(File(dir, MARKER).readText()) }.getOrNull()
val info = GogGameInfo.read(dir)
val id = marker?.optString("id")?.ifEmpty { null } ?: info?.id ?: return null
val complete = info?.task != null && !File(dir, RESUME).exists()
return Installed(id, info?.name ?: dir.name, dir, base, complete)
}
/** True for a folder the store put there and whose download has not finished: not a game yet. */
fun incomplete(dir: File): Boolean =
File(dir, MARKER).isFile && (File(dir, RESUME).exists() || GogGameInfo.read(dir)?.task == null)
internal fun exclusive(what: String, block: () -> String?): String? {
synchronized(this) {
if (busy != null) return "Another GOG task is running"
busy = what
}
try { return block() } finally { busy = null }
}
/** Downloads the pinned gogdl into the runtime and checks it. Null on success, else why not. */
fun setup(context: Context, onProgress: (String, Int) -> Unit): String? {
if (!LinuxRuntime.isInstalled(context)) return "Install the Linux runtime first"
return exclusive("setup") {
val target = gogdl(context)
val part = File(target.path + ".part")
target.parentFile?.mkdirs()
onProgress("Downloading gogdl $GOGDL_VERSION", -1)
if (!Downloader.downloadFile(GOGDL_URL, part, true) { f -> if (f >= 0) onProgress("Downloading gogdl $GOGDL_VERSION", (f * 100).toInt()) }) {
return@exclusive "Could not download gogdl"
}
if (!Hashes.sha256(part).equals(GOGDL_SHA256, ignoreCase = true)) {
part.delete()
return@exclusive "gogdl did not match its checksum"
}
if (!part.renameTo(target)) return@exclusive "Could not put gogdl in place"
target.setExecutable(true, false)
stamp(context).writeText(GOGDL_VERSION)
null
}
}
/** Runs the helper. Commands that touch tokens pass no [logName]: their output stays off shared storage. */
private fun helper(context: Context, args: List<String>, logName: String?, binds: List<String> = emptyList(),
onProcess: ((Process) -> Unit)? = null, onEvent: (JSONObject) -> Unit): Int {
val argv = listOf("/usr/bin/python3", HELPER, args[0], authFile(context).path) + args.drop(1)
return GuestCommand.run(context, argv, logName = logName, extraBinds = binds, onProcess = onProcess) { line ->
val o = runCatching { JSONObject(line) }.getOrNull()
if (o != null && o.has("e")) onEvent(o) else if (logName != null) Log.i(TAG, line)
}
}
/** Trades the sign-in page's code for gogdl's tokens. Null on success, else why not. */
fun login(context: Context, code: String): String? {
if (!ready(context)) return "Set up GOG first"
authFile(context).parentFile?.mkdirs()
return exclusive("login") {
var error: String? = null
var done = false
val status = helper(context, listOf("login", code), logName = null) { o ->
when (o.optString("e")) {
"done" -> done = true
"error" -> error = o.optString("message")
}
}
when {
done -> null
error != null -> error
else -> "Signing in failed (exit $status)"
}
}
}
fun signOut(context: Context) {
authFile(context).delete()
token = null
}
private class Token(val value: String, val userId: String, val expires: Long)
@Volatile private var token: Token? = null
/** A current access token for GOG's APIs, refreshed by gogdl when due; null when signed out. */
fun accessToken(context: Context): String? {
token?.takeIf { it.expires * 1000 > System.currentTimeMillis() + 60_000 }?.let { return it.value }
if (!ready(context) || !signedIn(context)) return null
var fresh: Token? = null
// Not exclusive: a token is wanted while a download runs, and gogdl only rewrites the
// file when it refreshes.
helper(context, listOf("token"), logName = null) { o ->
if (o.optString("e") == "token") fresh = Token(o.optString("access_token"), o.optString("user_id"), o.optLong("expires"))
}
token = fresh
return fresh?.value
}
class Sizes(val download: Long, val disk: Long)
/** The Windows build's download and installed sizes, or null when it cannot be read. */
fun sizes(context: Context, id: String): Sizes? {
if (!ready(context)) return null
var sizes: Sizes? = null
helper(context, listOf("info", id), logName = null) { o ->
if (o.optString("e") == "info") sizes = Sizes(o.optLong("download_size"), o.optLong("disk_size"))
}
return sizes
}
/**
* Downloads [id] into [base]; a stopped download picks up where it left off. [onProcess] gets
* the running command so the caller can stop it. Null on success, else why not.
*/
fun install(context: Context, id: String, base: Base, onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? =
transfer(context, "install", listOf("install", id, base.guest), base, onProcess, onProgress)
fun update(context: Context, game: Installed, onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? {
val guest = game.base.guest + "/" + game.dir.name
return transfer(context, "update", listOf("update", game.id, guest), game.base, onProcess, onProgress)
}
private fun transfer(context: Context, verb: String, args: List<String>, base: Base,
onProcess: (Process) -> Unit, onProgress: (String, Int) -> Unit): String? {
if (!ready(context)) return "Set up GOG first"
if (!signedIn(context)) return "Sign in to GOG first"
return exclusive("$verb:${args[1]}") {
base.host.mkdirs()
// proot binds the SD library onto this folder, as a session does.
if (base.binds.isNotEmpty()) File(LinuxRuntime.rootDir(context), "mnt/droiddeck-sd").mkdirs()
var error: String? = null
var done = false
var stage = if (verb == "update") "Updating" else "Downloading"
onProgress("Preparing", -1)
val status = helper(context, args, logName = "gog-$verb", binds = base.binds, onProcess = onProcess) { o ->
when (o.optString("e")) {
"info" -> {
stage = "${if (verb == "update") "Updating" else "Downloading"} ${formatSize(o.optLong("download_size"))}"
onProgress(stage, 0)
}
"progress" -> onProgress(stage, o.optInt("percent"))
"error" -> error = o.optString("message")
"done" -> done = true
}
}
when {
done -> null
error != null -> error
else -> "Stopped (exit $status)"
}
}
}
/**
* Removes the game's files and gogdl's record of them. The game's Proton prefix (its saves and
* settings) stays where Steam keeps it, as for any added game taken out of the library.
*/
fun uninstall(context: Context, game: Installed): String? = exclusive("uninstall:${game.id}") {
if (!game.dir.deleteRecursively() && game.dir.exists()) return@exclusive "Could not remove ${game.dir.name}"
File(LinuxRuntime.rootDir(context), "root/.config/heroic_gogdl/manifests/${game.id}").delete()
null
}
fun formatSize(bytes: Long): String = when {
bytes >= 1L shl 30 -> "%.1f GB".format(bytes / (1L shl 30).toDouble())
bytes >= 1L shl 20 -> "%.0f MB".format(bytes / (1L shl 20).toDouble())
else -> "%.0f KB".format(bytes / 1024.0)
}
}
@@ -0,0 +1,172 @@
package com.droiddeck.launcher.store.gog
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
/**
* The GOG store's state for the life of the process, so a download carries on - and its progress
* shows - while the user moves around the launcher or plays something meanwhile. Downloads run in
* [GogInstallService], which keeps the process in the foreground for as long as they take.
*/
object GogState {
private val main = Handler(Looper.getMainLooper())
var ready by mutableStateOf(false)
private set
var signedIn by mutableStateOf(false)
private set
/** The account's Windows games; null until loaded. */
var library by mutableStateOf<List<GogApi.Game>?>(null)
private set
var libraryFailed by mutableStateOf(false)
private set
var loadingLibrary by mutableStateOf(false)
private set
var installed by mutableStateOf<List<GogManager.Installed>>(emptyList())
private set
/** What is running: "setup", "login", or a game id; null when idle. */
var busy by mutableStateOf<String?>(null)
private set
var stage by mutableStateOf<String?>(null)
private set
var percent by mutableStateOf(-1)
private set
/** Download and installed sizes by game id; absent until asked, null while being read. */
val sizes = mutableStateMapOf<String, GogManager.Sizes?>()
@Volatile private var process: Process? = null
@Volatile private var cancelled = false
fun refresh(context: Context) {
val app = context.applicationContext
Thread({
val r = GogManager.ready(app)
val s = GogManager.signedIn(app)
val list = GogManager.installed(app)
main.post { ready = r; signedIn = s; installed = list }
}, "gog-refresh").start()
}
fun loadLibrary(context: Context, force: Boolean = false) {
if (loadingLibrary || (!force && library != null)) return
val app = context.applicationContext
loadingLibrary = true
libraryFailed = false
Thread({
val token = GogManager.accessToken(app)
val games = token?.let { GogApi.library(it) }
main.post {
loadingLibrary = false
if (games != null) library = games else libraryFailed = true
}
}, "gog-library").start()
}
fun loadSizes(context: Context, id: String) {
if (sizes.containsKey(id)) return
val app = context.applicationContext
sizes[id] = null
Thread({
val s = GogManager.sizes(app, id)
main.post { sizes[id] = s; if (s == null) sizes.remove(id) }
}, "gog-sizes").start()
}
private fun background(context: Context, what: String, label: String, work: (Context, (String, Int) -> Unit) -> String?) {
if (busy != null) return
val app = context.applicationContext
busy = what; stage = "Starting…"; percent = -1
Thread({
val problem = try {
work(app) { s, p -> main.post { stage = s; percent = p } }
} catch (e: Exception) {
e.message ?: e.toString()
}
val r = GogManager.ready(app)
val s = GogManager.signedIn(app)
val list = GogManager.installed(app)
main.post {
busy = null; stage = null; percent = -1
ready = r; signedIn = s; installed = list
if (problem != null) Toast.makeText(app, "$label: $problem", Toast.LENGTH_LONG).show()
}
}, "gog-$what").start()
}
fun setup(context: Context) = background(context, "setup", "GOG setup") { c, p -> GogManager.setup(c, p) }
fun login(context: Context, code: String) = background(context, "login", "GOG sign-in") { c, p ->
p("Signing in…", -1)
GogManager.login(c, code).also { if (it == null) main.post { library = null; loadLibrary(c, force = true) } }
}
fun signOut(context: Context) {
GogManager.signOut(context)
library = null
signedIn = false
}
fun uninstall(context: Context, game: GogManager.Installed) =
background(context, game.id, game.name) { c, p -> p("Removing…", -1); GogManager.uninstall(c, game) }
fun install(context: Context, game: GogApi.Game, base: GogManager.Base) {
if (busy != null) return
busy = game.id; stage = "Starting…"; percent = -1
GogInstallService.start(context, GogInstallService.Job("install", game.id, game.title, base.id, null))
}
fun update(context: Context, game: GogManager.Installed) {
if (busy != null) return
busy = game.id; stage = "Starting…"; percent = -1
GogInstallService.start(context, GogInstallService.Job("update", game.id, game.name, game.base.id, game.dir.path))
}
/** Stops the running download; installing again resumes it. */
fun cancel() {
cancelled = true
process?.destroy()
}
/** The service's half of [install] and [update]; runs on the service's thread. */
internal fun run(context: Context, job: GogInstallService.Job, notify: (String, Int) -> Unit) {
val app = context.applicationContext
cancelled = false
main.post { busy = job.id }
val base = GogManager.bases(app).firstOrNull { it.id == job.base }
val problem = try {
when {
base == null -> "That storage is not available"
job.kind == "update" -> {
val game = GogManager.installed(app).firstOrNull { it.dir.path == job.dir }
if (game == null) "The game is no longer installed"
else GogManager.update(app, game, { process = it }) { s, p -> main.post { stage = s; percent = p }; notify(s, p) }
}
else -> GogManager.install(app, job.id, base, { process = it }) { s, p -> main.post { stage = s; percent = p }; notify(s, p) }
}
} catch (e: Exception) {
e.message ?: e.toString()
} finally {
process = null
}
val list = GogManager.installed(app)
// GOG's own art for Steam to show; the Steam store's is the fallback if this finds none.
if (problem == null) list.firstOrNull { it.id == job.id }?.let { runCatching { GogApi.saveArt(job.id, it.dir) } }
main.post {
busy = null; stage = null; percent = -1
installed = list
val message = when {
cancelled -> "${job.title}: stopped. Install again to pick up where it left off."
problem != null -> "${job.title}: $problem"
job.kind == "update" -> "${job.title} is up to date."
else -> "${job.title} is installed. It shows in Steam the next time Steam starts."
}
Toast.makeText(app, message, Toast.LENGTH_LONG).show()
}
}
}
@@ -52,13 +52,13 @@ import kotlinx.coroutines.withContext
// dialog, with each variable's actions in a menu off its value as everywhere else.
@Composable
fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true) {
fun GameEnvironmentRow(modifier: Modifier = Modifier) {
var open by remember { mutableStateOf(false) }
// Opened with a pad, the editor starts with focus in it; the dialog is a window of its own and
// would otherwise give the pad nothing to move from.
var byPad by remember { mutableStateOf(false) }
val inputMode = LocalInputModeManager.current
SettingsRow(stringResource(R.string.game_env_title), if (showHint) stringResource(R.string.game_env_hint) else null) {
SettingsRow(stringResource(R.string.game_env_title), stringResource(R.string.game_env_hint)) {
SecondaryButton(stringResource(R.string.game_env_edit), modifier = modifier) {
byPad = inputMode.inputMode == InputMode.Keyboard
open = true
@@ -0,0 +1,328 @@
package com.droiddeck.launcher.ui
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.net.Uri
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.WebResourceRequest
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
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.width
import androidx.compose.material3.LinearProgressIndicator
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.store.gog.GogApi
import com.droiddeck.launcher.store.gog.GogManager
import com.droiddeck.launcher.store.gog.GogState
// The Store's GOG side: sign in, the account's Windows games, and installing them into a GOG
// folder the Added Games scan reads - so each shows in Steam as a non-Steam game, launched by
// Steam through Proton like any other added game. gogdl (Heroic's) does the downloading.
/** GOG's own sign-in page; it hands back a code on embed.gog.com, which gogdl trades for tokens. */
private const val GOG_LOGIN = "https://auth.gog.com/auth?client_id=46899977096215655" +
"&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code&layout=galaxy"
@Composable
internal fun GogStore(s: FrontEndState) {
val ctx = LocalContext.current
var open by rememberSaveable { mutableStateOf<String?>(null) }
var signingIn by remember { mutableStateOf(false) }
LaunchedEffect(s.ready) { GogState.refresh(ctx) }
BackHandler(enabled = open != null) { open = null }
if (signingIn) GogLoginDialog(onCode = { signingIn = false; GogState.login(ctx, it) }, onDismiss = { signingIn = false })
if (!s.ready) {
Rise(1) { Note("Install the Linux runtime from Setup first; GOG games install into it.") }
return
}
val id = open
if (id != null) {
GogDetail(id) { open = null }
return
}
GogBusyBar()
when {
!GogState.ready -> Rise(1) {
GogCard(
"Set up GOG",
"Adds gogdl, the GOG downloader Heroic Games Launcher uses (about 2 MB), to the Linux runtime. " +
"Games you own on GOG then install from here and show in Steam's library as non-Steam games.",
) {
PrimaryButton(if (GogState.busy == "setup") "Setting up…" else "Set up GOG", enabled = GogState.busy == null, main = true) { GogState.setup(ctx) }
}
}
!GogState.signedIn -> Rise(1) {
GogCard("Sign in to GOG", "Sign in with your GOG account to list and install the games you own. The sign-in stays in the app's private storage.") {
PrimaryButton(if (GogState.busy == "login") "Signing in…" else "Sign in", enabled = GogState.busy == null, main = true) { signingIn = true }
}
}
else -> GogLibrary(onOpen = { open = it }, onSignOut = {
GogState.signOut(ctx)
CookieManager.getInstance().removeAllCookies(null)
WebStorage.getInstance().deleteAllData()
})
}
}
@Composable
private fun GogCard(title: String, body: String, actions: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
verticalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).clip(Shape16).background(colors.surface).border(1.dp, pal.line, Shape16).padding(16.dp),
) {
Text(title, fontSize = 18.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(body, fontSize = 14.sp, color = colors.onSurfaceVariant)
Actions { actions() }
}
}
/** The running setup, sign-in or download, whichever page it was started from. */
@Composable
private fun GogBusyBar() {
val colors = MaterialTheme.colorScheme
val busy = GogState.busy ?: return
val name = GogState.library?.firstOrNull { it.id == busy }?.title ?: GogState.installed.firstOrNull { it.id == busy }?.name
?: when (busy) { "setup" -> "GOG"; "login" -> "GOG"; else -> busy }
Column(modifier = Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 4.dp)) {
val stage = GogState.stage
Text(
"$name · " + (if (stage != null && GogState.percent >= 0) "$stage · ${GogState.percent}%" else stage ?: "Starting…"),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(bottom = 6.dp),
)
if (GogState.percent >= 0) LinearProgressIndicator(progress = { GogState.percent / 100f }, modifier = Modifier.fillMaxWidth().height(4.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(4.dp))
}
}
@Composable
private fun GogLibrary(onOpen: (String) -> Unit, onSignOut: () -> Unit) {
val ctx = LocalContext.current
LaunchedEffect(Unit) { GogState.loadLibrary(ctx) }
val library = GogState.library
val installed = GogState.installed
Rise(2) {
Actions {
SecondaryButton(if (GogState.loadingLibrary) "Refreshing…" else "Refresh", enabled = !GogState.loadingLibrary) { GogState.loadLibrary(ctx, force = true) }
SecondaryButton("Sign out", enabled = GogState.busy == null, onClick = onSignOut)
}
}
if (installed.isNotEmpty()) {
Rise(3) { SectionTitle("Installed", installed.size.toString()) }
Rise(3) {
GogGrid(installed.map { i ->
Triple(i.id, i.name, library?.firstOrNull { it.id == i.id }?.image)
}, first = true, status = { gid -> installed.firstOrNull { it.id == gid }?.let { if (it.complete) "Installed · ${it.base.label}" else "Download stopped" } }, onOpen = onOpen)
}
Rise(3) { Note("Installed games show in Steam's library as non-Steam games the next time Steam starts.") }
}
when {
library == null && GogState.libraryFailed -> Rise(4) { Note("GOG could not be reached, or the sign-in has expired. Refresh, or sign out and in again.") }
library == null -> Rise(4) { SectionTitle("Your games", "loading…") }
library.isEmpty() -> Rise(4) { Note("No Windows games on this GOG account yet.") }
else -> {
Rise(4) { SectionTitle("Your games", library.size.toString()) }
Rise(5) {
GogGrid(library.map { Triple(it.id, it.title, it.image) }, first = installed.isEmpty(),
status = { gid -> installed.firstOrNull { it.id == gid }?.let { if (it.complete) "Installed" else "Download stopped" } }, onOpen = onOpen)
}
}
}
}
/** Games as tiles with GOG's wide art: three across, or one on a narrow page. */
@Composable
private fun GogGrid(games: List<Triple<String, String, String?>>, first: Boolean, status: (String) -> String?, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val columns = if (LocalNarrowPane.current) 1 else 3
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {
games.chunked(columns).forEachIndexed { r, row ->
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
row.forEachIndexed { i, (id, title, image) ->
key(id) {
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Column(
modifier = Modifier.weight(1f).paneItem("tile:gog:$id").then(if (first && r == 0 && i == 0) Modifier.firstTile() else Modifier)
.clip(Shape14).background(if (hot) pal.signal.copy(alpha = 0.10f) else colors.surface)
.glideBorder(hot, Shape14, pal.signal, pal.line)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button) { onOpen(id) },
) {
AsyncImage(
model = image, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).background(colors.surfaceVariant),
)
Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val st = status(id)
Text(st ?: "GOG", fontSize = 13.sp, color = if (st != null) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
}
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
}
}
}
}
@Composable
private fun GogDetail(id: String, onBack: () -> Unit) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val narrow = LocalNarrowPane.current
val game = GogState.library?.firstOrNull { it.id == id }
val local = GogState.installed.firstOrNull { it.id == id }
val title = game?.title ?: local?.name ?: id
val bases = remember { GogManager.bases(ctx) }
var baseId by rememberSaveable(id) { mutableStateOf(bases.first().id) }
LaunchedEffect(id) { GogState.loadSizes(ctx, id) }
val sizes = GogState.sizes[id]
val busyHere = GogState.busy == id
// Uninstall asks twice: one stray press of A should not cost a download.
var confirmRemove by remember(id) { mutableStateOf(false) }
LaunchedEffect(confirmRemove) { if (confirmRemove) { kotlinx.coroutines.delay(4000); confirmRemove = false } }
Rise(0) { BackLink("GOG", onClick = onBack) }
Rise(1) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), modifier = Modifier.padding(top = 12.dp, bottom = 8.dp)) {
AsyncImage(
model = game?.image, contentDescription = null, contentScale = ContentScale.Crop,
modifier = Modifier.width(if (narrow) 140.dp else 220.dp).aspectRatio(16f / 9f).clip(Shape12).background(colors.surfaceVariant),
)
Column(modifier = Modifier.weight(1f)) {
Text(title, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(
when {
local?.complete == true -> "Installed on ${local.base.label}"
local != null -> "Download stopped on ${local.base.label}"
else -> "Windows · runs through Proton in Steam"
},
fontSize = 14.sp, color = colors.onSurfaceVariant,
)
}
}
}
if (local == null && bases.size > 1) {
Rise(2) { SectionTitle("Install to", null) }
Rise(2) {
Actions {
bases.forEach { b ->
val label = "${b.label} · ${GameStorage.free(b.host.parentFile ?: b.host)} free"
if (b.id == baseId) PrimaryButton(label, compact = true) {} else SecondaryButton(label, compact = true) { baseId = b.id }
}
}
}
}
Rise(3) {
Actions {
when {
busyHere -> SecondaryButton("Stop") { GogState.cancel() }
local == null || !local.complete -> PrimaryButton(if (local == null) "Install" else "Resume download", main = true, enabled = GogState.busy == null && game != null) {
val base = local?.base ?: bases.first { it.id == baseId }
game?.let { GogState.install(ctx, it, base) }
}
else -> SecondaryButton("Check for update", enabled = GogState.busy == null) { GogState.update(ctx, local) }
}
if (local != null && !busyHere) {
SecondaryButton(if (confirmRemove) "Press again to uninstall" else "Uninstall", enabled = GogState.busy == null) {
if (confirmRemove) { confirmRemove = false; GogState.uninstall(ctx, local) } else confirmRemove = true
}
}
sizes?.let {
ActionChip("${GogManager.formatSize(it.download)} download", ok = false)
ActionChip("${GogManager.formatSize(it.disk)} installed", ok = false)
}
if (local?.complete == true) ActionChip("● Installed", ok = true)
}
}
if (busyHere) GogBusyBar()
Rise(4) {
Box(Modifier.padding(top = 12.dp)) {
Note(
if (local?.complete == true) "It is in Steam's library as a non-Steam game (after Steam next starts). Uninstalling removes the game's files; " +
"its saves and settings stay in its Proton prefix."
else "Installs the Windows build. Once it finishes, the game shows in Steam's library as a non-Steam game the next time Steam starts, " +
"and runs through Proton like the rest of your added games.",
)
}
}
}
/** A sign-in that ends on GOG's success page hands its code to [onCode]; GOG's page does the rest. */
@SuppressLint("SetJavaScriptEnabled")
@Composable
private fun GogLoginDialog(onCode: (String) -> Unit, onDismiss: () -> Unit) {
var done by remember { mutableStateOf(false) }
fun check(url: String?): Boolean {
val uri = url?.let(Uri::parse) ?: return false
if (uri.host != "embed.gog.com" || uri.path?.startsWith("/on_login_success") != true) return false
val code = uri.getQueryParameter("code") ?: return false
if (!done) { done = true; onCode(code) }
return true
}
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { c ->
WebView(c).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = check(request.url.toString())
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
if (check(url)) view.stopLoading()
}
}
loadUrl(GOG_LOGIN)
}
},
onRelease = { it.destroy() },
)
}
}
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.TextButton
@@ -43,8 +44,10 @@ class DownloadRow(val key: String, val label: String, val detail: String, val pr
class ModeSettings(
val mode: String,
val resolution: String,
val panelSize: Pair<Int, Int> = 1280 to 720,
val resolutionCap: Int,
/** A fixed session size, or null for the cap and shape. */
val customResolution: Pair<Int, Int>? = null,
val shapeMode: String,
val hdr: Boolean,
val hdrReason: String?,
/** The GPU drivers in use, as the row that opens them on the Components page says it. */
@@ -72,14 +75,13 @@ class ModeSettings(
val fexPreset: String? = null,
/** Steam only: SessionPrefs.SYNC_* chosen for Proton games; null outside Steam. */
val syncBackend: String? = null,
/** Steam only: forces game windows fullscreen (null = not a Steam page). */
/** Steam only: games are stretched to fill the screen (null = not a Steam page). */
val forceFullscreen: Boolean? = null,
val stretch16x9: Boolean? = null,
/** Steam only: the client branch forced on the command line. */
val steamChannel: String? = null,
/** Steam only: enable the SteamOS client interface and its performance controls. */
val steamDeckMode: Boolean = false,
val steamRepairQueued: Boolean = false,
/** Steam, Deck mode: the QAM's performance overlay (mangoapp) is started. */
val mangoapp: Boolean = true,
/** Steam only: what the pad is to the client (SessionPrefs.CONTROLLER_*); null outside Steam. */
@@ -111,7 +113,10 @@ class ModeSettings(
class AddedGameRow(val folderPath: String, val folderName: String, val exePath: String, val exeName: String, val candidates: List<Pair<String, String>>)
class ModeSettingsActions(
val onResolution: (String) -> Unit,
val onResolution: (Int) -> Unit,
/** Null clears it. */
val onCustomResolution: (Pair<Int, Int>?) -> Unit = {},
val onShape: (String) -> Unit,
val onHdr: (Boolean) -> Unit,
/** Opens the GPU drivers on the Components page: they are shared by every session. */
val onGpuDrivers: () -> Unit = {},
@@ -135,7 +140,6 @@ class ModeSettingsActions(
val onForceFullscreen: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {},
val onSteamChannel: (String) -> Unit = {},
val onSteamRepair: () -> Unit = {},
val onSteamDeckMode: (Boolean) -> Unit = {},
val onMangoapp: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
@@ -151,160 +155,142 @@ class ModeSettingsActions(
val onDeckyCheck: () -> Unit = {},
val onDeckyEnabled: (Boolean) -> Unit = {},
val onDeckyUninstall: () -> Unit = {},
val onPickDeckyPluginZip: () -> Unit = {},
val onDismiss: () -> Unit,
)
private enum class SteamSettingsTab(val label: Int) {
DISPLAY(R.string.drawer_page_display),
CONTROLS(R.string.drawer_page_controls),
GAMES(R.string.game_settings_title),
AUDIO(R.string.mode_audio),
SESSION(R.string.mode_session),
STEAM(R.string.mode_tab_steam),
}
@Composable
fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
val steam = s.mode == SessionService.MODE_STEAM
val host = rememberMenuHost()
var confirmDeckyRemoval by remember { mutableStateOf(false) }
var explainWifiDiscovery by remember { mutableStateOf(false) }
var tabIndex by androidx.compose.runtime.saveable.rememberSaveable(s.mode) { mutableStateOf(0) }
val tabs = SteamSettingsTab.entries
val tab = tabs[tabIndex]
val scrolls = tabs.map { androidx.compose.foundation.rememberScrollState() }
val tabFocus = remember { tabs.map { androidx.compose.ui.focus.FocusRequester() } }
val pageScroll = androidx.compose.foundation.rememberScrollState()
val firstChip = remember { androidx.compose.ui.focus.FocusRequester() }
fun selectTab(index: Int) { host.open = null; tabIndex = index }
androidx.compose.runtime.LaunchedEffect(steam, tabIndex) {
androidx.compose.runtime.LaunchedEffect(Unit) {
// One frame first: the box has to be laid out before it can take focus. Opened from the
// cog, focus starts on the first control (Resolution) so the d-pad works at once.
androidx.compose.runtime.withFrameNanos { }
runCatching {
if (!steam || tab == SteamSettingsTab.DISPLAY) firstChip.requestFocus()
else tabFocus[tabIndex].requestFocus()
}
runCatching { firstChip.requestFocus() }
}
SettingsPage(
host,
title = if (steam) stringResource(R.string.mode_steam_title) else stringResource(R.string.mode_desktop_title),
onBack = a.onDismiss,
scroll = scrolls[tabIndex],
modifier = if (steam) Modifier.bumpers(
onPrevious = { selectTab((tabIndex + tabs.size - 1) % tabs.size) },
onNext = { selectTab((tabIndex + 1) % tabs.size) },
) else Modifier,
header = if (steam) ({
TabStrip(tabs.map { stringResource(it.label) }, tabIndex, ::selectTab,
modifier = Modifier.fillMaxWidth().padding(top = 12.dp), focusRequesters = tabFocus)
}) else null,
scroll = pageScroll,
) {
if (!steam || tab == SteamSettingsTab.DISPLAY) {
val displaySize = com.droiddeck.launcher.session.SessionDisplay.resolveChoice(s.panelSize, s.resolution)
SettingsGroup(stringResource(R.string.display_session)) {
ResolutionRow(host, s.resolution, s.panelSize, a.onResolution,
chipModifier = Modifier.focusRequester(firstChip))
if (s.stretch16x9 != null && (com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(s.panelSize) ||
com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize))) {
val canStretch = com.droiddeck.launcher.session.SessionDisplay.canStretch16x9(displaySize)
ChoiceRow(host, "game-fit", stringResource(R.string.display_game_fit),
stringResource(if (canStretch) R.string.display_game_fit_hint else R.string.display_game_fit_unavailable),
listOf(false to stringResource(R.string.display_preserve), true to stringResource(R.string.display_stretch)),
s.stretch16x9 && canStretch, enabled = canStretch, onPick = a.onStretch16x9)
}
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
ChoiceRow(
host, "upscaler", stringResource(R.string.display_filter), null,
SessionPrefs.upscalerChoices, s.upscaler,
note = stringResource(R.string.display_filter_note), onPick = a.onUpscaler,
)
if (SessionPrefs.upscalerHasSharpness(s.upscaler)) SliderRow(
stringResource(R.string.display_sharpness), null, s.upscaleSharpness, 0..100, step = 5,
format = { "$it%" }, onChange = a.onUpscaleSharpness,
)
}
SettingsGroup(stringResource(R.string.display_frame_rate)) {
ChoiceRow(host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session),
SessionPrefs.fpsLimitChoices, s.fpsLimit, note = stringResource(R.string.mode_fps_note), onPick = a.onFpsLimit)
}
SettingsGroup(stringResource(R.string.mode_hdr)) {
ToggleRow(
host, "hdr", stringResource(R.string.mode_hdr10),
s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) }
?: stringResource(R.string.mode_hdr_restart),
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
)
}
SettingsGroup(stringResource(R.string.mode_drivers)) {
SettingsRow(stringResource(R.string.mode_gpu_drivers), stringResource(R.string.mode_gpu_drivers_hint)) {
ValueChip(s.gpuDrivers, open = false) { a.onGpuDrivers() }
}
SettingsGroup(stringResource(R.string.mode_display)) {
val default = SessionPrefs.defaultResolutionCap(s.mode)
var editCustom by remember { mutableStateOf(false) }
val custom = s.customResolution
ChoiceRow(
host, "res", stringResource(R.string.mode_resolution), stringResource(R.string.common_applies_next_session),
listOf(720 to stringResource(R.string.mode_res_720), 900 to stringResource(R.string.mode_res_900), 1080 to stringResource(R.string.mode_res_1080), 0 to stringResource(R.string.mode_res_native))
.map { (cap, label) -> cap to (if (cap == default) stringResource(R.string.mode_res_default, label) else label) } +
(CUSTOM to (custom?.let { stringResource(R.string.mode_res_custom_value, it.first, it.second) } ?: stringResource(R.string.mode_res_custom))),
if (custom != null) CUSTOM else s.resolutionCap, note = stringResource(R.string.mode_res_note),
chipModifier = androidx.compose.ui.Modifier.focusRequester(firstChip),
onPick = { v -> if (v == CUSTOM) editCustom = true else { a.onCustomResolution(null); a.onResolution(v) } },
)
ChoiceRow(
host, "shape", stringResource(R.string.mode_ratio),
if (custom != null) stringResource(R.string.mode_ratio_custom) else stringResource(R.string.mode_ratio_auto),
com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape,
)
ChoiceRow(
host, "fps", stringResource(R.string.mode_fps), stringResource(R.string.common_applies_next_session),
com.droiddeck.launcher.session.SessionPrefs.fpsLimitChoices, s.fpsLimit,
note = stringResource(R.string.mode_fps_note),
onPick = a.onFpsLimit,
)
ChoiceRow(
host, "upscaler", stringResource(R.string.drawer_scaling), "How the picture is resized to the screen; the sharpening modes sharpen where it is enlarged.",
com.droiddeck.launcher.session.SessionPrefs.upscalerChoices, s.upscaler,
note = "The sharpening modes work only when the session is smaller than the screen; Linear, Nearest and Sharpen only work at any size. Costs a little GPU time.",
onPick = a.onUpscaler,
)
SliderRow(
stringResource(R.string.drawer_scaling_sharpness), null, s.upscaleSharpness, 0..100, step = 5,
enabled = s.upscaler != 0, format = { "$it%" }, onChange = a.onUpscaleSharpness,
)
if (editCustom) CustomResolutionDialog(
initial = custom,
onSave = { size -> editCustom = false; a.onCustomResolution(size) },
onDismiss = { editCustom = false },
)
}
SettingsGroup(stringResource(R.string.mode_hdr)) {
ToggleRow(
host, "hdr", stringResource(R.string.mode_hdr10),
s.hdrReason?.let { stringResource(R.string.mode_hdr_unavailable, it) }
?: stringResource(R.string.mode_hdr_restart),
checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr,
)
}
SettingsGroup(stringResource(R.string.mode_drivers)) {
SettingsRow(stringResource(R.string.mode_gpu_drivers), stringResource(R.string.mode_gpu_drivers_hint)) {
ValueChip(s.gpuDrivers, open = false) { a.onGpuDrivers() }
}
}
if (!steam || tab == SteamSettingsTab.CONTROLS) {
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
ChoiceRow(
host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode,
note = stringResource(R.string.mode_touch_note),
onPick = a.onTouch,
)
if (steam && s.oscMode != null) ChoiceRow(
host, "osc", stringResource(R.string.mode_osc), null,
listOf(
SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto),
SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam),
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never),
), s.oscMode,
note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
)
if (steam && s.steamController != null) ChoiceRow(
host, "controller", stringResource(R.string.mode_controller), stringResource(R.string.mode_controller_hint),
listOf(
SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360),
), s.steamController,
note = stringResource(R.string.mode_controller_note),
onPick = a.onSteamController,
)
if (steam) ChoiceRow(
host, "back-actions", stringResource(R.string.mode_back), SessionPrefs.backActionsOrder(s.backActionsInverted),
listOf(
false to SessionPrefs.BACK_MENU_THEN_QAM,
true to SessionPrefs.BACK_QAM_THEN_MENU,
), s.backActionsInverted, onPick = a.onBackActionsInverted,
)
}
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
ChoiceRow(
host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode,
note = stringResource(R.string.mode_touch_note),
onPick = a.onTouch,
)
if (steam && s.oscMode != null) ChoiceRow(
host, "osc", stringResource(R.string.mode_osc), null,
listOf(
SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto),
SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam),
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never),
), s.oscMode,
note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
)
if (steam && s.steamController != null) ChoiceRow(
host, "controller", stringResource(R.string.mode_controller), stringResource(R.string.mode_controller_hint),
listOf(
SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360),
), s.steamController,
note = stringResource(R.string.mode_controller_note),
onPick = a.onSteamController,
)
if (steam) ChoiceRow(
host, "back-actions", stringResource(R.string.mode_back), SessionPrefs.backActionsOrder(s.backActionsInverted),
listOf(
false to SessionPrefs.BACK_MENU_THEN_QAM,
true to SessionPrefs.BACK_QAM_THEN_MENU,
), s.backActionsInverted, onPick = a.onBackActionsInverted,
)
}
if (!steam || tab == SteamSettingsTab.SESSION) {
SettingsGroup(stringResource(R.string.mode_session)) {
ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend),
stringResource(R.string.mode_suspend_hint),
listOf(
SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto),
SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual),
SessionPrefs.SUSPEND_NEVER to stringResource(R.string.common_never),
),
s.suspendPolicy,
note = stringResource(R.string.mode_suspend_note),
onPick = a.onSuspendPolicy,
)
}
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
s.pipAutoEnter, onChange = a.onPipAutoEnter)
}
if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
ToggleRow(
host, "steam-startup", stringResource(R.string.mode_steam_startup),
stringResource(R.string.mode_steam_startup_hint),
s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
)
}
SettingsGroup(stringResource(R.string.mode_session)) {
ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend),
stringResource(R.string.mode_suspend_hint),
listOf(
SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto),
SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual),
SessionPrefs.SUSPEND_NEVER to stringResource(R.string.common_never),
),
s.suspendPolicy,
note = stringResource(R.string.mode_suspend_note),
onPick = a.onSuspendPolicy,
)
}
if (steam && tab == SteamSettingsTab.STEAM) SettingsGroup(stringResource(R.string.mode_decky)) {
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
s.pipAutoEnter, onChange = a.onPipAutoEnter)
}
if (steam) SettingsGroup(stringResource(R.string.mode_startup)) {
ToggleRow(
host, "steam-startup", stringResource(R.string.mode_steam_startup),
stringResource(R.string.mode_steam_startup_hint),
s.runSteamAtStartup, onChange = a.onRunSteamAtStartup,
)
}
if (steam) SettingsGroup(stringResource(R.string.mode_decky)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
val status = when {
@@ -338,22 +324,15 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
) { confirmDeckyRemoval = true }
}
}
if (s.deckyInstalled != null) ToggleRow(
host, "decky-enabled", stringResource(R.string.mode_decky),
if (s.deckyInstalled != null) SettingsRow(
stringResource(R.string.mode_decky),
if (s.deckyEnabled) stringResource(R.string.mode_decky_on)
else stringResource(R.string.mode_decky_off),
s.deckyEnabled,
enabled = !s.deckySessionRunning && s.deckyStage == null,
onChange = a.onDeckyEnabled,
)
SettingsRow(
"Plugins",
"Install a plugin ZIP for the next Steam session.",
) {
SecondaryButton(
if (s.deckyStage?.startsWith("Downloading plugin binary") == true) "Downloading…" else "Install from ZIP",
enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning,
onClick = a.onPickDeckyPluginZip,
Switch(
checked = s.deckyEnabled,
onCheckedChange = a.onDeckyEnabled,
enabled = !s.deckySessionRunning && s.deckyStage == null,
)
}
if (s.deckyStage != null && s.deckyPercent >= 0) {
@@ -363,7 +342,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
}
}
if (steam && tab == SteamSettingsTab.STEAM && s.steamChannel != null) SettingsGroup(stringResource(R.string.mode_client)) {
if (steam && s.steamChannel != null) SettingsGroup(stringResource(R.string.mode_client)) {
ToggleRow(
host, "steamdeck", stringResource(R.string.mode_deck_mode),
stringResource(R.string.mode_deck_mode_hint),
@@ -382,14 +361,8 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
note = stringResource(R.string.mode_branch_note),
onPick = a.onSteamChannel,
)
SettingsRow(
stringResource(R.string.mode_steam_repair),
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
) {
SecondaryButton(stringResource(R.string.mode_steam_repair_button), enabled = !s.steamRepairQueued, onClick = a.onSteamRepair)
}
}
if (steam && tab == SteamSettingsTab.STEAM && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
if (steam && s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) {
val hint = when {
s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off)
!s.wifiDiscoveryPermission && s.wifiDiscoveryAsked -> stringResource(R.string.mode_wifi_permission_denied)
@@ -408,11 +381,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
}
}
if ((!steam || tab == SteamSettingsTab.GAMES) && s.forceFullscreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen),
stringResource(R.string.display_force_fullscreen_hint), s.forceFullscreen, onChange = a.onForceFullscreen)
}
if (steam && tab == SteamSettingsTab.GAMES && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
if (steam && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
for (dir in s.addedGamesDirs) {
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
ActionRow(
@@ -437,7 +406,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
)
}
if (steam && tab == SteamSettingsTab.GAMES && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
if (steam && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
if (s.syncBackend != null) SettingsRow(
stringResource(R.string.sync_backend_title),
stringResource(R.string.sync_backend_hint),
@@ -458,9 +427,18 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
note = stringResource(FexPreset.byId(s.fexPreset).detail), onPick = a.onFexPreset,
)
GameEnvironmentRow()
if (s.forceFullscreen != null) ToggleRow(
host, "fill", stringResource(R.string.mode_fill),
stringResource(R.string.mode_fill_hint),
s.forceFullscreen, onChange = a.onForceFullscreen,
)
if (s.stretch16x9 != null) ToggleRow(
host, "stretch169", stringResource(R.string.mode_stretch169),
stringResource(R.string.mode_stretch169_hint),
s.stretch16x9, onChange = a.onStretch16x9,
)
}
if (steam && tab == SteamSettingsTab.AUDIO && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
if (steam && s.directAudio != null && s.mic != null) SettingsGroup(stringResource(R.string.mode_audio)) {
ToggleRow(host, "da", stringResource(R.string.mode_directaudio), stringResource(R.string.mode_directaudio_hint), s.directAudio, onChange = a.onDirectAudio)
ChoiceRow(
host, "clientAudio", stringResource(R.string.mode_client_audio), stringResource(R.string.mode_client_audio_hint),
@@ -469,7 +447,7 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
ToggleRow(host, "mic", stringResource(R.string.mode_mic), stringResource(R.string.mode_mic_hint), s.mic, onChange = a.onMic)
}
if (steam && tab == SteamSettingsTab.GAMES && s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
if (steam && s.gameStorage != null) SettingsGroup(stringResource(R.string.mode_storage)) {
val custom = s.gameStorage.isNotEmpty() && s.gameStorage != "off" && s.storageOptions.none { it.second == s.gameStorage }
val options = buildList {
add("" to (if (s.storageOptions.isEmpty()) stringResource(R.string.mode_storage_auto_none) else stringResource(R.string.mode_storage_auto)))
@@ -538,10 +516,13 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
)
}
/** The Resolution menu's "Custom…" entry. */
private const val CUSTOM = -1
/** Width × height for the session, with the common handheld shapes one tap away. */
@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
@Composable
internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) {
private fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) {
var w by remember { mutableStateOf(initial?.first?.toString() ?: "") }
var h by remember { mutableStateOf(initial?.second?.toString() ?: "") }
val parsed = SessionPrefs.parseResolution("${w}x$h")
@@ -1,39 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionDisplay
/** Pre-session resolution choice, applied when the session starts. */
@Composable
fun ResolutionRow(
host: MenuHost, choice: String, panel: Pair<Int, Int>, onPick: (String) -> Unit,
chipModifier: Modifier = Modifier,
) {
val custom = "custom"
val size = SessionDisplay.resolveChoice(panel, choice)
val screen = SessionDisplay.screenSize(panel)
val choices = SessionDisplay.resolutionOptions(panel)
val selected = if (size == screen) SessionDisplay.MATCH_SCREEN else choice
var editCustom by remember { mutableStateOf(false) }
val options = choices.map { value ->
val dimensions = SessionDisplay.resolveChoice(panel, value)
value to if (value == SessionDisplay.MATCH_SCREEN) stringResource(R.string.display_match_screen, screen.first, screen.second)
else if (value == SessionDisplay.DEFAULT_RESOLUTION) stringResource(R.string.mode_res_default, "${dimensions.first}×${dimensions.second}")
else "${dimensions.first}×${dimensions.second}"
} + (custom to if (selected in choices) stringResource(R.string.mode_res_custom)
else stringResource(R.string.mode_res_custom_value, size.first, size.second))
ChoiceRow(host, "resolution", stringResource(R.string.display_resolution),
stringResource(R.string.common_applies_next_session),
options, if (selected in choices) selected else custom, chipModifier = chipModifier,
onPick = { value -> if (value == custom) editCustom = true else onPick(value) })
if (editCustom) CustomResolutionDialog(size,
onSave = { value -> editCustom = false; onPick("${value.first}x${value.second}") },
onDismiss = { editCustom = false })
}
@@ -1,19 +0,0 @@
package com.droiddeck.launcher.ui
/** Stable page identities keep focus and scroll positions when a secondary display comes and goes. */
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("touch"),
SECOND_SCREEN("second-screen:none"),
DISPLAY("hud"),
EFFECTS("look"),
GAMES("anisotropy"),
SESSION("suspend"),
}
internal fun sessionDrawerPages(hasSecondScreen: Boolean): List<SessionDrawerPage> =
SessionDrawerPage.entries.filter { hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN }
internal fun List<SessionDrawerPage>.step(current: SessionDrawerPage, direction: Int): SessionDrawerPage {
val index = indexOf(current).coerceAtLeast(0)
return this[Math.floorMod(index + direction, size)]
}
@@ -70,9 +70,6 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.PlatformTextStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.TextOverflow
// The session's loading screen, its paused screen and the HUD text style.
@@ -276,11 +273,7 @@ private fun CancelHint(onCancel: () -> Unit, modifier: Modifier = Modifier) {
.padding(horizontal = 12.dp),
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.size(20.dp).clip(CircleShape).background(colors.onBackground)) {
Text("B", color = colors.background, style = TextStyle(
fontSize = 12.sp, lineHeight = 12.sp, fontWeight = FontWeight.Bold,
platformStyle = PlatformTextStyle(includeFontPadding = false),
lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.Both),
))
Text("B", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = colors.background)
}
Text(stringResource(R.string.common_cancel), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
@@ -28,24 +28,15 @@ import androidx.compose.foundation.layout.offset
import androidx.compose.material.icons.Icons
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.outlined.AutoFixHigh
import androidx.compose.material.icons.outlined.ExpandMore
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.MoreHoriz
import androidx.compose.material.icons.outlined.PowerSettingsNew
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.material.icons.outlined.DesktopWindows
import androidx.compose.material.icons.outlined.Layers
import androidx.compose.material.icons.outlined.ScreenShare
import androidx.compose.material.icons.outlined.PictureInPictureAlt
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.draw.clipToBounds
import android.view.Display
import androidx.activity.compose.BackHandler
@@ -88,8 +79,6 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
@@ -104,6 +93,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -139,33 +129,22 @@ import com.droiddeck.launcher.input.SecondScreenMode
import kotlinx.coroutines.flow.collect
import java.util.Locale
private val SessionDrawerPage.title: Int get() = when (this) {
SessionDrawerPage.CONTROLLER -> R.string.drawer_page_controller
SessionDrawerPage.SECOND_SCREEN -> R.string.drawer_second_screen
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects
SessionDrawerPage.GAMES -> R.string.game_settings_title
SessionDrawerPage.SESSION -> R.string.mode_session
}
private val drawerPageTitles = listOf(R.string.drawer_page_display, R.string.drawer_page_effects, R.string.drawer_page_controls, R.string.drawer_page_components, R.string.drawer_page_settings)
private val SessionDrawerPage.icon get() = when (this) {
SessionDrawerPage.CONTROLLER -> Icons.Outlined.SportsEsports
SessionDrawerPage.SECOND_SCREEN -> Icons.Outlined.ScreenShare
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
SessionDrawerPage.SESSION -> Icons.Outlined.Settings
}
/** One icon per drawer page, in page order (QAM-style tabs). */
private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.AutoFixHigh, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings)
private val drawerPageEntries = listOf("hud", "look", "touch", "cmp-proton", "suspend")
private class DrawerFocus {
private val requesters = HashMap<String, FocusRequester>()
private val last = mutableMapOf<SessionDrawerPage, String>()
private val last = arrayOfNulls<String>(DRAWER_PAGES)
var focused by mutableStateOf<String?>(null)
private set
private fun requester(key: String) = requesters.getOrPut(key) { FocusRequester() }
fun track(page: SessionDrawerPage, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged {
fun track(page: Int, key: String): Modifier = Modifier.focusRequester(requester(key)).onFocusChanged {
if (it.isFocused) {
last[page] = key
focused = key
@@ -173,9 +152,9 @@ private class DrawerFocus {
}
/** Where focus was last on [page], if anywhere. */
fun target(page: SessionDrawerPage) = last[page]
fun target(page: Int) = last[page]
fun request(key: String) = runCatching { requester(key).requestFocus() }
fun forget(page: SessionDrawerPage) { last.remove(page) }
fun forget(page: Int) { last[page] = null }
}
/** Everything the drawer shows and does. */
@@ -189,13 +168,13 @@ class DrawerActions(
val frameGen: FrameGen.Mode,
val lossless: Lossless.State,
val oscMode: String,
val onScreenButtonsVisible: Boolean,
val suspendPolicy: String,
val backActionsInverted: Boolean,
val touchMode: String,
val touchAuto: String,
val shapeMode: String,
val fexPreset: String,
/** Steam only: forces game windows fullscreen, changed live (null = not Steam). */
/** Steam only: games stretched to the screen's size, changed live (null = not Steam). */
val fillScreen: Boolean? = null,
val upscaler: Int = 0,
val upscaleSharpness: Int = 75,
@@ -225,6 +204,7 @@ class DrawerActions(
val onSuspendPolicy: (String) -> Unit,
val onBackActionsInverted: (Boolean) -> Unit,
val onTouch: (String) -> Unit,
val onShape: (String) -> Unit,
val onFexPreset: (String) -> Unit,
val onFillScreen: (Boolean) -> Unit = {},
val onUpscaler: (Int) -> Unit = {},
@@ -245,7 +225,7 @@ class DrawerActions(
/** Stop with the dialog's button's bounds on screen, for the flood to grow out of; null falls back to [onStop]. */
val onStopFrom: ((androidx.compose.ui.geometry.Rect?) -> Unit)? = null,
val onClose: () -> Unit,
/** Games tab: every Proton with what it uses; null until first read. */
/** Components tab: every Proton with what it uses; null until first read. */
val components: ComponentsManager.Snapshot? = null,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
@@ -255,20 +235,16 @@ class DrawerActions(
@OptIn(ExperimentalComposeUiApi::class)
@Composable
internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, controllerActive: Boolean, onPageChange: (SessionDrawerPage) -> Unit, a: DrawerActions) {
val pages = sessionDrawerPages(a.steam && a.secondScreenDisplays.isNotEmpty())
val page = requestedPage.takeIf { it in pages } ?: SessionDrawerPage.CONTROLLER
LaunchedEffect(requestedPage, pages) { if (page != requestedPage) onPageChange(page) }
fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageChange: (Int) -> Unit, a: DrawerActions) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val host = rememberMenuHost()
var androidAppsExpanded by rememberSaveable { mutableStateOf(false) }
var advancedEffectsExpanded by rememberSaveable { mutableStateOf(false) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
var confirmStop by remember { mutableStateOf(false) }
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
var stopCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
val pageScroll = remember { SessionDrawerPage.entries.associateWith { ScrollState(0) } }
val pageScroll = remember { List(DRAWER_PAGES) { ScrollState(0) } }
val veil by animateFloatAsState(if (open) 1f else 0f, Motion.tw(260), label = "veil")
val focus = remember { DrawerFocus() }
val inputModeManager = LocalInputModeManager.current
@@ -278,13 +254,13 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
BackHandler(enabled = open && confirmStop) { confirmStop = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
LaunchedEffect(open, page) { if (open && page == SessionDrawerPage.GAMES) a.onComponentsRefresh() }
LaunchedEffect(open, page) { if (open && page == DRAWER_PAGE_COMPONENTS) a.onComponentsRefresh() }
LaunchedEffect(open, controllerActive) {
if (open && !controllerActive) focusManager.clearFocus(force = true)
}
// The page focus was last put on: turning to another (LB, RB, a tab) starts it at its first
// option; anything else (a menu closing, the drawer opening again) goes back where it was.
var focusedPage by remember { mutableStateOf(page) }
var focusedPage by remember { mutableIntStateOf(page) }
LaunchedEffect(open, page, controllerActive, host.open, appToChooseDisplay, confirmStop) {
if (!open) {
host.open = null
@@ -294,8 +270,8 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (host.open != null || appToChooseDisplay != null || confirmStop) return@LaunchedEffect
val turned = page != focusedPage
focusedPage = page
// The page's top control: on Session that is Android apps, when it is shown.
val first = if (page == SessionDrawerPage.SESSION && a.isHomeApp) "apps" else page.firstControl
// The page's top control: on Settings that is Android apps, when it is shown.
val first = if (page == drawerPageEntries.lastIndex && a.isHomeApp) "apps" else drawerPageEntries[page]
if (turned) focus.forget(page)
val target = focus.target(page) ?: first
repeat(24) {
@@ -374,21 +350,31 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
modifier = Modifier.fillMaxWidth().padding(top = if (short) 6.dp else 12.dp),
) {
DrawerBumper("LB", stringResource(R.string.drawer_prev_page), modifier = focus.track(page, "prev")) {
host.open = null; onPageChange(pages.step(page, -1))
host.open = null; onPageChange((page + DRAWER_PAGES - 1) % DRAWER_PAGES)
}
DrawerPageTabs(page = page, pages = pages, compact = short, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerPageTabs(page = page, compact = short, modifier = Modifier.weight(1f)) { index -> host.open = null; onPageChange(index) }
DrawerBumper("RB", stringResource(R.string.drawer_next_page), modifier = focus.track(page, "next")) {
host.open = null; onPageChange(pages.step(page, 1))
host.open = null; onPageChange((page + 1) % DRAWER_PAGES)
}
}
Column(
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)),
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]),
) { CompositionLocalProvider(LocalChipMinWidth provides 120.dp) {
when (page) {
SessionDrawerPage.DISPLAY -> {
0 -> {
SettingsGroup(stringResource(R.string.drawer_page_display)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn,
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
if (a.fillScreen != null) ToggleRow(
host, "fill", stringResource(R.string.drawer_fill), null, a.fillScreen,
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen,
)
ChoiceRow(host, "upscaler", stringResource(R.string.drawer_scaling), null,
SessionPrefs.upscalerChoices, a.upscaler,
chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler)
SliderRow(stringResource(R.string.drawer_scaling_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
enabled = a.upscaler != 0, format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"),
onChange = a.onUpscaleSharpness)
val fgOpen = host.open == "fg"
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
@@ -398,27 +384,14 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
ChoiceRow(host, "upscaler", stringResource(R.string.display_filter), null,
SessionPrefs.upscalerChoices, a.upscaler,
note = stringResource(R.string.display_filter_note),
chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler)
if (SessionPrefs.upscalerHasSharpness(a.upscaler)) SliderRow(
stringResource(R.string.display_sharpness), null, a.upscaleSharpness, 0..100, step = 5,
format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), onChange = a.onUpscaleSharpness)
}
if (a.fillScreen != null) SettingsGroup(stringResource(R.string.display_window_compatibility)) {
ToggleRow(host, "fill", stringResource(R.string.display_force_fullscreen),
stringResource(R.string.display_force_fullscreen_live), a.fillScreen,
chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen)
}
}
SessionDrawerPage.EFFECTS -> {
ScreenEffectsGroup(host, a, advancedEffectsExpanded,
onAdvancedToggle = { advancedEffectsExpanded = !advancedEffectsExpanded }) { key -> focus.track(page, key) }
DRAWER_PAGE_EFFECTS -> {
ScreenEffectsGroup(host, a) { key -> focus.track(page, key) }
TextureFilteringGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.CONTROLLER -> {
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
DRAWER_PAGE_CONTROLS -> {
SettingsGroup(stringResource(R.string.drawer_page_controls)) {
ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
@@ -429,16 +402,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
a.controller?.let { c ->
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
if (a.onScreenButtonsVisible) {
if (a.steam) {
ToggleRow(host, "steam-button", stringResource(R.string.ctrl_steam_button), null, c.steamButton,
chipModifier = focus.track(page, "steam-button"), onChange = a.onSteamButton)
ToggleRow(host, "qam-button", stringResource(R.string.ctrl_qam_button), null, c.qamButton,
chipModifier = focus.track(page, "qam-button"), onChange = a.onQamButton)
}
ToggleRow(host, "keyboard-button", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton,
chipModifier = focus.track(page, "keyboard-button"), onChange = a.onKeyboardButton)
}
ToggleRow(host, "steam-button", stringResource(R.string.ctrl_steam_button), null, c.steamButton,
chipModifier = focus.track(page, "steam-button"), onChange = a.onSteamButton)
ToggleRow(host, "qam-button", stringResource(R.string.ctrl_qam_button), null, c.qamButton,
chipModifier = focus.track(page, "qam-button"), onChange = a.onQamButton)
ToggleRow(host, "keyboard-button", stringResource(R.string.ctrl_keyboard_button), null, c.keyboardButton,
chipModifier = focus.track(page, "keyboard-button"), onChange = a.onKeyboardButton)
}
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.mode_back), null,
listOf(false to SessionPrefs.BACK_MENU_THEN_QAM, true to SessionPrefs.BACK_QAM_THEN_MENU),
@@ -454,23 +423,18 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
}
}
SessionDrawerPage.SECOND_SCREEN -> {
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.GAMES -> {
Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
TextureFilteringGroup(host, a) { key -> focus.track(page, key) }
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) {
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), null,
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
GameEnvironmentRow(modifier = focus.track(page, "game-env"), showHint = false)
if (a.steam && a.secondScreenDisplays.isNotEmpty()) SettingsGroup(stringResource(R.string.drawer_second_screen)) {
ChoiceRow(host, "second-screen-mode", stringResource(R.string.drawer_second_screen_shows), null,
(listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()))
.map { it to it.label },
a.secondScreenMode, chipModifier = focus.track(page, "second-screen-mode"), onPick = a.onSecondScreenMode)
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null,
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
chipModifier = focus.track(page, "second-screen-display"), onPick = a.onSecondScreenDisplay)
}
ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.SESSION -> {
else -> {
if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) {
SettingsRow(stringResource(R.string.drawer_launch_app), null) {
DrawerOutlineButton(if (androidAppsExpanded) stringResource(R.string.common_hide) else stringResource(R.string.common_show), modifier = focus.track(page, "apps")) {
@@ -502,7 +466,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SettingsGroup(stringResource(R.string.drawer_session_behavior)) {
ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend),
null,
stringResource(R.string.drawer_suspend_hint),
listOf(
SessionPrefs.SUSPEND_AUTO to stringResource(R.string.common_auto),
SessionPrefs.SUSPEND_MANUAL to stringResource(R.string.mode_suspend_manual),
@@ -514,6 +478,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
onPick = a.onSuspendPolicy,
)
}
SettingsGroup(stringResource(R.string.drawer_next_session)) {
ChoiceRow(host, "shape", stringResource(R.string.mode_ratio), null,
SessionPrefs.shapeChoices, a.shapeMode,
chipModifier = focus.track(page, "shape"), onPick = a.onShape)
}
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) {
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), stringResource(R.string.fex_next_launch),
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
GameEnvironmentRow(modifier = focus.track(page, "game-env"))
}
SettingsGroup(stringResource(R.string.drawer_support)) {
SettingsRow(stringResource(R.string.drawer_logs), stringResource(R.string.drawer_logs_hint)) {
DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs")) {
@@ -526,11 +501,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
a.pipAutoEnter, onChange = a.onPipAutoEnter)
}
Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (a.pipSupported) DrawerActionButton(stringResource(R.string.pip_title), Icons.Outlined.PictureInPictureAlt,
modifier = focus.track(page, "pip")) { host.open = null; a.onPip() }
if (!a.isHomeApp) DrawerActionButton(stringResource(R.string.drawer_background), Icons.AutoMirrored.Outlined.ExitToApp,
modifier = focus.track(page, "background")) { host.open = null; a.onBackground() }
Spacer(Modifier.height(18.dp))
if (a.pipSupported) DrawerOutlineButton(stringResource(R.string.pip_title), modifier = focus.track(page, "pip")) {
host.open = null; a.onPip()
}
if (!a.isHomeApp) DrawerOutlineButton(stringResource(R.string.drawer_background), modifier = focus.track(page, "background")) {
host.open = null; a.onBackground()
}
}
}
@@ -570,27 +546,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
}
@Composable
private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(8.dp)
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = modifier.fillMaxWidth().heightIn(min = 52.dp).clip(shape)
.background(if (hot) pal.signal.copy(alpha = 0.16f) else colors.surfaceVariant)
.glideBorder(hot, shape, pal.signal)
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, onClick = onClick)
.controllerConfirm(onClick = onClick).padding(horizontal = 16.dp, vertical = 10.dp),
) {
Icon(icon, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(22.dp))
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
}
}
@Composable
private fun DrawerOutlineButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -681,60 +636,58 @@ private fun DrawerBumper(label: String, description: String, modifier: Modifier
/**
* The drawer's page tabs, QAM-style: one icon per page standing in a line in page order. The
* selected one steps forward - full size, bright, a soft glow - while the others step back to
* a little smaller and fade, and the whole line leans a little toward the selection. LB / RB still turn
* half size and fade, and the whole line leans a little toward the selection. LB / RB still turn
* the page (the buttons beside it and the pad's bumpers); a tab can be tapped or picked with the
* pad like the dots it replaces.
*/
@Composable
private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPage>, modifier: Modifier = Modifier, compact: Boolean = false, onSelect: (SessionDrawerPage) -> Unit) {
private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, compact: Boolean = false, onSelect: (Int) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val count = pages.size
val selectedIndex = pages.indexOf(page)
val count = drawerPageIcons.size
val middle = (count - 1) / 2f
val motion = Motion.tw<Float>(340, easing = FastOutSlowInEasing)
androidx.compose.foundation.layout.BoxWithConstraints(
contentAlignment = Alignment.Center,
modifier = modifier.height(if (compact) 44.dp else 64.dp).clipToBounds(),
) {
val tab = if (compact) 36f else 44f
val tab = if (compact) 40f else 56f
// Fit the line to the room between LB and RB. Worst case is an end tab selected: full size
// ([tab] dp) and pushed outward by the lean, which scales with the spacing. So
// (count-1) * spacing * (1 + lean/spacingMax) + tab <= width
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(24f, DRAWER_TAB_SPACING_DP)
// (count-1) * spacing * (1 + lean/64) + 56 <= width
// - never more than the mock's 64 dp, never tighter than 32 dp.
val spacing = ((maxWidth.value - tab) / ((count - 1) * (1f + DRAWER_TAB_LEAN_DP / DRAWER_TAB_SPACING_DP))).coerceIn(32f, DRAWER_TAB_SPACING_DP)
val leanStep = DRAWER_TAB_LEAN_DP * spacing / DRAWER_TAB_SPACING_DP
val lean by animateFloatAsState(-(selectedIndex - middle) * leanStep, motion, label = "tabLean")
pages.forEachIndexed { index, item ->
androidx.compose.runtime.key(item) {
val selected = item == page
val source = remember { MutableInteractionSource() }
val focused = source.collectIsFocusedAsState().value
val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale")
val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha")
val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow")
val pageDescription = stringResource(R.string.drawer_page_desc, stringResource(item.title))
val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, Motion.tw(340, easing = FastOutSlowInEasing), label = "tabTint")
val select = { onSelect(item) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset(x = ((index - middle) * spacing + lean).dp)
.size(tab.dp)
.graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha }
.clip(RoundedCornerShape(16.dp))
.background(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent),
),
)
.glideBorder(focused, RoundedCornerShape(16.dp), colors.onBackground)
.semantics { contentDescription = pageDescription }
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Icon(item.icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
}
val lean by animateFloatAsState(-(page - middle) * leanStep, motion, label = "tabLean")
drawerPageIcons.forEachIndexed { index, icon ->
val selected = index == page
val source = remember { MutableInteractionSource() }
val focused = source.collectIsFocusedAsState().value
val scale by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_SCALE, motion, label = "tabScale")
val alpha by animateFloatAsState(if (selected) 1f else DRAWER_TAB_SIDE_ALPHA, motion, label = "tabAlpha")
val glow by animateFloatAsState(if (selected) 1f else 0f, motion, label = "tabGlow")
val pageDescription = stringResource(R.string.drawer_page_desc, stringResource(drawerPageTitles[index]))
val tint by animateColorAsState(if (selected) colors.onBackground else colors.onSurfaceVariant, Motion.tw(340, easing = FastOutSlowInEasing), label = "tabTint")
val select = { onSelect(index) }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.offset(x = ((index - middle) * spacing + lean).dp)
.size(tab.dp)
.graphicsLayer { scaleX = scale; scaleY = scale; this.alpha = alpha }
.clip(RoundedCornerShape(16.dp))
.background(
Brush.radialGradient(
listOf(pal.signal.copy(alpha = 0.34f * glow), pal.signal.copy(alpha = 0.10f * glow), Color.Transparent),
),
)
.glideBorder(focused, RoundedCornerShape(16.dp), colors.onBackground)
.semantics { contentDescription = pageDescription }
.hoverable(source)
.clickable(interactionSource = source, indication = LocalIndication.current, onClick = select)
.controllerConfirm(onClick = select),
) {
Icon(icon, contentDescription = null, tint = tint, modifier = Modifier.size(if (compact) 22.dp else 30.dp))
}
}
}
@@ -743,114 +696,54 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
/** The Look row's value when the rows below match no Look. */
private const val LOOK_CUSTOM = "custom"
/** Presets and simple effects first; detailed adjustments stay behind Advanced. */
/**
* Screen effects on the Effects page: a Look row that moves every row under it, then the rows
* themselves: switches and sliders the d-pad steps (SliderRow), so a pad drives them.
*/
@Composable
private fun ScreenEffectsGroup(
host: MenuHost, a: DrawerActions, advancedExpanded: Boolean, onAdvancedToggle: () -> Unit,
track: (String) -> Modifier,
) {
private fun ScreenEffectsGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val e = a.effects
val preset = ScreenEffectLooks.match(e, a.upscaler)
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val look = ScreenEffectLooks.match(e, a.upscaler)
SettingsGroup(stringResource(R.string.drawer_effects)) {
val presets = ScreenEffectLooks.LOOKS.map { it.name to it.name }
ChoiceRow(host, "look", stringResource(R.string.drawer_look), null,
if (preset == null) listOf(LOOK_CUSTOM to stringResource(R.string.drawer_look_custom)) + presets else presets,
preset?.name ?: LOOK_CUSTOM, chipModifier = track("look")) { name ->
val looks = ScreenEffectLooks.LOOKS.map { it.name to it.name }
ChoiceRow(host, "look", stringResource(R.string.drawer_look),
look?.desc ?: stringResource(R.string.drawer_effects_hint),
if (look == null) listOf(LOOK_CUSTOM to stringResource(R.string.drawer_look_custom)) + looks else looks,
look?.name ?: LOOK_CUSTOM, chipModifier = track("look"), hintLines = 2) { name ->
ScreenEffectLooks.LOOKS.firstOrNull { it.name == name }?.let { picked ->
picked.scalingMode?.let(a.onUpscaler)
a.onEffects(picked.effects)
}
}
ToggleRow(host, "cas", stringResource(R.string.drawer_cas), null, e.cas, chipModifier = track("cas")) { a.onEffects(e.copy(cas = it)) }
SliderRow(stringResource(R.string.drawer_cas_level), null, e.casLevel, 0..100, step = 5, enabled = e.cas,
format = { "$it%" }, modifier = track("cas-level")) { a.onEffects(e.copy(casLevel = it)) }
ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) }
ToggleRow(host, "deband", stringResource(R.string.drawer_deband), null, e.deband, chipModifier = track("deband")) { a.onEffects(e.copy(deband = it)) }
SliderRow(stringResource(R.string.drawer_deband_strength), null, e.debandStrength, 0..200, step = 5, enabled = e.deband,
format = { "$it%" }, modifier = track("deband-strength")) { a.onEffects(e.copy(debandStrength = it)) }
SliderRow(stringResource(R.string.drawer_brightness), null, e.brightness, -100..100, step = 2,
format = ::signed, modifier = track("brightness")) { a.onEffects(e.copy(brightness = it)) }
SliderRow(stringResource(R.string.drawer_contrast), null, e.contrast, -100..100, step = 2,
format = ::signed, modifier = track("contrast")) { a.onEffects(e.copy(contrast = it)) }
SliderRow(stringResource(R.string.drawer_gamma), null, (e.gamma * 100f).roundToInt(), 50..300, step = 5,
format = { String.format(Locale.US, "%.2f", it / 100f) }, modifier = track("gamma")) { a.onEffects(e.copy(gamma = it / 100f)) }
SliderRow(stringResource(R.string.drawer_saturation), null, e.saturation, 0..200, step = 5,
format = { "$it%" }, modifier = track("saturation")) { a.onEffects(e.copy(saturation = it)) }
ToggleRow(host, "fxaa", stringResource(R.string.drawer_fxaa), null, e.fxaa, chipModifier = track("fxaa")) { a.onEffects(e.copy(fxaa = it)) }
ToggleRow(host, "toon", stringResource(R.string.drawer_toon), null, e.toon, chipModifier = track("toon")) { a.onEffects(e.copy(toon = it)) }
ToggleRow(host, "crt", stringResource(R.string.drawer_crt), null, e.crt, chipModifier = track("crt")) { a.onEffects(e.copy(crt = it)) }
ToggleRow(host, "ntsc", stringResource(R.string.drawer_ntsc), null, e.ntsc, chipModifier = track("ntsc")) { a.onEffects(e.copy(ntsc = it)) }
ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) }
}
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val rotation by animateFloatAsState(if (advancedExpanded) 180f else 0f, Motion.tw(180), label = "advancedArrow")
val description = stringResource(if (advancedExpanded) R.string.widgets_expanded else R.string.widgets_collapsed)
val toggle = { host.open = null; onAdvancedToggle() }
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = track("effects-advanced").fillMaxWidth().padding(top = 12.dp).heightIn(min = 48.dp)
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(source).clickable(interactionSource = source, indication = LocalIndication.current, role = Role.Button, onClick = toggle)
.controllerConfirm(onClick = toggle).semantics { stateDescription = description }.padding(horizontal = 4.dp),
) {
Text(stringResource(R.string.drawer_effects_advanced).uppercase(), fontSize = 12.sp,
fontWeight = FontWeight.SemiBold, letterSpacing = 1.5.sp, color = colors.onSurfaceVariant)
Box(Modifier.weight(1f).height(1.dp).background(pal.line))
Icon(Icons.Outlined.ExpandMore, contentDescription = null, tint = colors.onSurfaceVariant,
modifier = Modifier.size(22.dp).rotate(rotation))
}
AnimatedVisibility(advancedExpanded) {
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(colors.surface).border(1.dp, pal.line, RoundedCornerShape(14.dp))) {
ToggleRow(host, "cas", stringResource(R.string.drawer_cas), null, e.cas, chipModifier = track("cas")) { a.onEffects(e.copy(cas = it)) }
if (e.cas) SliderRow(stringResource(R.string.drawer_cas_level), null, e.casLevel, 0..100, step = 5,
format = { "$it%" }, modifier = track("cas-level")) { a.onEffects(e.copy(casLevel = it)) }
ToggleRow(host, "deband", stringResource(R.string.drawer_deband), null, e.deband, chipModifier = track("deband")) { a.onEffects(e.copy(deband = it)) }
if (e.deband) SliderRow(stringResource(R.string.drawer_deband_strength), null, e.debandStrength, 0..200, step = 5,
format = { "$it%" }, modifier = track("deband-strength")) { a.onEffects(e.copy(debandStrength = it)) }
SliderRow(stringResource(R.string.drawer_brightness), null, e.brightness, -100..100, step = 2,
format = ::signed, modifier = track("brightness")) { a.onEffects(e.copy(brightness = it)) }
SliderRow(stringResource(R.string.drawer_contrast), null, e.contrast, -100..100, step = 2,
format = ::signed, modifier = track("contrast")) { a.onEffects(e.copy(contrast = it)) }
SliderRow(stringResource(R.string.drawer_gamma), null, (e.gamma * 100f).roundToInt(), 50..300, step = 5,
format = { String.format(Locale.US, "%.2f", it / 100f) }, modifier = track("gamma")) { a.onEffects(e.copy(gamma = it / 100f)) }
SliderRow(stringResource(R.string.drawer_saturation), null, e.saturation, 0..200, step = 5,
format = { "$it%" }, modifier = track("saturation")) { a.onEffects(e.copy(saturation = it)) }
}
}
}
/** Secondary-display modes are mutually exclusive and apply immediately. */
@Composable
private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val modes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
Column(Modifier.fillMaxWidth().selectableGroup()) {
modes.forEach { mode ->
val selected = a.secondScreenMode == mode
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val pick = { host.open = null; a.onSecondScreenMode(mode) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = track("second-screen:${mode.id}").fillMaxWidth().heightIn(min = 56.dp)
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(source)
.selectable(selected, interactionSource = source, indication = null, role = Role.RadioButton, onClick = pick)
.controllerConfirm(onClick = pick)
.padding(horizontal = 14.dp, vertical = 8.dp),
) {
Text(mode.label, fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
RadioButton(selected, onClick = null,
colors = RadioButtonDefaults.colors(selectedColor = pal.signal, unselectedColor = colors.onSurfaceVariant))
}
}
}
if (a.secondScreenDisplays.size > 1) ChoiceRow(host, "second-screen-display", stringResource(R.string.drawer_page_display), null,
a.secondScreenDisplays.map { it.id to it.label }, a.selectedSecondScreenDisplay,
chipModifier = track("second-screen-display"), onPick = a.onSecondScreenDisplay)
}
}
/** Texture filtering on the Games page: DXVK options for the next DirectX 9-11 launch. */
/** Texture filtering on the Effects page: DXVK options for the next DirectX 9-11 launch. */
@Composable
private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
SettingsGroup(stringResource(R.string.drawer_texture)) {
ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), null,
ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), stringResource(R.string.drawer_texture_hint),
SessionPrefs.textureAnisotropyChoices, a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy)
ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), null,
ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), stringResource(R.string.drawer_texture_hint),
SessionPrefs.textureLodBiasChoices, a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
chipModifier = track("texture-sharpness"), onPick = a.onTextureLodBias)
}
@@ -858,8 +751,16 @@ private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (Stri
private fun signed(v: Int) = if (v > 0) "+$v" else "$v"
/** Display, Effects, Controls, Components, Settings. */
const val DRAWER_PAGES = 5
private const val DRAWER_PAGE_EFFECTS = 1
private const val DRAWER_PAGE_CONTROLS = 2
private const val DRAWER_PAGE_COMPONENTS = 3
/**
* The Games tab's components: quick swaps between what is already installed, per Proton. A swap
* The drawer's Components tab: quick swaps between what is already installed, per Proton. A swap
* into the Proton a running game uses waits until that game closes; downloading, importing and
* deleting stay on the Components page in the app.
*/
@@ -983,14 +884,14 @@ private fun <T> DrawerStackedChoice(
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
/** A close row of icons: inactive tabs stay legible while the active tab leads. */
private const val DRAWER_TAB_SPACING_DP = 48f
/** The tab row's measure, from the approved mock: side tabs at half size, a little faded. */
private const val DRAWER_TAB_SPACING_DP = 64f
private const val DRAWER_TAB_LEAN_DP = 8f
private const val DRAWER_TAB_LEAN_DP = 12f
private const val DRAWER_TAB_SIDE_SCALE = 0.8f
private const val DRAWER_TAB_SIDE_SCALE = 0.5f
private const val DRAWER_TAB_SIDE_ALPHA = 0.8f
private const val DRAWER_TAB_SIDE_ALPHA = 0.7f
/** Room between the Stop pill and the box that steps out under it: the pull. */
private val StepPull = 6.dp
@@ -29,7 +29,6 @@ import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
@@ -61,7 +60,6 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -84,10 +82,6 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.semantics.progressBarRangeInfo
import androidx.compose.ui.semantics.setProgress
import androidx.compose.ui.semantics.disabled
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.text.style.TextAlign
import kotlin.math.roundToInt
import androidx.compose.ui.input.InputMode
@@ -474,16 +468,8 @@ fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = nul
fun SliderRow(
label: String, hint: String?, value: Int, range: IntRange, step: Int = 1, enabled: Boolean = true,
format: (Int) -> String = { it.toString() }, modifier: Modifier = Modifier, onChange: (Int) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth()) {
ValueSlider(value, range, step, enabled, label, format,
modifier = modifier.padding(horizontal = 6.dp, vertical = 3.dp), onChange = onChange)
if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 14.dp, end = 14.dp, bottom = 8.dp))
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
) = SettingsRow(label, hint) {
ValueSlider(value, range, step, enabled, label, format, modifier, onChange)
}
@Composable
@@ -493,39 +479,34 @@ fun ValueSlider(
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val currentOnChange by rememberUpdatedState(onChange)
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val span = (range.last - range.first).coerceAtLeast(1)
val fraction = ((value - range.first).toFloat() / span).coerceIn(0f, 1f)
val thumbInset = with(LocalDensity.current) { 8.dp.toPx() }
val shape = RoundedCornerShape(99.dp)
var trackPx by remember { mutableIntStateOf(0) }
val text = format(value)
val shape = RoundedCornerShape(8.dp)
// Preserve off-grid preset values until the user adjusts; every input snaps to the same step.
// A step from the d-pad lands on the grid of [step] from the range's start; a Look's own
// value, which need not be on it, is kept until the user moves.
fun stepped(v: Int) = (((v - range.first).toFloat() / step).roundToInt() * step + range.first).coerceIn(range.first, range.last)
fun fromX(x: Float) {
val width = trackPx - 2 * thumbInset
if (width > 0) {
val position = ((x - thumbInset) / width).coerceIn(0f, 1f)
currentOnChange(stepped(range.first + (position * span).roundToInt()))
}
}
Column(
modifier = modifier.fillMaxWidth().heightIn(min = 72.dp)
.clip(shape).background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.glideBorder(hot, shape, pal.signal)
fun fromX(x: Float) { if (trackPx > 0) onChange(stepped(range.first + (x / trackPx * span).roundToInt())) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.heightIn(min = 48.dp)
.alpha(if (enabled) 1f else 0.5f)
.hoverable(source).focusable(enabled, source)
.hoverable(src)
.focusable(enabled, src)
.onPreviewKeyEvent { event ->
val keyEvent = event.nativeKeyEvent
val left = keyEvent.keyCode == KeyEvent.KEYCODE_DPAD_LEFT
if (!left && keyEvent.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) false
else {
// Repeated key-down events let a held direction keep adjusting.
if (!left && keyEvent.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) {
false
} else {
// Every down counts, repeats included, so a held direction keeps stepping.
if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN) {
val next = stepped(value + if (left) -step else step)
if (next != value) currentOnChange(next)
if (next != value) onChange(next)
}
true
}
@@ -534,33 +515,28 @@ fun ValueSlider(
stateDescription = text
progressBarRangeInfo = ProgressBarRangeInfo(value.toFloat(), range.first.toFloat()..range.last.toFloat())
if (label != null) contentDescription = label
if (!enabled) disabled()
setProgress { next ->
if (!enabled) false else { currentOnChange(stepped(next.roundToInt())); true }
}
}
.padding(horizontal = 8.dp, vertical = 6.dp),
},
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
if (label != null) Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold,
color = colors.onBackground, modifier = Modifier.weight(1f))
else Spacer(Modifier.weight(1f))
Text(text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
}
Canvas(
Modifier.fillMaxWidth().height(40.dp).onSizeChanged { trackPx = it.width }
.pointerInput(enabled, range, step, thumbInset) { if (enabled) detectTapGestures { fromX(it.x) } }
.pointerInput(enabled, range, step, thumbInset) {
Text(text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, textAlign = TextAlign.End,
maxLines = 1, modifier = Modifier.width(56.dp))
Spacer(Modifier.width(10.dp))
Box(
contentAlignment = Alignment.CenterStart,
modifier = Modifier.size(width = 164.dp, height = 30.dp).clip(shape).background(colors.surfaceVariant)
.glideBorder(hot, shape, colors.onBackground, pal.line2)
.onSizeChanged { trackPx = it.width }
.pointerInput(enabled, range, step) { if (enabled) detectTapGestures { fromX(it.x) } }
.pointerInput(enabled, range, step) {
if (enabled) detectHorizontalDragGestures { change, _ -> fromX(change.position.x); change.consume() }
},
) {
val start = Offset(thumbInset, size.height / 2f)
val end = Offset(size.width - thumbInset, start.y)
val thumb = Offset(start.x + (end.x - start.x) * fraction, start.y)
val fill = if (hot) pal.signal else colors.onBackground
drawLine(colors.onSurfaceVariant.copy(alpha = 0.35f), start, end, strokeWidth = 4.dp.toPx(), cap = StrokeCap.Round)
if (fraction > 0) drawLine(fill, start, thumb, strokeWidth = 4.dp.toPx(), cap = StrokeCap.Round)
drawCircle(fill, radius = 7.dp.toPx(), center = thumb)
Box(Modifier.fillMaxWidth(fraction).fillMaxHeight().background(pal.signal))
Box(
Modifier.padding(4.dp).size(22.dp)
.graphicsLayer { translationX = fraction * (trackPx - 30.dp.toPx()).coerceAtLeast(0f) }
.clip(CircleShape)
.background(pal.onSignal),
)
}
}
}
@@ -608,9 +584,6 @@ fun SettingsPage(
scroll: androidx.compose.foundation.ScrollState? = null,
scrollContent: Boolean = true,
compactLayout: Boolean = false,
/** Controls that remain below the title while the settings scroll, such as a tab strip. */
header: (@Composable () -> Unit)? = null,
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit,
) {
val scrollState = scroll ?: rememberScrollState()
@@ -618,7 +591,7 @@ fun SettingsPage(
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
val narrow = LocalNarrowPane.current && !compactLayout
Column(
modifier = modifier.fillMaxSize().padding(
modifier = Modifier.fillMaxSize().padding(
horizontal = if (compactLayout) 14.dp else if (narrow) 16.dp else 22.dp,
vertical = if (compactLayout) 6.dp else if (narrow) 12.dp else 18.dp,
),
@@ -683,7 +656,6 @@ fun SettingsPage(
}
}
}
if (header != null) header()
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
Column(
modifier = Modifier
@@ -78,6 +78,8 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
var openApp by rememberSaveable { mutableStateOf<String?>(null) }
var query by rememberSaveable { mutableStateOf("") }
var category by rememberSaveable { mutableStateOf<String?>(null) }
// Which store the page shows: Flathub's apps, or the user's GOG games.
var store by rememberSaveable { mutableStateOf("flathub") }
LaunchedEffect(s.ready) { StoreState.refresh(ctx) }
LaunchedEffect(Unit) { StoreState.loadSections() }
// A pad's focus sits on something the page is about to replace - the tile that opens an app,
@@ -105,8 +107,8 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
Column(
modifier = modifier.verticalScroll(scroll).padding(horizontal = padH, vertical = padV)
.bumpers(onPrevious = { if (openApp == null) switchTab((tab + TABS.size - 1) % TABS.size) },
onNext = { if (openApp == null) switchTab((tab + 1) % TABS.size) }),
.bumpers(onPrevious = { if (openApp == null && store == "flathub") switchTab((tab + TABS.size - 1) % TABS.size) },
onNext = { if (openApp == null && store == "flathub") switchTab((tab + 1) % TABS.size) }),
) {
val id = openApp
if (id != null) {
@@ -115,10 +117,25 @@ internal fun StorePage(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
}
Rise(0) {
PageHeader(stringResource(R.string.store_title)) {
Chip(stringResource(R.string.store_chip_flathub), ok = false)
if (StoreState.ready) Chip(stringResource(R.string.store_chip_ready), ok = true)
if (store == "gog") {
Chip("GOG", ok = false)
if (com.droiddeck.launcher.store.gog.GogState.signedIn) Chip("Signed in", ok = true)
} else {
Chip(stringResource(R.string.store_chip_flathub), ok = false)
if (StoreState.ready) Chip(stringResource(R.string.store_chip_ready), ok = true)
}
}
}
Rise(0) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 10.dp)) {
PillButton("Flathub", selected = store == "flathub") { store = "flathub" }
PillButton("GOG", selected = store == "gog") { store = "gog" }
}
}
if (store == "gog") {
GogStore(s)
return@Column
}
if (!s.ready) {
Rise(1) { Note(stringResource(R.string.store_needs_runtime)) }
return@Column
@@ -115,11 +115,6 @@ public final class WaylandCompositor {
public static void setPointerLockListener(PointerLockListener l) { pointerLockListener = l; }
/** Unhooks {@code l} only if it is still the listener, so a finishing activity never unhooks its successor's. */
public static void clearPointerLockListener(PointerLockListener l) {
if (pointerLockListener == l) pointerLockListener = null;
}
/** Invoked from native (droiddeck_on_pointer_lock). */
@SuppressWarnings("unused")
static void onPointerLock(boolean locked, int x, int y) {
@@ -505,11 +500,4 @@ public final class WaylandCompositor {
if (dx == 0 && dy == 0) return;
nativeSendSceneInput(6, dx * 256, dy * 256);
}
/** As {@link #sendPointerDelta(int, int)}, keeping a captured mouse's fractions of a pixel. */
public static void sendPointerDelta(float dx, float dy) {
int x = Math.round(dx * 256f), y = Math.round(dy * 256f);
if (x == 0 && y == 0) return;
nativeSendSceneInput(6, x, y);
}
}
+1 -31
View File
@@ -291,10 +291,6 @@
<string name="mode_branch_public">Public beta</string>
<string name="mode_branch_deck_beta">Steam Deck public beta</string>
<string name="mode_branch_note">Deck mode always uses Steam Deck public beta.</string>
<string name="mode_steam_repair">Repair Steam client</string>
<string name="mode_steam_repair_hint">Downloads the Steam client again the next time Steam starts. Use it if Steam stays on its loading screen. Games, sign-in and settings are kept.</string>
<string name="mode_steam_repair_queued">The Steam client will be downloaded again the next time Steam starts.</string>
<string name="mode_steam_repair_button">Repair</string>
<string name="mode_added_games">Added games</string>
<string name="mode_added_none">no game folders with a .exe found</string>
<string name="mode_games_folder">Games folder</string>
@@ -474,7 +470,6 @@
<string name="drawer_page_effects">Effects</string>
<string name="drawer_page_controls">Controls</string>
<string name="drawer_page_components">Components</string>
<string name="drawer_page_controller">Controller</string>
<string name="drawer_page_settings">Settings</string>
<string name="drawer_page_desc">%1$s page</string>
<string name="drawer_steam">Steam</string>
@@ -490,11 +485,8 @@
<string name="drawer_scaling_sharpness">Scaling sharpness</string>
<string name="drawer_effects">Screen effects</string>
<string name="drawer_effects_hint">Live. Costs a little GPU time while any effect is on.</string>
<string name="drawer_look">Presets</string>
<string name="drawer_look">Look</string>
<string name="drawer_look_custom">Custom</string>
<string name="drawer_effects_advanced">Advanced</string>
<string name="widgets_expanded">Expanded</string>
<string name="widgets_collapsed">Collapsed</string>
<string name="drawer_cas">Sharpening (CAS)</string>
<string name="drawer_cas_level">Sharpening level</string>
<string name="drawer_fake_hdr">Fake HDR</string>
@@ -518,7 +510,6 @@
<string name="drawer_pc_keyboard">PC keyboard</string>
<string name="drawer_android_keyboard">Android</string>
<string name="drawer_second_screen">Second screen</string>
<string name="drawer_second_screen_mode">Mode</string>
<string name="drawer_second_screen_shows">Shows</string>
<string name="drawer_android_apps">Android apps</string>
<string name="drawer_launch_app">Launch an app</string>
@@ -1020,25 +1011,4 @@
<string name="game_file_folder">Choose a folder for frontend game files</string>
<string name="game_file_exported">Game files saved to %1$s</string>
<string name="game_frontend_files">Frontend files</string>
<string name="display_session">Session display</string>
<string name="display_resolution">Resolution</string>
<string name="display_game_fit">16:9 game fit</string>
<string name="display_game_fit_hint">How 16:9 games fit this display. Next session.</string>
<string name="display_game_fit_unavailable">Choose Match screen or a custom size narrower than 16:9.</string>
<string name="display_preserve">Keep proportions</string>
<string name="display_stretch">Stretch to display</string>
<string name="display_image_scaling">Image scaling</string>
<string name="display_filter">Scaling filter</string>
<string name="display_filter_hint">Shared by Steam and Desktop.</string>
<string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string>
<string name="display_filter_note">FSR, GSR and NIS apply when enlarging the session image. Sharpen only also works without enlargement.</string>
<string name="display_sharpness">Filter sharpness</string>
<string name="display_frame_rate">Frame rate</string>
<string name="display_window_compatibility">Game window compatibility</string>
<string name="display_force_fullscreen">Force game windows fullscreen</string>
<string name="display_force_fullscreen_hint">Keeps games fullscreen after focus changes. Turn off if a game draws small. Applies live during a session.</string>
<string name="display_force_fullscreen_live">Keeps games fullscreen after focus changes. Applies live.</string>
<string name="display_look_filter">%1$s Sets scaling to %2$s.</string>
<string name="display_match_screen">Match screen (%1$d×%2$d)</string>
<string name="mode_tab_steam">Steam</string>
</resources>
@@ -1,53 +0,0 @@
package com.droiddeck.launcher.input
import java.io.File
import java.nio.file.Files
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
/**
* The ring paths handed to the guest (FAKE_EVDEV_MEMFD_PATHS) must keep the spelling the session
* tree is bound under. On ColorOS 16 /data/user/0 resolves to /data/data, the guest only has the
* first bound, and a canonical export left every pad dead (#166). A symlinked directory stands in
* for that here.
*/
class FakeInputRingPathTest {
private lateinit var base: File
private lateinit var real: File
private lateinit var link: File
@Before fun setUp() {
base = Files.createTempDirectory("ring-path").toFile()
real = File(base, "data-data").apply { mkdirs() }
link = File(base, "data-user-0")
Files.createSymbolicLink(link.toPath(), real.toPath())
}
@After fun tearDown() {
base.deleteRecursively()
}
@Test fun ringsSitBesideTheFakeInputNodes() {
val fakeInputDir = File(link, "files/session/dev/input")
assertEquals(File(link, "files/session/dev/fakeinput-rings/ring2"), FakeInputRingPaths.ringFile(fakeInputDir, 2))
}
@Test fun theExportKeepsTheBoundSpellingThroughALinkedDataDirectory() {
val fakeInputDir = File(link, "files/session/dev/input").apply { mkdirs() }
val ring = FakeInputRingPaths.ringFile(fakeInputDir, 0)!!.apply { parentFile!!.mkdirs(); writeText("") }
// The link really does resolve elsewhere, as /data/user/0 does on the affected devices.
assertTrue(ring.canonicalPath.startsWith(real.canonicalPath + "/"))
val exported = FakeInputRingPaths.exportPath(ring)
assertEquals(File(link, "files/session/dev/fakeinput-rings/ring0").path, exported)
assertFalse("$exported resolved through the link", exported.startsWith(real.path + "/"))
assertTrue("$exported does not open", File(exported).isFile)
}
@Test fun aRelativeInputDirIsExportedAbsolute() {
val exported = FakeInputRingPaths.exportPath(FakeInputRingPaths.ringFile(File("session/dev/input"), 1)!!)
assertTrue(exported, File(exported).isAbsolute)
assertTrue(exported, exported.endsWith("/session/dev/fakeinput-rings/ring1"))
}
}
@@ -1,84 +0,0 @@
package com.droiddeck.launcher.runtime
import java.io.File
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class DeckyPluginInstallTest {
@get:Rule val temporary = TemporaryFolder()
private fun plugin(parent: File, folder: String, name: String): File = File(parent, folder).apply {
mkdirs(); File(this, "plugin.json").writeText(JSONObject().put("name", name).toString())
}
@Test fun renamedFolderReplacesByIdentityAndPreservesDataAndOrder() {
val home = temporary.newFolder()
val plugins = File(home, "plugins").apply { mkdirs() }
val old = plugin(plugins, "old-folder", "Unifideck")
val data = File(home, "data/old-folder/save").apply { parentFile.mkdirs(); writeText("keep") }
val settings = File(home, "settings/loader.json").apply {
parentFile.mkdirs()
writeText("""{"pluginOrder":["Other","Unifideck"],"hiddenPlugins":["Unifideck","Other"],"disabled_plugins":["Unifideck"],"store":2}""")
}
val staged = plugin(temporary.newFolder(), "Unifideck", "Unifideck")
DeckyPluginInstall.activate(staged, plugins, "Unifideck", settings, ".test")
assertFalse(old.exists())
assertTrue(File(plugins, "Unifideck/plugin.json").exists())
assertEquals("keep", data.readText())
val state = JSONObject(settings.readText())
assertEquals("[\"Other\",\"Unifideck\"]", state.getJSONArray("pluginOrder").toString())
assertEquals("[\"Other\"]", state.getJSONArray("hiddenPlugins").toString())
assertEquals(0, state.getJSONArray("disabled_plugins").length())
assertEquals(2, state.getInt("store"))
}
@Test fun newImportAppendsOnceAndReimportKeepsItsPosition() {
val plugins = temporary.newFolder()
val settings = File(temporary.newFolder(), "loader.json").apply { writeText("""{"pluginOrder":["Other"]}""") }
repeat(2) {
DeckyPluginInstall.activate(plugin(temporary.newFolder(), "Unifideck", "Unifideck"), plugins, "Unifideck", settings, ".test")
}
assertEquals("[\"Other\",\"Unifideck\"]", JSONObject(settings.readText()).getJSONArray("pluginOrder").toString())
}
@Test fun conflictingFolderLeavesInstalledPluginAndSettingsUntouched() {
val plugins = temporary.newFolder()
plugin(plugins, "Unifideck", "Other")
val settings = File(temporary.newFolder(), "loader.json").apply { writeText("{}") }
try {
DeckyPluginInstall.activate(plugin(temporary.newFolder(), "Unifideck", "Unifideck"), plugins, "Unifideck", settings, ".test")
fail("Expected conflicting identity to fail")
} catch (_: IllegalArgumentException) {}
assertEquals("{}", settings.readText())
assertEquals("Other", JSONObject(File(plugins, "Unifideck/plugin.json").readText()).getString("name"))
}
@Test fun firstLoaderSettingsIncludeExistingPlugins() {
val plugins = temporary.newFolder()
plugin(plugins, "Other", "Other")
val settings = File(temporary.newFolder(), "loader.json")
DeckyPluginInstall.activate(plugin(temporary.newFolder(), "Unifideck", "Unifideck"), plugins, "Unifideck", settings, ".test")
assertEquals("[\"Other\",\"Unifideck\"]", JSONObject(settings.readText()).getJSONArray("pluginOrder").toString())
}
@Test fun activationFailureRestoresPreviousPlugin() {
val plugins = temporary.newFolder()
val old = plugin(plugins, "Unifideck", "Unifideck")
File(old, "old-version").writeText("keep")
// An empty staged directory makes the plugin activation fail after backing up the old one.
val staged = plugin(temporary.newFolder(), "Unifideck", "Unifideck")
staged.deleteRecursively()
val settings = File(temporary.newFolder(), "loader.json").apply { writeText("{}") }
try {
DeckyPluginInstall.activate(staged, plugins, "Unifideck", settings, ".test")
fail("Expected activation to fail")
} catch (_: IllegalStateException) {}
assertEquals("keep", File(old, "old-version").readText())
assertEquals("{}", settings.readText())
}
}
@@ -8,7 +8,6 @@ import android.os.Looper
import android.os.Vibrator
import android.os.VibratorManager
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.PadBridge
import java.io.IOException
import org.junit.After
import org.junit.Before
@@ -69,74 +68,12 @@ class RumbleComponentTest {
assertTrue(shadowOf(vibrator).isVibrating)
}
@Test fun aControllerWithMotorsGetsTheEffectInsteadOfThePhone() {
val pad = FakeMotors()
rumble.controllerMotors = { id -> if (id == PAD_ID) pad else null }
activeController(PAD_ID)
effect(strong = 40000, weak = 1000)
assertEquals(listOf(Triple(40000, 1000, 5000L)), pad.played)
assertFalse("the phone buzzed as well", shadowOf(vibrator).isVibrating)
private fun effect() {
// Inject a decoded force-feedback packet; transport is outside this preference test.
RumbleComponent::class.java.getDeclaredMethod("buzz", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(rumble, 65535, 5000)
}
@Test fun aControllerWithoutMotorsFallsBackToThePhone() {
rumble.controllerMotors = { null }
activeController(PAD_ID)
effect()
assertTrue(shadowOf(vibrator).isVibrating)
}
@Test fun theOnScreenPadTakingOverMovesTheEffectBackToThePhone() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect()
assertTrue(pad.vibrating)
activeController(PadBridge.NO_CONTROLLER)
effect()
assertFalse("the controller kept rumbling after the switch", pad.vibrating)
assertTrue(shadowOf(vibrator).isVibrating)
}
@Test fun aStopPacketDisablingAndStoppingAllEndTheControllersEffect() {
val pad = FakeMotors()
rumble.controllerMotors = { pad }
activeController(PAD_ID)
effect()
effect(strong = 0, weak = 0)
assertFalse(pad.vibrating)
effect()
ControllerPrefs.setRumble(context, false)
shadowOf(Looper.getMainLooper()).idle()
assertFalse(pad.vibrating)
ControllerPrefs.setRumble(context, true)
shadowOf(Looper.getMainLooper()).idle()
effect()
rumble.stop()
assertFalse(pad.vibrating)
}
@After fun clearActiveController() { activeController(PadBridge.NO_CONTROLLER) }
private fun activeController(id: Int) {
PadBridge::class.java.getDeclaredField("activeControllerId").apply { isAccessible = true }.setInt(null, id)
}
private fun effect(strong: Int = 65535, weak: Int = 65535) {
// Inject a decoded force-feedback packet; transport is outside these tests.
RumbleComponent::class.java.getDeclaredMethod("buzz", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
.apply { isAccessible = true }.invoke(rumble, strong, weak, 5000)
}
private class FakeMotors : RumbleComponent.Motors {
override val name = "fake pad"
val played = mutableListOf<Triple<Int, Int, Long>>()
var vibrating = false
override fun play(strong: Int, weak: Int, ms: Long) { played += Triple(strong, weak, ms); vibrating = true }
override fun cancel() { vibrating = false }
}
private companion object { const val PAD_ID = 7 }
@Implements(LocalServerSocket::class)
class NoPacketsSocket {
@Implementation fun __constructor__(name: String) = Unit
@@ -1,58 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.*
import org.junit.Test
class SessionDisplayTest {
@Test fun explicitPresetsAndMatchScreenResolveWithoutAnyAspectSetting() {
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1440 to 1080, "1280x720"))
assertEquals(1600 to 900, SessionDisplay.resolveChoice(1280 to 720, "1600x900"))
assertEquals(1440 to 1080, SessionDisplay.resolveChoice(1080 to 1440, SessionDisplay.MATCH_SCREEN))
assertEquals(2400 to 1080, SessionDisplay.resolveChoice(1080 to 2400, SessionDisplay.MATCH_SCREEN))
}
@Test fun panelOptionReplacesTheIdenticalPresetAndTracksPanelChanges() {
val thor = SessionDisplay.resolutionOptions(1920 to 1080)
assertEquals(listOf("1280x720", "1600x900", SessionDisplay.MATCH_SCREEN), thor)
val small = SessionDisplay.resolutionOptions(1280 to 720)
assertFalse(small.contains("1280x720"))
assertEquals(1280 to 720, SessionDisplay.resolveChoice(1280 to 720, SessionDisplay.MATCH_SCREEN))
assertEquals(2560 to 1440, SessionDisplay.resolveChoice(2560 to 1440, SessionDisplay.MATCH_SCREEN))
}
@Test fun resolutionCapsPreserveTheSelectedShapeWithoutExceedingPanelHeight() {
assertEquals(1280 to 720, SessionDisplay.resolve(1920 to 1080, 720, SessionPrefs.SHAPE_AUTO))
assertEquals(960 to 720, SessionDisplay.resolve(1440 to 1080, 720, SessionPrefs.SHAPE_EXACT))
assertEquals(1280 to 720, SessionDisplay.resolve(1440 to 1080, 720, SessionPrefs.SHAPE_AUTO))
assertEquals(1280 to 720, SessionDisplay.resolve(1280 to 720, 1080, SessionPrefs.SHAPE_AUTO))
}
@Test fun noCapUsesPanelHeightWhileCustomOverridesBothCapAndAspect() {
assertEquals(1440 to 1080, SessionDisplay.resolve(1440 to 1080, 0, SessionPrefs.SHAPE_EXACT))
assertEquals(1920 to 1080, SessionDisplay.resolve(1440 to 1080, 0, SessionPrefs.SHAPE_WIDE))
assertEquals(1024 to 768, SessionDisplay.resolve(1920 to 1080, 720, SessionPrefs.SHAPE_WIDE, 1024 to 768))
}
@Test fun orientationAndOddDimensionsKeepTheExistingEvenLandscapeDisplay() {
assertEquals(1920 to 1080, SessionDisplay.resolve(1081 to 1921, 0, SessionPrefs.SHAPE_EXACT))
assertEquals(1600 to 720, SessionDisplay.resolve(2400 to 1080, 720, SessionPrefs.SHAPE_AUTO))
}
@Test fun gameStretchAvailabilityMatchesTheRuntimeIncludingRounding() {
assertTrue(SessionDisplay.canStretch16x9(960 to 720))
assertFalse(SessionDisplay.canStretch16x9(1280 to 720))
assertFalse(SessionDisplay.canStretch16x9(1600 to 720))
val wide = SessionDisplay.resolve(1440 to 1080, 0, SessionPrefs.SHAPE_WIDE)
assertFalse(SessionDisplay.canStretch16x9(wide))
}
@Test fun removedFilterAliasesRetainTheirEquivalentBehavior() {
assertEquals(0, SessionPrefs.canonicalUpscaler(1))
assertEquals(4, SessionPrefs.canonicalUpscaler(5))
assertEquals(0, SessionPrefs.canonicalUpscaler(99))
assertFalse(SessionPrefs.upscalerHasSharpness(0))
assertFalse(SessionPrefs.upscalerHasSharpness(1))
assertFalse(SessionPrefs.upscalerHasSharpness(2))
for (mode in 3..8) assertTrue(SessionPrefs.upscalerHasSharpness(mode))
}
}
@@ -1,63 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionScalingPrefsTest {
@Before fun clearSettings() {
RuntimeEnvironment.getApplication().getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun explicitLegacyAspectAndCapKeepTheirSizeUntilAResolutionIsPicked() {
val context = RuntimeEnvironment.getApplication()
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putString("shape", SessionPrefs.SHAPE_EXACT).putInt("resolutionCap.steam", 900).commit()
assertEquals("1200x900", SessionPrefs.resolutionChoice(context, "steam", 1440 to 1080))
SessionPrefs.setResolutionChoice(context, "steam", "1600x900")
prefs.edit().putString("shape", SessionPrefs.SHAPE_WIDE).commit()
assertEquals("1600x900", SessionPrefs.resolutionChoice(context, "steam", 1440 to 1080))
assertTrue(SessionPrefs.resolutionChosen(context, "steam"))
}
@Test fun matchScreenOverridesLegacyCustomAndAspectWithoutAffectingTheOtherMode() {
val context = RuntimeEnvironment.getApplication()
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putString("shape", SessionPrefs.SHAPE_WIDE).putString("customRes.steam", "1024x768")
.putString("customRes.lxqt", "800x600").commit()
assertEquals("1024x768", SessionPrefs.resolutionChoice(context, "steam", 1440 to 1080))
SessionPrefs.setResolutionChoice(context, "steam", SessionDisplay.MATCH_SCREEN)
val choice = SessionPrefs.resolutionChoice(context, "steam", 1440 to 1080)
assertEquals(1440 to 1080, SessionDisplay.resolveChoice(1440 to 1080, choice))
assertEquals("800x600", SessionPrefs.resolutionChoice(context, "lxqt", 1440 to 1080))
}
@Test fun freshSettingsUseTheConcreteDefaultAndCustomSizesAreNormalized() {
val context = RuntimeEnvironment.getApplication()
assertEquals("1280x720", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
SessionPrefs.setResolutionChoice(context, "steam", "1025×769")
assertEquals("1024x768", SessionPrefs.resolutionChoice(context, "steam", 2400 to 1080))
}
@Test fun legacySavedFiltersStillResolveToAVisibleEquivalentChoice() {
val context = RuntimeEnvironment.getApplication()
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
prefs.edit().putInt("upscaler", 1).putInt("upscaleSharpness", 65).commit()
assertEquals(0, SessionPrefs.upscaler(context))
prefs.edit().putInt("upscaler", 5).commit()
assertEquals(4, SessionPrefs.upscaler(context))
assertEquals(65, SessionPrefs.upscaleSharpness(context))
SessionPrefs.setUpscaler(context, 5)
assertEquals(4, prefs.getInt("upscaler", -1))
SessionPrefs.setUpscaler(context, 1)
assertEquals(0, prefs.getInt("upscaler", -1))
}
}
@@ -0,0 +1,109 @@
package com.droiddeck.launcher.store.gog
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class GogTest {
@org.junit.Test
fun successfulOperationReturnsNoErrorAndReleasesTheLock() {
org.junit.Assert.assertNull(GogManager.exclusive("setup") { null })
org.junit.Assert.assertNull(GogManager.busy)
org.junit.Assert.assertEquals("download failed", GogManager.exclusive("install") { "download failed" })
org.junit.Assert.assertNull(GogManager.busy)
}
@org.junit.Test
fun concurrentOperationIsRejectedAndExceptionsReleaseTheLock() {
org.junit.Assert.assertNull(GogManager.exclusive("install") {
org.junit.Assert.assertEquals("Another GOG task is running", GogManager.exclusive("setup") { null })
null
})
runCatching { GogManager.exclusive("setup") { error("failed") } }
org.junit.Assert.assertNull(GogManager.busy)
}
@get:Rule val tmp = TemporaryFolder()
private fun game(): File = tmp.newFolder("Example Game").apply {
File(this, "Bin").mkdirs()
File(this, "Bin/Game.EXE").writeText("x")
File(this, "Launcher.exe").writeText("x")
File(this, "Data").mkdirs()
}
private fun info(vararg tasks: String) =
JSONObject("""{"gameId":"42","rootGameId":"42","name":"Example: The Game","playTasks":[${tasks.joinToString(",")}]}""")
@Test fun primaryGameTaskWinsWithWindowsPathsMatchedCaselessly() {
val dir = game()
val parsed = GogGameInfo.parse(dir, info(
"""{"type":"FileTask","category":"launcher","isPrimary":true,"path":"Launcher.exe"}""",
"""{"type":"URLTask","category":"document","link":"https://example.com"}""",
"""{"type":"FileTask","category":"game","isPrimary":true,"path":"bin\\game.exe","workingDir":"data","arguments":"-windowed -lang \"en\""}""",
))!!
assertEquals("42", parsed.id)
assertEquals("Example: The Game", parsed.name)
assertEquals(File(dir, "Bin/Game.EXE"), parsed.task!!.exe)
assertEquals(File(dir, "Data"), parsed.task!!.workingDir)
assertEquals("-windowed -lang \"en\"", parsed.task!!.arguments)
}
@Test fun noWorkingDirStartsInTheGameFolder() {
val dir = game()
val parsed = GogGameInfo.parse(dir, info("""{"type":"FileTask","category":"game","path":"Bin\\Game.exe"}"""))!!
assertEquals(dir, parsed.task!!.workingDir)
assertEquals("", parsed.task!!.arguments)
}
@Test fun missingExeMeansNoTask() {
val dir = game()
assertNull(GogGameInfo.parse(dir, info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Missing.exe"}"""))!!.task)
}
@Test fun readPicksTheRootGameOverDlcInfoFiles() {
val dir = game()
File(dir, "goggame-7.info").writeText("""{"gameId":"7","rootGameId":"42","name":"DLC","playTasks":[]}""")
File(dir, "goggame-42.info").writeText(info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Bin\\Game.exe"}""").toString())
assertEquals("42", GogGameInfo.read(dir)!!.id)
}
@Test fun incompleteUntilTheDownloadFinishes() {
val dir = game()
File(dir, GogManager.MARKER).writeText("""{"id":"42"}""")
assertTrue(GogManager.incomplete(dir))
File(dir, "goggame-42.info").writeText(info("""{"type":"FileTask","category":"game","isPrimary":true,"path":"Bin\\Game.exe"}""").toString())
File(dir, ".gogdl-resume").writeText("")
assertTrue(GogManager.incomplete(dir))
File(dir, ".gogdl-resume").delete()
assertEquals(false, GogManager.incomplete(dir))
}
@Test fun libraryKeepsWindowsGamesAndPageCount() {
val (games, pages) = GogApi.parseLibraryPage("""{"totalPages":3,"products":[
{"id":1207658924,"title":"Unreal Tournament","image":"//images-1.gog-statics.com/abc","worksOn":{"Windows":true,"Mac":false,"Linux":false}},
{"id":2,"title":"Mac Only","image":"//images-1.gog-statics.com/def","worksOn":{"Windows":false,"Mac":true}}
]}""")!!
assertEquals(3, pages)
assertEquals(listOf("1207658924"), games.map { it.id })
assertEquals("https://images-1.gog-statics.com/abc_392.jpg", games[0].image)
}
@Test fun artFillsGamesDbUrlTemplates() {
val art = GogApi.parseArt("""{"game":{"vertical_cover":{"url_format":"https://images.gog.com/v{formatter}.{ext}"},
"logo":{"url_format":"https://images.gog.com/l{formatter}.{ext}"}}}""")!!
assertEquals("https://images.gog.com/v.jpg", art.cover)
assertEquals("https://images.gog.com/l.png", art.logo)
assertNull(art.hero)
}
}
@@ -1,27 +0,0 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.*
import org.junit.Test
class SessionDrawerPageTest {
@Test fun singleScreenNavigationStartsWithControllerAndSkipsSecondScreen() {
val pages = sessionDrawerPages(false)
assertEquals(SessionDrawerPage.CONTROLLER, pages.first())
assertFalse(SessionDrawerPage.SECOND_SCREEN in pages)
assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.CONTROLLER, -1))
assertEquals(SessionDrawerPage.CONTROLLER, pages.step(SessionDrawerPage.SESSION, 1))
}
@Test fun connectedSecondaryDisplayAddsItsPageAfterControllerAndPreservesOtherPages() {
val connected = sessionDrawerPages(true)
assertEquals(SessionDrawerPage.SECOND_SCREEN, connected.step(SessionDrawerPage.CONTROLLER, 1))
assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1))
assertEquals(sessionDrawerPages(false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN })
for (pages in listOf(connected, sessionDrawerPages(false))) {
assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.DISPLAY, 1))
assertEquals(SessionDrawerPage.GAMES, pages.step(SessionDrawerPage.EFFECTS, 1))
assertEquals(SessionDrawerPage.SESSION, pages.step(SessionDrawerPage.GAMES, 1))
}
}
}
@@ -1,107 +0,0 @@
Thor SD storage investigation: selected saved evidence
Recorded 2026-10-04; event timestamps are EDT.
These are excerpts, not complete logs or a continuous attribution profile.
See ../thor-sd-storage-investigation.md for context and live-only observations.
=== Reporter unsupported allocation ===
Source: Reporter diagnostic storage.log
volume_removable=true
filesystem=fuse
allocation pid=29062 comm=steam api=fallocate result=-1 api_error=95 errno_after=95 flags=0x0 offset=0 length=374272 elapsed_us=212
=== Thor unsupported allocation ===
Source: candidate-storage.log
volume_removable=true
filesystem=fuse
allocation pid=9810 comm=steam api=fallocate result=-1 api_error=95 errno_after=95 flags=0x0 offset=0 length=650752 elapsed_us=310
=== Native-path allocation diagnostics ===
Source: direct-storage-completed.log / session 64
DroidDeck storage diagnostics v1
selected_library=secondary
volume_removable=true
filesystem=exfat
truncate_allocation_probe=passed
block_size_bytes=131072
total_bytes=393855500288
available_bytes=101076697088
native_observation=enabled
public_symbol_interposition=enabled
direct_syscalls_and_libc_internal_calls=not_observed
pwrite_timing=sampled_1_in_32
per_process_allocation_detail_limit=64
storage_log_limit_bytes=524288
summary pid=26725 comm=python3 allocation_calls=0 allocation_failures=0 allocation_total_us=0 pwrite_sample_every=32 pwrite_samples=0 pwrite_bytes=0 pwrite_failures=0 pwrite_sample_total_us=0 pwrite_sample_max_us=0 ftruncate_calls=0 ftruncate_failures=0 ftruncate_total_us=0 ftruncate_max_us=0 fstat_calls=1 fstat_total_us=0 fstat_max_us=0 fsync_calls=0 fsync_failures=0 fsync_total_us=0 fsync_max_us=0
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=667648 elapsed_us=387
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=39 elapsed_us=32
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=156 elapsed_us=25
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=457428 elapsed_us=351
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=901928 elapsed_us=864
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=15041920 elapsed_us=15292
allocation pid=26825 comm=steam api=fallocate_ftruncate result=0 api_error=0 errno_after=0 flags=0x0 offset=0 length=337563 elapsed_us=2783
=== Fresh real Steam install ===
Source: direct-content-completed.log / session 64
[2026-10-04 17:31:20] AppID 1675830 App update changed : Running Update,Preallocating,
[2026-10-04 17:38:04] AppID 1675830 preallocated 2216 files (7626 MB)
[2026-10-04 17:38:06] AppID 1675830 App update changed : Running Update,Downloading,Staging,
[2026-10-04 17:45:25] AppID 1675830 App update changed : Running Update,Committing,
[2026-10-04 17:45:25] AppID 1675830 starting commit from "/mnt/droiddeck-sd/steamapps/downloading/1675830" to "/mnt/droiddeck-sd/steamapps/common/1000xRESIST" : 2230 updated, 0 moved, 0 deleted files
[2026-10-04 17:47:55] AppID 1675830 state changed : Fully Installed,Update Queued,Update Running,
[2026-10-04 17:47:55] AppID 1675830 finished update, 1 mounted depots (BuildID 21498291) : 1675831 (3663189783241284849),
[2026-10-04 17:47:56] AppID 1675830 state changed : Fully Installed,Update Queued,
[2026-10-04 17:47:56] AppID 1675830 state changed : Fully Installed,
[2026-10-04 17:47:56] AppID 1675830 scheduler finished : removed from schedule (result No Error, state 0xc)
=== Normal-app native/FUSE directory read ===
Source: app-raw-probe-session.log / session 62
APP_RAW_PROBE uid=10195 path=/mnt/media_rw/FF7F-F56A/Android/data/com.droiddeck.launcher/files/steam/steamapps/downloading/1675830-fuse-control/1000xRESIST_Data/StreamingAssets/aa/StandaloneWindows64 seconds=0.002288 calls=2 bytes=154920 read_error=0
APP_RAW_PROBE uid=10195 path=/storage/FF7F-F56A/Android/data/com.droiddeck.launcher/files/steam/steamapps/downloading/1675830-fuse-control/1000xRESIST_Data/StreamingAssets/aa/StandaloneWindows64 seconds=0.501306 calls=112 bytes=154872 read_error=0
=== Binding regression: bind-probe-before.log ===
Source: bind-probe-before.log
BIND_PROBE index=0 pass=1 errno=0 bytes=17 path=/mnt/droiddeck-sd/steamapps/common/SteamLinuxRuntime_4-arm64/.droiddeck-bind-probe
BIND_PROBE index=1 pass=1 errno=0 bytes=17 path=/mnt/droiddeck-sd/steamapps/common/steamlinuxruntime_4-arm64/.droiddeck-bind-probe
BIND_PROBE index=2 pass=0 errno=2 bytes=-1 path=/mnt/droiddeck-sd/steamapps/common/proton experimental (arm64)/.droiddeck-bind-probe
BIND_PROBE index=3 pass=0 errno=2 bytes=-1 path=/mnt/bannerlator-sd/steamapps/shadercache/.droiddeck-bind-probe
=== Binding regression: bind-probe-after.log ===
Source: bind-probe-after.log
BIND_PROBE index=0 pass=1 errno=0 bytes=17 path=/mnt/droiddeck-sd/steamapps/common/SteamLinuxRuntime_4-arm64/.droiddeck-bind-probe
BIND_PROBE index=1 pass=1 errno=0 bytes=17 path=/mnt/droiddeck-sd/steamapps/common/steamlinuxruntime_4-arm64/.droiddeck-bind-probe
BIND_PROBE index=2 pass=1 errno=0 bytes=17 path=/mnt/droiddeck-sd/steamapps/common/proton experimental (arm64)/.droiddeck-bind-probe
BIND_PROBE index=3 pass=1 errno=0 bytes=17 path=/mnt/bannerlator-sd/steamapps/shadercache/.droiddeck-bind-probe
=== Root metadata/mount experiment: metadata-mount-comparison.log ===
Source: metadata-mount-comparison.log
original_mount
/dev/block/vold/public:179,1 /mnt/media_rw/FF7F-F56A exfat rw,dirsync,nosuid,nodev,noexec,noatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,iocharset=utf8,errors=remount-ro 0 0
files=64 bytes_per_file=262144 open_seconds=6.707435 truncate_seconds=0.084806 wall_seconds=6.794807 error=0
mount: '/dev/block/vold/public:179,1'->'/mnt/media_rw/FF7F-F56A': Invalid argument
mount: '/dev/block/vold/public:179,1'->'/mnt/media_rw/FF7F-F56A': Invalid argument
=== Root metadata/mount experiment: metadata-syscall-comparison.log ===
Source: metadata-syscall-comparison.log
original_mount
/dev/block/vold/public:179,1 /mnt/media_rw/FF7F-F56A exfat rw,dirsync,nosuid,nodev,noexec,noatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,iocharset=utf8,errors=remount-ro 0 0
files=64 bytes_per_file=262144 open_seconds=25.181255 truncate_seconds=0.309577 wall_seconds=25.493210 error=0
temporary_mount
/dev/block/vold/public:179,1 /mnt/media_rw/FF7F-F56A exfat rw,dirsync,nosuid,nodev,noexec,noatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,iocharset=utf8,errors=remount-ro 0 0
files=64 bytes_per_file=262144 open_seconds=2.013194 truncate_seconds=0.095924 wall_seconds=2.112288 error=0
=== Post-install Android low-memory exit ===
Source: game-launch-exit-info.txt
ApplicationExitInfo #0:
timestamp=2026-10-04 18:13:48.454 pid=14709 realUid=10195 packageUid=10195 definingUid=10195 user=0
process=com.droiddeck.launcher reason=3 (LOW_MEMORY) subreason=0 (UNKNOWN) status=0
importance=100 pss=227MB rss=344MB description=null state=empty trace=null
=== Combined release unit-test completion ===
Source: combined-233-tests.log
> Task :app:testReleaseUnitTest
BUILD SUCCESSFUL in 10s
=== Combined release build completion ===
Source: combined-233-build.log
BUILD SUCCESSFUL in 25s
APK: /Users/danhimebauch/.codex/worktrees/steam-sd-preallocation/DroidDeck/app/build/outputs/apk/release/app-release.apk
-5
View File
@@ -5,11 +5,6 @@ games should keep running under proot, run directly on glibc, or a mix of the tw
fastest correct setup is. Everything below was measured on a Snapdragon 8 Elite Gen 5 (SM8850, kernel
6.12.38-android16, Android 16) over adb, unless it says otherwise.
For Steam SD allocation measurements on AYN Thor (Android 13), see the
[Thor storage investigation](thor-sd-storage-investigation.md). It separates
observed allocation-wrapper time, FUSE directory access and native exFAT metadata
waits; it does not establish a full-install PRoot overhead percentage.
## Short answer
- **Don't drop proot.** On Android it does two jobs. It translates paths. It also answers every
@@ -1,379 +0,0 @@
# Steam SD allocation on Thor
Investigation recorded on 2026-10-04. Device measurements and PR states below are a
snapshot of that day's work. All event times are EDT (UTC−04:00).
A fresh 1000xRESIST install on the Thor SD card completed with the native-path and
allocation-fallback patches: 2,216 files preallocated in **6m44s**, followed by a
successful download and commit, **16m36s total**. The observed allocation wrappers
reported zero failures and roughly 7.1 seconds of aggregate execution time.
That wrapper measurement does **not** account for the entire preallocation phase.
Native directory access was substantially faster than Android's FUSE view in a
small controlled probe. Kernel samples during the remaining delay showed exFAT
file-creation and size-update waits. This supports further investigation of SD
metadata writes. It does not establish that PRoot is free, that `dirsync` alone
causes the delay, or that SD now matches internal-storage install speed.
Selected source-log excerpts are preserved in
[the evidence file](evidence/thor-sd-storage-2026-10-04.txt). The original full logs
contain unrelated sessions and are not needed to interpret those excerpts.
## Device and storage
| Item | Observed configuration |
|---|---|
| Device | AYN Thor, Android 13, kernel 5.15.123, 12 GB RAM and 8 GB swap |
| App | Production-signed `com.droiddeck.launcher`, normal app UID 10195 |
| Configured SD library | `/storage/FF7F-F56A/Android/data/com.droiddeck.launcher/files/steam` |
| Native view of the same library | `/mnt/media_rw/FF7F-F56A/Android/data/com.droiddeck.launcher/files/steam` |
| Guest content aliases | `/mnt/droiddeck-sd` and legacy `/mnt/bannerlator-sd` |
| SD filesystem | Native exFAT; its Android `/storage` view reports FUSE |
| Native filesystem magic | `0x2011BAB0`, matching the NDK Linux header |
| Internal comparison location | App-private cache under `/data` |
The native SD mount was observed with these options:
```text
rw,dirsync,nosuid,nodev,noexec,noatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,iocharset=utf8,errors=remount-ro
```
The device already had root and SELinux Permissive. Neither state was introduced
by this investigation. Root was used for inspection and temporary experiments.
The validated Steam session ran with the app's normal UID and existing groups,
without a root launcher or an app-specific Magisk root grant.
This distinction does not prove the native path works on an unrooted device with
enforcing SELinux. The production change tests access in the app and retains the
configured path when verification fails.
## Initial report and allocation failure
The [linked Discord report](https://discord.com/channels/1552707793247539220/1555632840388116491/1556271955076710560)
included a newer diagnostic ZIP with `storage.log`. Unlike the earlier capture
that lacked allocation instrumentation, this capture established:
- The selected secondary library was removable and its exposed filesystem was
FUSE.
- Steam called mode-zero `fallocate` and received `EOPNOTSUPP` (errno 95).
- That observed failure returned in 212 microseconds. It was not itself a
multi-minute blocked call.
A Thor baseline capture likewise showed `fallocate` failing with errno 95 in
310 microseconds. These establish an unsupported allocation API on the tested
paths. They do not attribute the later Steam delay to any particular fallback.
The suggestion that glibc's `posix_fallocate` emulation accounts for the whole
hang was not established by those logs. The tested Steam calls included
`fallocate`; directory operations and other calls occur outside that wrapper.
## Published patches and the tested build
The main base was `26cb9e2f038cdbab4cdc8670d2f64c18d1d90875`. These heads were
checked again while preparing this report; all three storage PRs were open with
successful Build APK checks and clean merge states. This is a dated snapshot,
not a statement about their future merge status.
| PR | Tested head | Behavior |
|---|---|---|
| [#221](https://github.com/Droid-Deck/DroidDeck/pull/221) | `7962c19283bfb0f18a5c7672e08a879814a3d5a1` | Verify a native SD content alias and handle safe case aliases in the path fast path |
| [#229](https://github.com/Droid-Deck/DroidDeck/pull/229) | `4628ae4c92cc5813013537165a0e95886e6de904` | Use a verified truncate fallback for unsupported selected-library allocation |
| [#233](https://github.com/Droid-Deck/DroidDeck/pull/233) | `5c6765233ae5405d7bd4c1b29f20c9e8343a1fed` | Preserve the complete fast-path binding table, including later private overrides |
| [#225](https://github.com/Droid-Deck/DroidDeck/pull/225) | `0b5908d6d63080f625b51bab3439e2e68466631e` | Repair repeated failed Steam client starts; reviewed separately, excluded from this storage build |
### Native content path and case handling: #221
For a configured `/storage/...` library, the launcher checks the corresponding
`/mnt/media_rw/...` candidate. It requires usable directory permissions and
performs a write/read/delete identity probe through both views. Failure keeps
the original configured path.
Only the shared SD content bindings change. The configured path remains the
library's identity for private prefixes, migrations and other private storage.
This avoids moving existing saves or runtime state when selecting a faster view.
Removable-volume detection also uses the original configured path because
Android's volume API need not recognize the native alias.
The C fast path permits case-only canonical-parent differences on known
FUSE/FAT/exFAT filesystems only after checking directory components without
following symlinks. It also handles the supported `F_OK` plus
`AT_SYMLINK_NOFOLLOW` case. Ambiguous paths still fall back to PRoot.
The final #221 diff was four files, 98 insertions and 20 deletions, including
28 new test lines. The experimental directory cache was removed from that diff.
### Allocation fallback: #229
The launcher first creates a temporary 1 MiB file on the selected content path,
extends it, and checks that `st_blocks` reports at least 2,048 512-byte blocks.
The file must also be cleaned up successfully. The fallback is enabled only for
a removable library that passes this reservation probe.
For file descriptors on the selected library device, the wrapper tries the real
allocation API. On mode-zero `fallocate` returning `EOPNOTSUPP`, it extends the
file with `ftruncate`. It validates the range, detects overflow and avoids
shrinking an existing file. Other modes and other errors retain their normal
behavior. The POSIX wrapper tries kernel allocation first to avoid unnecessary
libc emulation and preserves POSIX error-return and `errno` semantics.
This is a capability-tested fallback, not unconditional successful allocation
reporting. A failed extension still returns an error. The optimization operates
independently of the optional diagnostic toggle.
The reservation probe and one successful full install do not replace separate
future tests for ENOSPC, interrupted installs or other devices/filesystems.
### Complete binding table: #233
The real Steam session had **96 bindings**. The old C limit of 64 silently
dropped later mappings. Several of those were private overrides inside the
shared SD root, so truncation could send an operation to the wrong location or
return `ENOENT`.
#233 raises capacity to 256 and makes both the launcher and C implementation
disable the fast path if a complete table cannot be represented. Overlong paths
also cause fallback rather than partial mapping. This is a correctness fix as
well as a requirement for trusting the storage fast path.
Marker files existed only in private directories. A normal app-process probe
read them through these guest paths:
| Guest path under the library | Before #233 | After #233 |
|---|---|---|
| `SteamLinuxRuntime_4-arm64` | Correct private marker | Correct private marker |
| `steamlinuxruntime_4-arm64` | Correct private marker | Correct private marker |
| `proton experimental (arm64)` | `ENOENT` | Correct private marker |
| Legacy `steamapps/shadercache` | `ENOENT` | Correct private marker |
Each successful read returned the 17-byte `private-override\n` marker. The
temporary markers and helper executable were removed afterward.
### Deployment and checks
The full fresh install used #221 plus #229. #233 was then integrated locally,
tested, built and installed for the binding regression and game-launch check.
It was not merged on GitHub during this investigation.
The combined integration commit was
`f5d3e93b8eb8912ca3834f7447a6498c95250177`. The production-signed APK was installed
in place with `adb install -r`; its SHA-256 was:
```text
099a0d7e76b9462b3b238c6f1abeb03570ec9708ace3092adf178ec2bee63e2a
```
`tools/build_local.sh` completed for the combined build. The release unit tests
for `SecondaryLibraryTest` and `ProotFastPathTest` passed. The latter covers
96/256 bindings, exceeding capacity, and overlong paths. #225 was reviewed for
scope; its tests were not run as part of this storage validation.
## Fresh real Steam install
Game: **1000xRESIST**, app 1675830, depot 1675831, BuildID 21498291. Steam reported
6,582,351,824 download bytes and 7,997,085,707 staging bytes, approximately 8 GB.
| Event | Time | Evidence |
|---|---|---|
| Fresh preallocation began | 17:31:20 | Steam entered `Preallocating` |
| Preallocation completed | 17:38:04 | 2,216 files, 7,626 MB in Steam's log |
| Download/staging began | 17:38:06 | `Downloading,Staging` |
| Commit began | 17:45:25 | 2,230 updated files |
| Fully installed | 17:47:55 | `Fully Installed`, BuildID 21498291 |
| Scheduler completed | 17:47:56 | `No Error` |
Preallocation took **404 seconds**. Start to scheduler completion took
**996 seconds**. Live counters showed 2,216 allocation calls, zero allocation
failures and about **7.1 seconds aggregate allocation-wrapper time**. The saved
diagnostic detail log is capped at the first 64 allocation details per process;
that file alone cannot reproduce the live aggregate counter observation.
The final manifest had `StateFlags=4`, `UpdateResult=0`, all expected download
and staging bytes completed, and `SizeOnDisk=7997085707`. The completed executable
was under `steamapps/common/1000xRESIST`; the active staging directory was gone.
Transfer rates were mostly 117–132 Mbps, about 15–16.5 MB/s. Two root metadata
experiments ran during downloading, so this is not a clean network/card
throughput benchmark. No matched full internal-storage install was performed.
The run's `storage.log` reported native exFAT and a passed truncate reservation
probe. Recorded allocation details used `api=fallocate_ftruncate`, with
`result=0` and `api_error=0`.
## What the metadata measurements show
Metadata is filesystem bookkeeping: names, directory entries, sizes and space
allocation. Steam's `Preallocating` phase includes work outside the observed
allocation wrappers, including creating and locating files.
### Directory reads through native and FUSE paths
A helper ran in a normal app process and listed the same stable asset directory
from a saved staging tree through both host paths. It used the existing fast-path
syscall trampoline to bypass PRoot path translation while retaining the app's
Android permissions. The read buffer was 128 KiB.
| View | Elapsed | Successful `getdents64` calls | Directory bytes |
|---|---|---|---|
| Native exFAT | About 2.3 ms | 2 | 154,920 |
| Android FUSE | About 501 ms | 112 | 154,872 |
The views returned slightly different byte counts. This was a single
native-first pass, not a repeated benchmark with fully controlled cache state.
It demonstrates a large cost difference for that directory read, not a
corresponding multiplier for a full Steam install.
An earlier root listing during concurrent file creation measured roughly
5.56 seconds through FUSE and 9.25 milliseconds native. Its directory was
changing, so it is weaker evidence and is not used as a controlled comparison.
### File creation and size updates
During the fresh native-path Steam run, sampled kernel stacks included:
```text
__sync_dirty_buffer -> exfat_update_bh -> exfat_init_ext_entry
-> exfat_add_entry -> exfat_create -> path_openat
__wait_on_buffer -> exfat_update_bhs -> exfat_free_dentry_set
-> __exfat_write_inode -> exfat_truncate -> do_sys_ftruncate
```
These were live samples, not a continuous attribution profile. They show time
waiting in the native filesystem's creation/update paths during the delay.
A root-only helper created a temporary directory, then 64 long-named files using
`open(O_CREAT|O_EXCL|O_WRONLY, 0600)`, `ftruncate(fd, 262144)` and `close`. It timed
the creation and truncate calls separately and removed its files afterward.
| Location/run | Sum of open times | Sum of truncate times | Whole loop |
|---|---|---|---|
| Native SD, original mount | 6.707435 s | 0.084806 s | 6.794807 s |
| Native SD, later repeat | 25.181255 s | 0.309577 s | 25.493210 s |
| Internal app cache, live observation | About 7.88 ms | About 0.498 ms | About 9.1 ms |
The SD results varied substantially, and these root probes do not reproduce the
normal app's complete Steam workload. The measured internal probe is not a full
internal-install benchmark. Within these probes, file creation cost far more
than the observed truncate calls.
### `dirsync` and the failed remount comparison
The [Linux mount documentation](https://man7.org/linux/man-pages/man2/mount.2.html)
defines `MS_DIRSYNC` as synchronous directory changes. Combined with the observed
exFAT buffer waits, this makes synchronous SD metadata updates a strong lead.
It remains an inference about the remaining overall delay.
A toybox remount attempt returned `Invalid argument`. A direct mount-syscall
experiment changed the root view, but Steam's observed mount table still showed
`dirsync`. A subsequent 64-file probe took 2.112288 seconds; because the effective
flag change was not established and timings were variable, this is **not proof
that removing `dirsync` improves Steam allocation**. The Linux documentation also
notes that attempts to change `MS_DIRSYNC` during a remount are silently ignored.
Original effective options were restored and checked in root and app/process
views. No remount or root-launch behavior is included in the production patches.
### What remains attributable to PRoot
One sampled Steam worker was executing an `openat` through the fast-path
trampoline at `0xffff00020`, with an absolute native host path. That establishes
that some operations bypassed PRoot's path translation in the actual session.
Other syscalls still use PRoot.
There was no matched PRoot-versus-direct full preallocation comparison. The
fraction of the 404 seconds attributable to PRoot is therefore unknown. The
earlier [PRoot performance notes](proot-performance.md) concern different hardware
and workloads and cannot supply that missing percentage.
Seven seconds in public allocation wrappers does not mean the remaining
397 seconds are unrelated to allocation: libc-internal/direct-syscall bypasses,
explicit size changes and file-creation work may occur outside those counters.
## Experiments that did not become the fix
- **Directory caching:** eager scans held up directory open; creation-driven
invalidation repeatedly reread growing directories. The capped design could
also read and discard a large directory before rereading it. A lazy variant
still left 182 files taking 4m49s while the allocation wrappers accounted for
only 0.879 seconds. These were interrupted/resumed runs, not a matched A/B
benchmark. The final #221 snapshot removes the cache entirely.
- **Allocation fallback alone:** a FUSE-path attempt was still slow after
unsupported allocation calls were handled. A later eager-cache resumed run
accumulated roughly 8.36 seconds in 1,435 successful allocation calls over
about 36 minutes of wall time. Successful wrappers alone were insufficient.
- **Launching Steam through root:** experimental wrappers failed compositor
startup. They did not produce allocation measurements and were reverted.
- **Changing mount flags:** effective removal of `dirsync` from Steam's view was
not demonstrated. The apparent probe speedup is not a validated fix.
- **Replacing PRoot or reformatting storage:** no such replacement, adoptable
storage conversion or ext4 loop-image deployment was validated here.
The early FUSE runs used partial staging state. Their file counts and durations
must not be compared to the fresh 2,216-file run as a precise speedup ratio.
## Post-install launch and separate memory failure
After deploying #221 + #229 + #233, the installed SD game was launched through
Steam. First-run Proton prefix initialization preceded the game window.
At **18:10:45**, the compositor changed from Steam Big Picture to **1000xRESIST**
and received the game's 1280×720 GPU frames. A screenshot showed the game loading
screen and spinner. A main menu or sustained gameplay was not validated.
At **18:13:48.454**, Android recorded the foreground app's exit as reason 3,
`LOW_MEMORY`, with main-app PSS 227 MB and RSS 344 MB. Those figures describe that
process, not the complete native process tree or its peak memory use. Subsequent
gamescope/reaper shutdown messages followed the parent being killed.
This was after the install had completed. It is a separate unresolved launch/
memory issue and does not undo the successful allocation/download result.
Post-kill free-memory readings cannot establish peak memory pressure.
## Remaining questions and next useful tests
1. Run the same fresh game install on internal and secondary storage with the
same manifest, awake device and no competing benchmarks. Compare preallocation,
download/staging and commit separately.
2. Match the file-creation/extension workload through PRoot and through the normal
app's direct syscall path. Keep UID, filesystem, names and sizes identical,
repeat runs and record background I/O. This can quantify the remaining tracer
contribution without changing storage semantics.
3. Establish an actual controlled difference in synchronous directory behavior
before attributing a speedup to mount flags. A remount return code alone is
insufficient; this is separate from a portable app patch.
4. Validate native-path fallback under enforcing SELinux and on unrooted devices,
plus allocation behavior near ENOSPC and after interruption. Preserve the
configured-path fallback if either access or reservation verification fails.
5. Investigate the low-memory exit with process-tree/cgroup memory and Android
kill evidence during loading. Treat it separately from install performance.
At this point, one fresh SD install and the binding regression are validated.
Internal-speed parity, the exact PRoot share, a `dirsync` remedy, broad device
coverage and stable gameplay remain unproven.
## Evidence inventory and handoff state
The device captures used for the final measurements were:
- `2026-10-04-62-app-raw-probe`: normal-app native/FUSE directory probe.
- `2026-10-04-64-steam`: fresh complete allocation/download/commit.
- Probe sessions before and after #233: private binding markers.
- `2026-10-04-67-steam`: combined-build launch, followed by Android's low-memory
kill; the exit reason was obtained separately with `dumpsys activity exit-info`.
Local originals during the investigation were under
`/tmp/droiddeck-storage-live/`: `direct-content-completed.log`,
`direct-storage-completed.log`, `app-raw-probe-session.log`,
`bind-probe-before.log`, `bind-probe-after.log`,
`metadata-mount-comparison.log`, `metadata-syscall-comparison.log`,
`game-launch-exit-info.txt`, `combined-233-build.log` and
`combined-233-tests.log`. The repository evidence file preserves the selected
excerpts even if those temporary local files disappear. Live-only counters,
kernel samples and the internal metadata timing are identified above rather
than represented as saved continuous traces.
The combined signed build and completed SD install remained on Thor. Storage
diagnostics remained enabled. Temporary probe files, executables and obsolete
partial staging were removed after validation. Original effective mount options
were restored; no app-specific Magisk root policy remained. The primary checkout's
unrelated `SessionService.kt` modification was preserved.
-62
View File
@@ -1,62 +0,0 @@
# DroidDeck 0.3.1
### Steam
- Decky plugins can be imported from ZIP files, with remote binaries verified and installed copies of the same plugin replaced. (@xXJSONDeruloXx, [#79](https://github.com/Droid-Deck/DroidDeck/pull/79))
- Steam's Internet page shows Android Wi-Fi and cellular connections. Optional Wi-Fi discovery adds network names and nearby networks with Android's Location permission. (@xXJSONDeruloXx, [#150](https://github.com/Droid-Deck/DroidDeck/pull/150))
- Paste text from the Android clipboard into Steam sessions. (@xXJSONDeruloXx, [#151](https://github.com/Droid-Deck/DroidDeck/pull/151))
- The Proton selected in Components stays in sync with Steam's default compatibility tool, and runnable builds are marked **Compatible**. Windows titles with a Valve recommendation use that default unless you choose another compatible tool for the game. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197), [#224](https://github.com/Droid-Deck/DroidDeck/pull/224))
### Compatibility and performance
- Choose **esync**, **fsync**, experimental **ntsync**, or **wineserver** for Proton games. These sync options work around Android's missing kernel support, with esync as the default for fresh installs and existing choices preserved. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197), [#223](https://github.com/Droid-Deck/DroidDeck/pull/223))
- droiddeck-esync packs are matched to the exact Valve, GE-Proton or CachyOS Proton build and fetched automatically. droiddeck-fsync stands in when a pack is not available. (@maxjivi05, [#189](https://github.com/Droid-Deck/DroidDeck/pull/189), [#197](https://github.com/Droid-Deck/DroidDeck/pull/197))
- Linux-only x86 Steam titles can run through FEX using Steam's FEX and Steam Linux Runtime, with controller input and the device's graphics drivers. Missing dependencies are requested through Steam. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197))
- .NET and Godot games get automatic launch fixes under FEX, including the settings needed for Slay the Spire 2. Per-game overrides are kept. (@magarto, [#168](https://github.com/Droid-Deck/DroidDeck/pull/168))
### Display and effects
- Live image scaling with AMD FSR 1, Snapdragon GSR and GSR quality, NVIDIA NIS, linear and nearest filtering, plus sharpening. (@magarto, @The412Banner, [#128](https://github.com/Droid-Deck/DroidDeck/pull/128), [#198](https://github.com/Droid-Deck/DroidDeck/pull/198))
- An **Effects** page adds presets, FXAA, Toon, CRT, NTSC and Fake HDR. Advanced controls cover sharpening, debanding, brightness, contrast, gamma and saturation, with choices saved between sessions. (@The412Banner, @xXJSONDeruloXx, [#198](https://github.com/Droid-Deck/DroidDeck/pull/198), [#247](https://github.com/Droid-Deck/DroidDeck/pull/247))
- Anisotropic filtering and texture sharpness for DirectX 9–11 games, applied on the next game launch. (@The412Banner, [#198](https://github.com/Droid-Deck/DroidDeck/pull/198))
- One **Resolution** menu before starting a session, with preset dimensions, Custom and **Match screen**. Resolution, image scaling and fullscreen compatibility have separate controls. (@xXJSONDeruloXx, [#247](https://github.com/Droid-Deck/DroidDeck/pull/247))
### Controls and sessions
- Standard Android picture-in-picture, opened manually or automatically when leaving a ready session, with second-screen controls restored when you return. (@xXJSONDeruloXx, [#156](https://github.com/Droid-Deck/DroidDeck/pull/156), [#195](https://github.com/Droid-Deck/DroidDeck/pull/195))
- A quick toggle hides or restores on-screen controls. **Touch Off** ignores touches on the game picture while keeping Android controls usable. (@xXJSONDeruloXx, [#147](https://github.com/Droid-Deck/DroidDeck/pull/147), [#196](https://github.com/Droid-Deck/DroidDeck/pull/196))
- Optional game vibration and on-screen Steam, Quick Access and keyboard buttons. (@xXJSONDeruloXx, [#194](https://github.com/Droid-Deck/DroidDeck/pull/194))
- Steam session settings use tabs for Display, Controls, Games, Audio, Session and Steam. The session menu starts with Controller, gives second-screen modes their own page, and groups live display changes separately from settings for the next game launch. (@xXJSONDeruloXx, [#247](https://github.com/Droid-Deck/DroidDeck/pull/247))
- Compact Steam Home and Quick Access shortcuts beside Stop. Switching to Desktop stays in Steam's own menu. (@xXJSONDeruloXx, [#188](https://github.com/Droid-Deck/DroidDeck/pull/188), [#196](https://github.com/Droid-Deck/DroidDeck/pull/196))
- Back's double-press window is back to 500 ms, making Quick Access easier to open. (@xXJSONDeruloXx, [#193](https://github.com/Droid-Deck/DroidDeck/pull/193))
### Apps and launcher
- Android home-screen shortcuts for installed Steam games and added games. (@xXJSONDeruloXx, [#157](https://github.com/Droid-Deck/DroidDeck/pull/157))
- Export per-game `.droiddeck` launch files and Steam icons for Android frontends, with optional automatic folder sync as the library changes. (@xXJSONDeruloXx, [#179](https://github.com/Droid-Deck/DroidDeck/pull/179))
- Import x86 AppImages and run x86 Linux scripts and programs through FEX. Added apps have a **Use FEX** Auto/On/Off choice, and GitHub imports can use an x86_64 AppImage when no ARM64 build is available. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197))
- Vulkan Qt Quick AppImages such as OpenNOW use Wayland to avoid X11 startup failures. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197))
- Preview updates show recent published changes and how many builds behind you are when the installed Preview can be matched. (@xXJSONDeruloXx, [#159](https://github.com/Droid-Deck/DroidDeck/pull/159))
- A new empty-library intro and DroidDeck wordmark on the Steam page, plus an option to reduce app animations. (@xXJSONDeruloXx, [#182](https://github.com/Droid-Deck/DroidDeck/pull/182), [#194](https://github.com/Droid-Deck/DroidDeck/pull/194))
- The Linux file manager bookmarks the selected game library automatically. (@xXJSONDeruloXx, [#194](https://github.com/Droid-Deck/DroidDeck/pull/194))
### Languages and logs
- Simplified Chinese. (@Dantalian-dev, [#202](https://github.com/Droid-Deck/DroidDeck/pull/202))
- Japanese, Korean and Traditional Chinese for Taiwan, Hong Kong and Macau. (@starwishHi, [#216](https://github.com/Droid-Deck/DroidDeck/pull/216))
- Optional **Storage diagnostics** include allocation and storage timing in shared session logs to help investigate slow Steam installs. (@xXJSONDeruloXx, [#158](https://github.com/Droid-Deck/DroidDeck/pull/158))
- Session logs retain their final output and include more detail when an AppImage or FEX program fails to start or crashes. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197))
### Fixed
- Steam's Deck controller not being found on handhelds with older kernels. (@xXJSONDeruloXx, [#146](https://github.com/Droid-Deck/DroidDeck/pull/146))
- Physical and on-screen controllers doing nothing on ColorOS devices with linked app data directories. (@maxjivi05, [#242](https://github.com/Droid-Deck/DroidDeck/pull/242))
- Game vibration going to the phone instead of the active physical controller. The device vibrator remains the fallback for on-screen controls or controllers without motors. (@maxjivi05, [#242](https://github.com/Droid-Deck/DroidDeck/pull/242))
- A physical mouse stopping camera movement at the screen edge. Games that request a pointer lock now use Android's relative pointer capture, released while menus or PiP are open. (@maxjivi05, [#242](https://github.com/Droid-Deck/DroidDeck/pull/242))
- Steam remaining on a black screen after idle sleep or Android session resume. (@xXJSONDeruloXx, @jmarti326, [#155](https://github.com/Droid-Deck/DroidDeck/pull/155), [#172](https://github.com/Droid-Deck/DroidDeck/pull/172))
- Steam stuck at **Waiting for Steam** after an interrupted client update. After two starts without a frame, DroidDeck fetches the client again while preserving games, settings and user data; **Repair Steam client** also queues a manual repair. (@maxjivi05, [#225](https://github.com/Droid-Deck/DroidDeck/pull/225))
- Play racing runtime removal. Removal now shows progress and verifies completion, and first-run setup respects the selected Steam channel and saved UI scaling. (@xXJSONDeruloXx, [#185](https://github.com/Droid-Deck/DroidDeck/pull/185))
- GE-Proton and CachyOS Proton failing their protonfixes checks because Android blocks `/proc/sys/fs/file-max`. (@magarto, [#169](https://github.com/Droid-Deck/DroidDeck/pull/169))
- DirectAudio not being selected correctly, mismatched FEX helpers surviving component swaps, and FEX or its runtime not being executable from an SD-card Steam library. (@maxjivi05, [#197](https://github.com/Droid-Deck/DroidDeck/pull/197))
[Full changelog](https://github.com/Droid-Deck/DroidDeck/compare/0.3.0...0.3.1)
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/python3
"""The app's GOG store talks to Heroic's gogdl through this: one JSON object per line on stdout,
so progress reaches the front end as numbers rather than log lines. The app puts gogdl in the
runtime (GOGDL below) and keeps the sign-in in its own files (the auth path every command takes).
Tokens never leave on stdout except from "token", whose output the app does not log.
droiddeck-gog login <auth> <code> trades the sign-in page's code for tokens
droiddeck-gog token <auth> a current access token (refreshed when due)
droiddeck-gog info <auth> <id> folder name and sizes of the Windows build
droiddeck-gog install <auth> <id> <base> downloads into <base>/<folder name>
droiddeck-gog update <auth> <id> <dir> brings an installed game to the latest build
Lines: {"e":"info",...}, {"e":"progress","percent":45,"written":..,"total":..},
{"e":"error","message":"..."} and {"e":"done",...} at the end. Exit status 0 on success.
"""
import json
import os
import re
import subprocess
import sys
GOGDL = "/opt/droiddeck/gogdl/gogdl"
PLATFORM = "windows"
MARKER = ".droiddeck-gog.json"
PROGRESS = re.compile(r"= Progress: ([\d.]+) (\d+)/(\d+)")
# gogdl's own log lines: "[NAME] LEVEL: message".
LOG = re.compile(r"^\[([^\]]+)\] (\w+): (.*)$")
def emit(**kw):
sys.stdout.write(json.dumps(kw) + "\n")
sys.stdout.flush()
def gogdl(auth, *args):
return [sys.executable or "/usr/bin/python3", GOGDL, "--auth-config-path", auth] + list(args)
def last_json(text):
"""gogdl prints its answer as the last JSON line of stdout, after anything else it says."""
for line in reversed(text.splitlines()):
line = line.strip()
if line.startswith("{") or line == "null":
try:
return json.loads(line)
except ValueError:
continue
return None
def quiet(auth, *args):
"""Runs a gogdl command that answers in JSON; its log (stderr) is dropped, never echoed."""
run = subprocess.run(gogdl(auth, *args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return run.returncode, last_json(run.stdout), run.stderr
def login(auth, code):
os.makedirs(os.path.dirname(auth) or ".", exist_ok=True)
status, data, _ = quiet(auth, "auth", "--code", code)
if status != 0 or not isinstance(data, dict) or data.get("error") or not data.get("access_token"):
emit(e="error", message="GOG did not accept the sign-in")
return 1
emit(e="done", user_id=str(data.get("user_id", "")))
return 0
def token(auth):
if not os.path.isfile(auth):
emit(e="error", message="signed out")
return 1
status, data, _ = quiet(auth, "auth")
if status != 0 or not isinstance(data, dict) or not data.get("access_token"):
emit(e="error", message="signed out")
return 1
expires = float(data.get("loginTime", 0)) + float(data.get("expires_in", 0))
emit(e="token", access_token=data["access_token"], user_id=str(data.get("user_id", "")), expires=int(expires))
return 0
def sizes(size, language):
"""Bytes to download and on disk: the depots every language needs ("*") plus one language's."""
pick = [k for k in ("*", language) if k in size]
if language not in size:
pick += [k for k in size if k != "*"][:1]
return (sum(int(size[k].get("download_size") or 0) for k in pick),
sum(int(size[k].get("disk_size") or 0) for k in pick))
def language_of(data):
langs = data.get("languages") or []
for want in ("en-US", "en"):
if want in langs:
return want
return langs[0] if langs else "en-US"
def info(auth, game_id, out=True):
status, data, err = quiet(auth, "info", game_id, "--platform", PLATFORM, "--skip-dlcs")
if status != 0 or not isinstance(data, dict) or not data.get("folder_name"):
reason = failure(err) or "GOG has no Windows build of this game to download"
if out:
emit(e="error", message=reason)
return None, reason
language = language_of(data)
download, disk = sizes(data.get("size") or {}, language)
result = dict(folder=data["folder_name"], language=language, download_size=download, disk_size=disk,
build=str(data.get("buildId", "")))
if out:
emit(e="info", **result)
return result, None
def failure(text):
"""The last error gogdl logged, for the user; None when it logged none."""
errors = [m.group(3) for m in (LOG.match(line) for line in (text or "").splitlines())
if m and m.group(2) in ("ERROR", "CRITICAL")]
return errors[-1] if errors else None
def follow(argv):
"""Runs a download, turning its progress lines into ours. Returns (status, last error)."""
proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
error, last = None, -1
for line in proc.stdout:
line = line.rstrip("\n")
m = PROGRESS.search(line)
if m:
percent = int(float(m.group(1)))
if percent != last:
last = percent
emit(e="progress", percent=percent, written=int(m.group(2)), total=int(m.group(3)))
continue
log = LOG.match(line)
if log and log.group(2) in ("ERROR", "CRITICAL"):
error = log.group(3)
# Everything else goes to the app's log of this command as it is.
sys.stdout.write(line + "\n")
sys.stdout.flush()
return proc.wait(), error
def install(auth, game_id, base):
data, _ = info(auth, game_id)
if data is None:
return 1
target = os.path.join(base, data["folder"])
os.makedirs(target, exist_ok=True)
# Which game a folder is, from the first byte: the app lists a stopped download by it.
with open(os.path.join(target, MARKER), "w", encoding="utf-8") as f:
json.dump(dict(id=game_id, build=data["build"], language=data["language"]), f)
status, error = follow(gogdl(auth, "download", game_id, "--platform", PLATFORM, "--path", base,
"--skip-dlcs", "--lang", data["language"]))
if status != 0 or not os.path.isfile(os.path.join(target, "goggame-%s.info" % game_id)):
emit(e="error", message=error or "the download stopped (gogdl exit %d)" % status)
return 1
emit(e="done", dir=target)
return 0
def update(auth, game_id, target):
data, _ = info(auth, game_id, out=False)
language = data["language"] if data else "en-US"
status, error = follow(gogdl(auth, "update", game_id, "--platform", PLATFORM, "--path", target,
"--skip-dlcs", "--lang", language))
if status != 0:
emit(e="error", message=error or "the update stopped (gogdl exit %d)" % status)
return 1
emit(e="done", dir=target)
return 0
def main(argv):
if len(argv) < 3:
print(__doc__)
return 2
verb, auth, rest = argv[1], argv[2], argv[3:]
if not os.path.isfile(GOGDL):
emit(e="error", message="gogdl is not set up")
return 1
if verb == "login" and len(rest) == 1:
return login(auth, rest[0])
if verb == "token" and not rest:
return token(auth)
if verb == "info" and len(rest) == 1:
return 0 if info(auth, rest[0])[0] else 1
if verb == "install" and len(rest) == 2:
return install(auth, rest[0], rest[1])
if verb == "update" and len(rest) == 2:
return update(auth, rest[0], rest[1])
print(__doc__)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv))
@@ -775,10 +775,6 @@ BUSCONF
echo "== steam: client branch on disk was '$(cat "$steam_beta" 2>/dev/null)', set to '$steam_channel' to match -clientbeta"
echo "$steam_channel" > "$steam_beta"
fi
if [ -z "${_bl_counted:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then
echo start >> "$steam_root/package/droiddeck-unconfirmed"
_bl_counted=1
fi
step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}"
"$steam_root/steamrtarm64/steam" "${_bl_ui[@]}" "${_bl_cdp[@]}" -clientbeta "$steam_channel" \
-no-cef-sandbox -cef-force-gpu -cef-ozone-platform=x11 \
@@ -397,12 +397,11 @@ class Helper:
default, state = COMPAT["choose_default"](top["selected"], state, request, live, apply_request=not waiting)
installed = COMPAT["installed_apps"](self.steam_root)
self.installed = installed
picks = COMPAT["valve_picks"](self.steam_root)
apps = sorted(set(installed) | set(picks) | set(state.get("auto", {})), key=COMPAT["app_order"])
apps = sorted(set(installed) | set(state.get("auto", {})), key=COMPAT["app_order"])
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
current["0"] = top["selected"]
native = COMPAT["native_targets"](self.steam_root, installed)
changes, auto = COMPAT["plan_mapping"](current, installed, [t["name"] for t in live], default, COMPAT["followers"](state, current), native, picks)
changes, auto = COMPAT["plan_mapping"](current, installed, [t["name"] for t in live], default, COMPAT["followers"](state, current), native)
for app, tool in sorted(changes.items(), key=lambda item: COMPAT["app_order"](item[0])):
page.compat("set(%d, %s)" % (int(app), json.dumps(tool)))
say("%s -> %s" % ("default" if app == "0" else "app %s" % app, tool))
@@ -178,7 +178,7 @@ def unimported(steam_root, snapshot, candidates):
def watch(steam_root, listing):
games = read_json(listing, [])
games = [game for game in read_json(listing, []) if isinstance(game, dict) and not game.get("store")]
if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games:
return
candidates, sources = {}, {}
@@ -344,6 +344,10 @@ def route(steam_root, acct, games):
owned, candidates, sources = {}, {}, {}
shortcuts, routes = [], {}
for game in games:
# A store's copy (GOG) is that store's game, never the Steam title of the same name.
if game.get("store"):
shortcuts.append(game)
continue
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
stamp = source_stamp(game)
@@ -12,33 +12,9 @@ manifest=steam_client_${steam_channel}_linuxarm64
steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam
stamp=$steam_root/package/droiddeck-installed
legacy_stamp=$steam_root/package/bannerlator-installed
unconfirmed=$steam_root/package/droiddeck-unconfirmed
repair_request=$HOME/.bl-steam-repair
if [ -f "$legacy_stamp" ] && [ ! -f "$stamp" ]; then
mv -f "$legacy_stamp" "$stamp" || true
fi
repair=""
if [ -e "$repair_request" ]; then
repair="requested"
elif [ -f "$unconfirmed" ] && ! grep -qx repaired "$unconfirmed" \
&& [ "$(grep -cx start "$unconfirmed")" -ge 2 ]; then
repair="the client was started $(grep -cx start "$unconfirmed") times without showing anything"
fi
if [ -n "$repair" ]; then
echo "== STEP $(date -u +%H:%M:%S) repairing the Steam client ($repair)"
rm -f "$stamp" "$legacy_stamp" "$steam_root/.crash" "$steam_root/steam.pid" \
"$steam_root"/package/steam_client_*.manifest "$steam_root"/package/steam_client_*.installed
for part in "$steam_root"/package/*.zip.*; do
[ -f "$part" ] || continue
sum=${part##*.}
sum=${sum%%_*}
case $sum in
*[!0-9a-f]*|"") continue ;;
esac
[ ${#sum} -eq 40 ] || continue
[ "$(sha1sum "$part" | cut -d' ' -f1)" = "$sum" ] || rm -f "$part"
done
fi
[ -x "$steam_root/steamrtarm64/steam" ] && [ -f "$stamp" ] && exit 0
work=$(mktemp -d)
@@ -92,7 +68,3 @@ ln -sfn "$steam_root/linuxarm64" "$HOME/.steam/sdkarm64"
ln -sfn "$steam_root/steamrtarm64" "$HOME/.steam/binarm64"
ln -sfn "$steam_root/linux32" "$HOME/.steam/sdk32"
echo "$version" > "$stamp"
if [ -n "$repair" ]; then
echo repaired > "$unconfirmed"
rm -f "$repair_request"
fi
@@ -219,9 +219,10 @@ def main():
for game in games:
if not game.get("exe") or not game.get("name"):
continue
entry = shortcut(game)
# A store's own launch arguments (a GOG play task's) unless the user has set some in Steam.
entry = shortcut(game, game.get("args") or "")
previous = managed.get(entry["appid"])
if previous and isinstance(previous.get("LaunchOptions"), str):
if previous and isinstance(previous.get("LaunchOptions"), str) and previous["LaunchOptions"]:
entry["LaunchOptions"] = previous["LaunchOptions"]
ours.append(entry)
entries = {str(i): v for i, v in enumerate(kept + ours)}
@@ -632,18 +632,17 @@ def installed_apps(steam_root):
APPINFO_CACHE = {}
STEAM_PLAY_MANIFESTS = 891390
def appinfo_entries(path):
def appinfo_platforms(path, wanted):
import struct
try:
stamp = os.stat(path).st_mtime_ns
except OSError:
return {}
cached = APPINFO_CACHE.get(path)
if cached and cached[0] == stamp:
return cached[1]
if cached and cached[0] == stamp and wanted <= cached[1].keys() | cached[2]:
return {app: cached[1][app] for app in wanted if app in cached[1]}
try:
with open(path, "rb") as f:
data = f.read()
@@ -656,19 +655,16 @@ def appinfo_entries(path):
return {}
offset = 8
strings = None
try:
if magic == 0x07564429:
table = struct.unpack_from("<q", data, offset)[0]
offset += 8
count = struct.unpack_from("<I", data, table)[0]
position = table + 4
strings = []
for _ in range(count):
end = data.index(b"\0", position)
strings.append(data[position:end].decode("utf-8", "replace"))
position = end + 1
except (ValueError, IndexError, struct.error):
return {}
if magic == 0x07564429:
table = struct.unpack_from("<q", data, offset)[0]
offset += 8
count = struct.unpack_from("<I", data, table)[0]
position = table + 4
strings = []
for _ in range(count):
end = data.index(b"\0", position)
strings.append(data[position:end].decode("utf-8", "replace"))
position = end + 1
header = 4 + 4 + 8 + 20 + 4 + (20 if magic >= 0x07564428 else 0)
def section(position):
@@ -701,58 +697,23 @@ def appinfo_entries(path):
raise ValueError("unknown appinfo field type %d" % kind)
found = {}
while offset + 8 <= len(data):
try:
try:
while offset + 8 <= len(data):
app, size = struct.unpack_from("<II", data, offset)
except struct.error:
break
if app == 0:
break
start = offset + 8
offset = start + size
try:
if app == 0:
break
start = offset + 8
offset = start + size
if str(app) not in wanted:
continue
info = section(start + header)[0].get("appinfo", {})
except (ValueError, IndexError, struct.error):
continue
if not isinstance(info, dict):
continue
common = info.get("common", {}) if isinstance(info.get("common"), dict) else {}
deck = common.get("steam_deck_compatibility")
configuration = deck.get("configuration") if isinstance(deck, dict) else None
recommended = configuration.get("recommended_runtime", "") if isinstance(configuration, dict) else ""
entry = {
"oslist": {part.strip().lower() for part in str(common.get("oslist", "")).split(",") if part.strip()},
"osarch": str(common.get("osarch", "")).lower(),
"type": str(common.get("type", "")).lower(),
"recommended": str(recommended),
}
if app == STEAM_PLAY_MANIFESTS:
extended = info.get("extended", {})
mappings = extended.get("app_mappings", {}) if isinstance(extended, dict) else {}
entry["app_mappings"] = {str(m.get("appid", key)): str(m.get("tool", "")) for key, m in mappings.items()
if isinstance(m, dict)} if isinstance(mappings, dict) else {}
found[str(app)] = entry
APPINFO_CACHE[path] = (stamp, found)
return found
def appinfo_platforms(path, wanted):
entries = appinfo_entries(path)
return {app: (entries[app]["oslist"], entries[app]["osarch"], entries[app]["type"]) for app in wanted if app in entries}
def valve_picks(steam_root):
entries = appinfo_entries(os.path.join(steam_root, "appcache", "appinfo.vdf"))
mapped = {app for app, tool in entries.get(str(STEAM_PLAY_MANIFESTS), {}).get("app_mappings", {}).items() if tool}
picks = set()
for app, entry in entries.items():
if app in NOT_GAMES or entry["type"] not in PLAYABLE_TYPES:
continue
if entry["oslist"] and "windows" not in entry["oslist"]:
continue
if entry["recommended"] or app in mapped:
picks.add(app)
return sorted(picks, key=int)
common = info.get("common", {}) if isinstance(info, dict) else {}
oslist = {part.strip().lower() for part in str(common.get("oslist", "")).split(",") if part.strip()}
found[str(app)] = (oslist, str(common.get("osarch", "")).lower(), str(common.get("type", "")).lower())
except (ValueError, IndexError, struct.error):
return {}
APPINFO_CACHE[path] = (stamp, found, set(wanted))
return {app: found[app] for app in wanted if app in found}
def native_targets(steam_root, apps):
@@ -850,22 +811,21 @@ def app_order(app):
return (len(app), app)
def plan_mapping(current, installed, runnable, default, auto, native=None, picks=()):
def plan_mapping(current, installed, runnable, default, auto, native=None):
runnable = {n.lower() for n in runnable}
installed = set(installed)
picks = set(picks)
native = native or {}
changes, kept = {}, {}
if current.get("0", "") != default:
changes["0"] = default
for app in sorted((set(current) | installed | picks | set(auto)) - {"0"}, key=app_order):
for app in sorted((set(current) | installed | set(auto)) - {"0"}, key=app_order):
name = current.get(app, "")
mine = auto.get(app)
target = native.get(app, default)
stale = unrunnable(name, runnable) or (app in native and linux_runtime_tool(name))
if name and not stale and (mine is None or name != mine):
continue
if not name and app not in installed and app not in picks:
if not name and app not in installed:
continue
if name != target:
changes[app] = target
@@ -1016,7 +976,7 @@ def live_helper_running(directory=None):
return False
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False, picks=()):
def register_default(config_path, apps=(), protect=(), default=None, catalog=None, directory=None, settle=False):
"""Writes the mapping: the "0" default and every title that follows it (see plan_mapping).
With settle, the default itself is decided first (see choose_default): before the client
starts, config.vdf holds what the client last kept, menu changes included."""
@@ -1039,7 +999,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
else:
default = state.get("default") if state.get("default") in names else TOOL
steam_root = os.path.dirname(os.path.dirname(os.path.abspath(config_path)))
changes, auto = plan_mapping(current, apps, names, default, followers(state, current), native_targets(steam_root, apps), picks)
changes, auto = plan_mapping(current, apps, names, default, followers(state, current), native_targets(steam_root, apps))
for app, tool in changes.items():
set_mapping(tokens, mapping, app, tool)
text = serialize(tokens)
@@ -1136,9 +1096,8 @@ def main():
print("steam-compatibility: the live helper keeps the client's mapping; tools listed")
elif os.path.isfile(config):
apps = installed_apps(steam_root)
picks = valve_picks(steam_root)
default = register_default(config, apps, protect=extras, catalog=catalog, settle=not steam_running(), picks=picks)
print("steam-compatibility: default, %d installed title(s) and %d title(s) with a Valve pick set to %s" % (len(apps), len(picks), default))
default = register_default(config, apps, protect=extras, catalog=catalog, settle=not steam_running())
print("steam-compatibility: default and %d installed title(s) set to %s" % (len(apps), default))
sync = os.path.join(os.path.dirname(os.path.realpath(__file__)), "droiddeck-esync")
if os.path.isfile(sync):
try:
+2 -38
View File
@@ -465,12 +465,8 @@ class AppInfoTest(unittest.TestCase):
return out + b"\x08"
body = b""
for app, entry in apps.items():
if isinstance(entry, dict):
data = section({"appinfo": dict(entry, appid=str(app))})
else:
oslist, osarch, kind = entry
data = section({"appinfo": {"appid": str(app), "common": {"type": kind, "oslist": oslist, "osarch": osarch}}})
for app, (oslist, osarch, kind) in apps.items():
data = section({"appinfo": {"appid": str(app), "common": {"type": kind, "oslist": oslist, "osarch": osarch}}})
header = struct.pack("<IIQ", 2, 0, 0) + b"\0" * 20 + struct.pack("<I", 1) + (b"\0" * 20 if magic >= 0x07564428 else b"")
body += struct.pack("<II", app, len(header) + len(data)) + header + data
body += struct.pack("<I", 0)
@@ -494,38 +490,6 @@ class AppInfoTest(unittest.TestCase):
targets = self.COMPAT["native_targets"](str(steam), ["10", "20", "30", "40", "50", "70", "80", "90", "1628350", "60"])
self.assertEqual(targets, {"20": "droiddeck-fex", "50": "droiddeck-fex"}, hex(magic))
def test_titles_with_a_valve_pick_are_found_installed_or_not(self):
def deck(oslist, runtime, kind="game"):
common = {"type": kind, "oslist": oslist, "steam_deck_compatibility": {"configuration": {"recommended_runtime": runtime}}}
if oslist is None:
del common["oslist"]
return {"common": common}
for magic in (0x07564427, 0x07564428, 0x07564429):
with tempfile.TemporaryDirectory() as tmp:
steam = Path(tmp)
(steam / "appcache").mkdir()
(steam / "appcache/appinfo.vdf").write_bytes(self.appinfo({
10: deck("windows", "proton-stable"), 11: deck("windows,linux", "native"), 12: deck(None, "proton-7.0-5"),
13: deck("linux", "native"), 14: deck("windows", "proton-stable", "Tool"), 15: ("windows", "", "game"),
16: ("windows", "", "game"), 1628350: deck("linux", "native", "game"),
891390: {"common": {"type": "Config"}, "extended": {"app_mappings": {
"16": {"appid": "16", "tool": "proton-stable"}, "17": {"appid": "17", "tool": ""}}}},
}, magic))
self.COMPAT["APPINFO_CACHE"].clear()
self.assertEqual(self.COMPAT["valve_picks"](str(steam)), ["10", "11", "12", "16"], hex(magic))
def test_titles_with_a_valve_pick_follow_the_default_until_the_user_picks(self):
tool = self.COMPAT["TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
{"0": tool, "31": "GE-Proton11-7", "32": "proton_11_arm64", "33": "steamlinuxruntime"},
["40"], [tool, "GE-Proton11-7"], tool, {}, {}, ["30", "31", "32", "33"])
self.assertEqual(changes, {"30": tool, "32": tool, "40": tool})
self.assertEqual(auto, {"30": tool, "32": tool, "40": tool})
changes, auto = self.COMPAT["plan_mapping"](
{"0": "GE-Proton11-7", "30": tool, "31": "GE-Proton11-7", "32": tool}, [], [tool, "GE-Proton11-7"], "GE-Proton11-7", auto, {}, ["30", "31", "32"])
self.assertEqual(changes, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
self.assertEqual(auto, {"30": "GE-Proton11-7", "32": "GE-Proton11-7"})
def test_the_mapping_sends_native_titles_to_fex_and_keeps_picks(self):
tool, fex = self.COMPAT["TOOL"], self.COMPAT["FEX_TOOL"]
changes, auto = self.COMPAT["plan_mapping"](
+145
View File
@@ -0,0 +1,145 @@
import io
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
from test_steam_games import BIN, imports, load, shortcuts
gog = load('droiddeck-gog')
# Stands in for gogdl: answers info/auth like it, and "downloads" by writing the game's info file.
FAKE_GOGDL = r'''
import json, os, sys
args = sys.argv[1:]
auth = args[args.index("--auth-config-path") + 1]
args = args[args.index("--auth-config-path") + 2:]
cmd = args[0]
if cmd == "auth":
if "--code" in args:
print(json.dumps({"error": True}) if args[-1] == "bad" else json.dumps({"access_token": "A", "refresh_token": "R", "user_id": "7", "expires_in": 3600, "loginTime": 1000}))
elif os.path.exists(auth):
print(json.dumps({"access_token": "A", "refresh_token": "R", "user_id": "7", "expires_in": 3600, "loginTime": 1000}))
else:
print("null")
elif cmd == "info":
print("[MAIN] INFO: working", file=sys.stderr)
print(json.dumps({"folder_name": "Example", "languages": ["de-DE", "en-US"], "buildId": "b1",
"size": {"*": {"download_size": 100, "disk_size": 200}, "en-US": {"download_size": 10, "disk_size": 20},
"de-DE": {"download_size": 5, "disk_size": 6}}}))
elif cmd == "download":
base = args[args.index("--path") + 1]
if os.environ.get("FAIL"):
print("[DOWNLOAD] ERROR: disk full", file=sys.stderr)
sys.exit(1)
for p in ("0.00 0/100", "50.10 50/100", "50.90 51/100", "100.00 100/100"):
print("[PROGRESS] INFO: = Progress: %s, Running for: 00:00:01, ETA: 00:00:01" % p, file=sys.stderr)
target = os.path.join(base, "Example")
os.makedirs(target, exist_ok=True)
open(os.path.join(target, "goggame-%s.info" % args[1]), "w").write("{}")
'''
class GogHelperTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
fake = self.root / 'gogdl'
fake.write_text(FAKE_GOGDL)
patcher = patch.object(gog, 'GOGDL', str(fake))
patcher.start()
self.addCleanup(patcher.stop)
self.auth = str(self.root / 'gog/auth.json')
def run_helper(self, *args):
out = io.StringIO()
with redirect_stdout(out):
status = gog.main(['droiddeck-gog'] + list(args))
lines = [json.loads(line) for line in out.getvalue().splitlines() if line.startswith('{')]
return status, lines, out.getvalue()
def test_token_output_never_carries_the_refresh_token(self):
Path(self.auth).parent.mkdir()
Path(self.auth).write_text('{}')
status, lines, raw = self.run_helper('token', self.auth)
self.assertEqual(0, status)
self.assertEqual({'e': 'token', 'access_token': 'A', 'user_id': '7', 'expires': 4600}, lines[0])
self.assertNotIn('"R"', raw)
def test_signed_out_without_the_auth_file(self):
status, lines, _ = self.run_helper('token', self.auth)
self.assertEqual(1, status)
self.assertEqual('error', lines[0]['e'])
def test_login_reports_success_without_tokens(self):
status, lines, raw = self.run_helper('login', self.auth, 'good')
self.assertEqual((0, [{'e': 'done', 'user_id': '7'}]), (status, lines))
self.assertNotIn('access_token', raw)
status, lines, _ = self.run_helper('login', self.auth, 'bad')
self.assertEqual(1, status)
def test_sizes_are_shared_depots_plus_one_language(self):
status, lines, _ = self.run_helper('info', self.auth, '42')
self.assertEqual(0, status)
self.assertEqual(dict(e='info', folder='Example', language='en-US', download_size=110, disk_size=220, build='b1'), lines[0])
def test_install_reports_progress_once_per_percent_and_marks_the_folder(self):
base = self.root / 'GOG'
status, lines, _ = self.run_helper('install', self.auth, '42', str(base))
self.assertEqual(0, status)
self.assertEqual([0, 50, 100], [line['percent'] for line in lines if line['e'] == 'progress'])
self.assertEqual({'e': 'done', 'dir': str(base / 'Example')}, lines[-1])
self.assertEqual('42', json.loads((base / 'Example' / gog.MARKER).read_text())['id'])
def test_failed_download_passes_on_gogdls_error(self):
with patch.dict('os.environ', {'FAIL': '1'}):
status, lines, _ = self.run_helper('install', self.auth, '42', str(self.root / 'GOG'))
self.assertEqual(1, status)
self.assertEqual({'e': 'error', 'message': 'disk full'}, lines[-1])
class StoreShortcutsTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / 'Steam'
self.acct = self.steam / 'userdata/123'
(self.acct / 'config').mkdir(parents=True)
folder = self.root / 'GOG/Example'
folder.mkdir(parents=True)
(folder / 'Example.exe').write_bytes(b'game')
self.game = dict(name='Example', exe=str(folder / 'Example.exe'), folder=str(folder), dir=str(folder),
appid=0x87654321, args='-windowed', store='gog')
def write(self, *games):
listing = self.root / 'games.json'
listing.write_text(json.dumps(list(games)))
subprocess.run(['python3', str(BIN / 'droiddeck-steam-shortcuts'), str(self.steam), str(listing)], check=True, capture_output=True)
return list(shortcuts.parse((self.acct / 'config/shortcuts.vdf').read_bytes())['shortcuts'].values())
def test_store_arguments_become_launch_options(self):
self.assertEqual('-windowed', self.write(self.game)[0]['LaunchOptions'])
def test_launch_options_set_in_steam_are_kept(self):
self.write(self.game)
path = self.acct / 'config/shortcuts.vdf'
entries = shortcuts.parse(path.read_bytes())['shortcuts']
entries['0']['LaunchOptions'] = '-dx11'
path.write_bytes(shortcuts.write({'shortcuts': entries}))
self.assertEqual('-dx11', self.write(self.game)[0]['LaunchOptions'])
def test_store_games_are_never_routed_to_an_owned_steam_title(self):
imports.save_json(self.acct / 'config' / imports.STATE,
dict(account='123', owned={'42': True}, candidates={self.game['folder']: 42},
sources={self.game['folder']: imports.source_stamp(self.game)}))
games, routes = imports.route(self.steam, self.acct, [self.game])
self.assertEqual(([self.game], {}), (games, routes))
if __name__ == '__main__':
unittest.main()
-63
View File
@@ -38,10 +38,6 @@ cp "$TEST_CDN/${2##*/}" "$4"
sha = self.bin / 'sha256sum'
sha.write_text('#!/bin/bash\nexec shasum -a 256 "$@"\n')
sha.chmod(0o755)
if shutil.which('sha1sum') is None:
sha1 = self.bin / 'sha1sum'
sha1.write_text('#!/bin/bash\nexec shasum -a 1 "$@"\n')
sha1.chmod(0o755)
self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data),
PATH=str(self.bin) + os.pathsep + os.environ['PATH'],
TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests))
@@ -108,65 +104,6 @@ cp "$TEST_CDN/${2##*/}" "$4"
self.assertEqual(0, self.install('publicbeta').returncode)
self.assertEqual('publicbeta\n', (self.steam / 'package/beta').read_text())
def break_client(self, starts):
self.assert_installed('steamdeck_publicbeta')
self.requests.unlink()
package = self.steam / 'package'
(self.steam / 'steamrtarm64/steam').write_text('half updated')
(package / 'steam_client_steamdeck_publicbeta_linuxarm64.manifest').write_text('manifest')
(package / 'steam_client_steamdeck_publicbeta_linuxarm64.installed').write_text('installed')
good = b'complete package'
(package / ('bins_linuxarm64.zip.vz.' + hashlib.sha1(good).hexdigest() + '_16')).write_bytes(good)
(package / ('bins_misc_linuxarm64.zip.vz.' + hashlib.sha1(b'whole').hexdigest() + '_5')).write_bytes(b'wh')
(package / ('strings_all.zip.' + hashlib.sha1(b'strings').hexdigest())).write_bytes(b'strings')
(self.steam / '.crash').write_text('')
(package / 'droiddeck-unconfirmed').write_text('start\n' * starts)
return package
def test_two_starts_with_nothing_shown_fetch_the_client_again(self):
package = self.break_client(2)
self.assert_installed('steamdeck_publicbeta')
self.assertEqual('repaired\n', (package / 'droiddeck-unconfirmed').read_text())
self.assertFalse((self.steam / '.crash').exists())
self.assertEqual([], sorted(p.name for p in package.glob('steam_client_*')))
self.assertEqual(['bins_linuxarm64.zip.vz.', 'strings_all.zip.'],
sorted(p.name[:p.name.rindex('.') + 1] for p in package.glob('*.zip.*')))
def test_one_start_with_nothing_shown_is_left_alone(self):
package = self.break_client(1)
self.assertEqual(0, self.install().returncode)
self.assertFalse(self.requests.exists())
self.assertEqual('half updated', (self.steam / 'steamrtarm64/steam').read_text())
self.assertTrue((package / 'steam_client_steamdeck_publicbeta_linuxarm64.installed').exists())
def test_a_repair_is_not_repeated_until_the_client_has_been_seen(self):
package = self.break_client(2)
self.assertEqual(0, self.install().returncode)
self.requests.unlink()
with (package / 'droiddeck-unconfirmed').open('a') as marker:
marker.write('start\nstart\nstart\n')
self.assertEqual(0, self.install().returncode)
self.assertFalse(self.requests.exists())
def test_requested_repair_runs_once_and_is_retried_until_it_completes(self):
package = self.break_client(0)
(package / 'droiddeck-unconfirmed').unlink()
request = self.home / '.bl-steam-repair'
request.write_text('1\n')
archive = self.cdn / 'steamdeck_publicbeta.zip'
original = archive.read_bytes()
archive.write_bytes(b'corrupt download')
self.assertNotEqual(0, self.install().returncode)
self.assertTrue(request.exists())
self.assertFalse((package / 'droiddeck-installed').exists())
archive.write_bytes(original)
self.requests.unlink()
self.assert_installed('steamdeck_publicbeta')
self.assertFalse(request.exists())
self.requests.unlink()
self.assertEqual(0, self.install().returncode)
self.assertFalse(self.requests.exists())
def test_invalid_channel_fails_before_any_download(self):
result = self.install('../unknown')
self.assertNotEqual(0, result.returncode)