Compare commits

..
73 changed files with 879 additions and 2731 deletions

No files matched your search

+1 -1
View File
@@ -210,7 +210,7 @@ jobs:
done
if [ -f tools/gamescope/release.env ]; then
. tools/gamescope/release.env
gh release download "${GAMESCOPE_TAG}" -R "${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}" -p gamescope.tzst -O gamescope.tzst
gh release download "${GAMESCOPE_TAG}" -R "${GITHUB_REPOSITORY}" -p gamescope.tzst -O gamescope.tzst
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
test -f "$D/usr/local/bin/gamescope"
+1
View File
@@ -4,6 +4,7 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Session logs go to Downloads so a failed run can be handed over as one folder. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
@@ -121,6 +121,7 @@ class MainActivity : ComponentActivity() {
private var steamDeckMode by mutableStateOf(false)
private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true)
private var dualXwayland by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
private var showProtons by mutableStateOf(false)
// Components page: FEX / DXVK / VKD3D-Proton per Proton (ComponentsManager).
@@ -175,16 +176,6 @@ class MainActivity : ComponentActivity() {
refreshWifiDiscovery()
}
}
private val mediaRefresh = Runnable {
refresh()
refreshAddedGames()
}
private val mediaReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
ui.removeCallbacks(mediaRefresh)
ui.postDelayed(mediaRefresh, MEDIA_SETTLE_MS)
}
}
private val wifiLocationPermission = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
refreshWifiDiscovery()
@@ -340,7 +331,6 @@ class MainActivity : ComponentActivity() {
private var hdrReason by mutableStateOf<String?>(null)
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var backActionsInverted by mutableStateOf(false)
private var renderer by mutableStateOf("vulkan")
@@ -822,6 +812,9 @@ class MainActivity : ComponentActivity() {
if (savedInstanceState == null) ui.post { startSteamAtStartupIfEnabled() }
// The session's logs land in Downloads so a failed run can be handed over as a folder
// rather than dug out of app-private storage. targetSdk 28 means the old permission still
// grants exactly that.
val wanted = ArrayList<String>()
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
@@ -934,11 +927,6 @@ class MainActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
registerReceiver(wifiLocationReceiver, android.content.IntentFilter(android.location.LocationManager.MODE_CHANGED_ACTION))
registerReceiver(mediaReceiver, android.content.IntentFilter().apply {
for (action in listOf(Intent.ACTION_MEDIA_MOUNTED, Intent.ACTION_MEDIA_UNMOUNTED, Intent.ACTION_MEDIA_REMOVED,
Intent.ACTION_MEDIA_EJECT, Intent.ACTION_MEDIA_BAD_REMOVAL)) addAction(action)
addDataScheme("file")
})
displayManager.registerDisplayListener(secondScreenDisplayListener, ui)
refreshSecondScreenDisplays()
}
@@ -950,8 +938,6 @@ class MainActivity : ComponentActivity() {
override fun onStop() {
unregisterReceiver(wifiLocationReceiver)
unregisterReceiver(mediaReceiver)
ui.removeCallbacks(mediaRefresh)
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
// The session covers the page by now; coming back finds it as it was.
flood = null
@@ -1178,7 +1164,6 @@ class MainActivity : ComponentActivity() {
gpuDrivers = drivers.summary(),
touchMode = touchMode,
suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
pipAutoEnter = pipAutoEnter,
oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null,
@@ -1198,6 +1183,7 @@ class MainActivity : ComponentActivity() {
steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode,
steamRepairQueued = steamRepairQueued,
mangoapp = mangoapp,
dualXwayland = dualXwayland,
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
runSteamAtStartup = mode == SessionService.MODE_STEAM && runSteamAtStartup,
wifiDiscovery = if (mode == SessionService.MODE_STEAM) wifiDiscovery else null,
@@ -1238,10 +1224,6 @@ class MainActivity : ComponentActivity() {
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this, mode, policy); suspendPolicy = policy },
onSteamDownloadsInBackground = { enabled ->
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
steamDownloadsInBackground = enabled
},
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
onBackActionsInverted = { inverted ->
@@ -1285,6 +1267,7 @@ class MainActivity : ComponentActivity() {
steamChannel = SessionPrefs.steamChannel(this)
},
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
onDualXwayland = { on -> SessionPrefs.setDualXwayland(this, on); dualXwayland = on },
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
onRunSteamAtStartup = { on ->
SessionPrefs.setRunSteamAtStartup(this, on)
@@ -1363,7 +1346,7 @@ class MainActivity : ComponentActivity() {
/** Walks the added-games folders, which can sit on slow shared storage or an SD card. */
private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, (g.candidates + g.exe).map { c -> c.path to c.name }.distinctBy { it.first })
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, g.candidates.map { c -> c.path to c.name }.distinctBy { it.first })
}
private fun fetchAddedGameArt() {
@@ -1400,6 +1383,7 @@ class MainActivity : ComponentActivity() {
steamDeckMode = SessionPrefs.steamDeckMode(this)
steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this)
dualXwayland = SessionPrefs.dualXwayland(this)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
@@ -1410,7 +1394,6 @@ class MainActivity : ComponentActivity() {
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
touchMode = SessionPrefs.touchMode(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
@@ -1639,7 +1622,6 @@ class MainActivity : ComponentActivity() {
companion object {
private const val TAG = "MainActivity"
private const val MEDIA_SETTLE_MS = 1500L
/** What the picker offers for a driver zip; some file apps label a zip as a plain stream. */
private val ZIP_EXT = listOf("zip")
private val WCP_EXT = listOf("wcp")
@@ -246,7 +246,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var frameGen by mutableStateOf(FrameGen.Mode.OFF)
private var fexPreset by mutableStateOf("")
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var onScreenButtonsVisible by mutableStateOf(false)
private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode)
@@ -511,8 +510,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
frameGen = frameGen,
lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy, touchMode = touchMode,
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
@@ -564,11 +562,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
suspendPolicy = policy
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onSteamDownloadsInBackground = { enabled ->
SessionPrefs.setSteamDownloadsInBackground(this@SessionActivity, enabled)
steamDownloadsInBackground = enabled
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode,
@@ -796,7 +789,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
frameGen = FrameGen.mode(this)
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = SessionPrefs.oscMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
}
@@ -15,7 +15,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.session.SessionArtifacts
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionService
@@ -51,7 +50,6 @@ class AgentBridgeProvider : ContentProvider() {
val response = try {
when (method) {
"state" -> state(context).put("ok", true)
"logs" -> exportLogs(context)
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
"stop" -> stop(context)
"resume" -> resume(context)
@@ -65,7 +63,7 @@ class AgentBridgeProvider : ContentProvider() {
private fun state(context: Context): JSONObject {
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
val session = JSONObject()
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
.put("phase", SessionState.phase.name)
@@ -103,12 +101,10 @@ class AgentBridgeProvider : ContentProvider() {
.put("session", session)
}
private fun exportLogs(context: Context): JSONObject {
val dir = SessionState.logDirectory ?: SessionLogShare.latest(context)
?: return error("NO_SESSION_LOGS", "No session logs are available")
val zip = SessionLogShare.zipFolder(context, dir)
?: return error("NO_SESSION_LOGS", "No diagnostic logs are available")
return JSONObject().put("ok", true).put("sessionId", dir.name).put("path", zip.absolutePath)
private fun latestSessionDirectory(): File? {
val parent = LinuxRuntime.debugLogDir()
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
}
private fun stop(context: Context): JSONObject {
@@ -154,6 +154,7 @@ object DeviceReport {
k("No GL error checks", SessionPrefs.noGlError(context))
k("Steam Deck mode", SessionPrefs.steamDeckMode(context))
k("Steam controller", SessionPrefs.steamController(context))
k("Two Xwayland servers", SessionPrefs.dualXwayland(context))
k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") +
" (sharpness ${SessionPrefs.upscaleSharpness(context)}%)")
k("FEX preset", SessionPrefs.fexPreset(context).ifEmpty { "FEX defaults" })
@@ -36,16 +36,11 @@ object LogRedactor {
* WebAPI key is caught by [WEBAPI_KEY]. The value class excludes `<` and `>` so running this
* twice over an already-scrubbed line changes nothing.
*/
private const val SECRET_KEYS =
"access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret"
private val SECRET_KV = Regex(
"(?i)\\b($SECRET_KEYS)" +
"([\"']?\\s*[=:]\\s*[\"']?)([^\\s\"'<>&;,]{1,})"
)
private val QUOTED_SECRET = Regex(
"(?i)\\b($SECRET_KEYS)([\"']?\\s*[=:]\\s*)(\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*')"
"(?i)\\b(access[_-]?token|refresh[_-]?token|auth[_-]?token|authtoken|token|authcode|" +
"auth[_-]?ticket|ticket|sessionid|steamloginsecure|webapikey|api[_-]?key|" +
"machine[_-]?auth(?:[_-]?token)?|machineauth|password|passwd|pwd|secret)" +
"(\\s*[=:]\\s*|=)([^\\s\"'<>&;,]{4,})"
)
/** A Steam Guard code, only where the text around it says that is what it is. */
private val GUARD_CODE = Regex(
@@ -58,7 +53,6 @@ object LogRedactor {
"(?i)\\b(jwt|token|ticket|sessionid|steamloginsecure|machineauth)\\b[\\s=:]*([A-Za-z0-9+/=_\\-]{12,})"
)
private val LONG_TOKEN = Regex("[A-Za-z0-9_\\-]{88,}")
private val AUTHORIZATION = Regex("(?i)(\\b(?:proxy-)?authorization[\"']?\\s*[:=]\\s*[\"']?)[^\\r\\n\"']+")
private val STEAMID64 = Regex("\\b(76561)(\\d{8})(\\d{4})\\b")
private val STEAMID3 = Regex("\\[U:1:(\\d+)]")
/** "external address 2607:..." / "external IP: 203.0.113.9" - the client stating ours. */
@@ -185,6 +179,30 @@ object LogRedactor {
return out
}
/** A file worth scrubbing: text (no NUL in its first 4 KB) and not huge. */
fun isText(file: java.io.File): Boolean = try {
file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input ->
val buf = ByteArray(4096)
val n = input.read(buf)
n <= 0 || (0 until n).none { buf[it].toInt() == 0 }
}
} catch (e: Exception) {
false
}
/**
* Bump whenever a pattern is added or tightened. A session folder records the version it was
* scrubbed under (SessionArtifacts.SCRUBBED_TREE_MARKER), and a share copies a file as it is
* only when that matches, so a folder scrubbed under older rules is scrubbed again on the way
* out.
*/
const val RULES_VERSION = 1
/** [src]'s lines, scrubbed, to [out]. */
fun scrubTo(src: java.io.File, out: java.io.Writer) {
src.forEachLine { line -> out.write(redact(line)); out.write("\n") }
}
/** [line] with every credential shape replaced. Null- and exception-safe by construction. */
fun redact(line: String): String {
if (line.isEmpty()) return line
@@ -193,11 +211,6 @@ object LogRedactor {
out = GUID.replace(out, "<redacted:guid>")
out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}<redacted:jwt>" }
out = JWT_BASE64.replace(out, "<redacted:jwt>")
out = AUTHORIZATION.replace(out) { "${it.groupValues[1]}<redacted:authorization>" }
out = QUOTED_SECRET.replace(out) {
val quote = it.groupValues[3].first()
"${it.groupValues[1]}${it.groupValues[2]}$quote<redacted:token>$quote"
}
out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}<redacted:token>" }
out = GUARD_CODE.replace(out) { "${it.groupValues[1]}<redacted:code>" }
out = WEBAPI_KEY.replace(out, "<redacted:key>")
@@ -49,7 +49,7 @@ object SessionLogCapture {
) { line ->
synchronized(this) {
try {
if (writer === out) out.apply { write(line); newLine(); flush() }
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
// A full or unmounted card must not take the session with it.
}
@@ -22,7 +22,6 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FileCopy
@@ -313,47 +312,6 @@ internal fun FileItemRow(
}
}
// The ".." row at the top of a folder: one level up, styled like a folder row so it reads as part
// of the list and takes controller focus the same way.
@Composable
internal fun ParentFolderRow(compact: Boolean = false, onTap: () -> Unit) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 3.dp)
.clickable(onClick = onTap),
shape = RoundedCornerShape(10.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp),
) {
Icon(
imageVector = Icons.Filled.ArrowUpward,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(if (compact) 24.dp else 36.dp),
)
Spacer(Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "..",
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
)
Text(
text = stringResource(R.string.fm_up_one_level),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
)
}
}
}
}
// Dedicated Favorites list that replaces the file list while the star toggle is on.
// Reads the store keyed on [favTick] so it recomposes after any pin/unpin.
@Composable
@@ -99,10 +99,5 @@ fun describeLocation(file: File): FavLocation {
}
}
// The Linux system's root (the app's files/linuxfs, the sessions' /) and anything under it.
if (Regex("/files/linuxfs(/|$)").containsMatchIn(abs)) {
return FavLocation(FavStorage.OTHER, R.string.fm_drive_linux, abs)
}
return FavLocation(FavStorage.OTHER, R.string.fm_drive_storage, abs)
}
@@ -22,7 +22,6 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.rememberLazyListState
@@ -42,7 +41,6 @@ import androidx.compose.material.icons.filled.ViewList
import androidx.compose.material.icons.filled.StarBorder
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material.icons.filled.Smartphone
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.Image
@@ -145,14 +143,7 @@ fun FileManagerScreen(
val name = abs.removePrefix("/storage/").substringBefore('/')
if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else rootDir
}
// A game's own folder or Proton prefix lives in the app's private storage, which has no
// volume above it: floor at the app's files dir so up/back still reach the library roots.
else -> {
val appFiles = runCatching { context.filesDir.canonicalPath }.getOrNull()
generateSequence(rootDir) { it.parentFile }
.firstOrNull { appFiles != null && runCatching { it.canonicalPath }.getOrNull() == appFiles }
?: rootDir
}
else -> rootDir
}
mutableStateOf(vol)
}
@@ -241,9 +232,7 @@ fun FileManagerScreen(
loadDirectory(dir)
}
// Open the start dir without openDrive(): that pins the floor to the start dir itself, which
// greyed out up/back whenever the manager was opened at a game's folder.
LaunchedEffect(Unit) { loadDirectory(rootDir) }
LaunchedEffect(Unit) { openDrive(rootDir) }
// System/gesture Back: while the Favorites view is open it closes that first; otherwise
// it goes up one directory. Only at the current drive's root with Favorites closed is it
@@ -257,14 +246,6 @@ fun FileManagerScreen(
if (parent != null && parent.exists()) loadDirectory(parent)
}
// One level up, never above the current drive's root: shared by the toolbar arrow and the
// ".." row at the top of the list.
val canGoUp = currentDir != currentRoot && currentDir.parentFile?.exists() == true
fun goUp() {
val parent = currentDir.parentFile
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
}
// Resolve a non-colliding destination in [dir] for [name] (foo.txt -> "foo (1).txt").
fun uniqueDestination(dir: File, name: String): File {
var candidate = File(dir, name)
@@ -431,9 +412,6 @@ fun FileManagerScreen(
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
val drives = remember(storageTick) { StorageRoots.list(context) }
val linuxRoot = remember(storageTick) {
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context).takeIf { File(it, "usr").isDirectory }
}
// ── Dialogs ──
@@ -639,7 +617,11 @@ fun FileManagerScreen(
.background(MaterialTheme.colorScheme.surfaceContainer)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { goUp() }, enabled = canGoUp) {
IconButton(onClick = {
val parent = currentDir.parentFile
// Don't climb above the current drive's root.
if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent)
}, enabled = currentDir != currentRoot) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
}
@@ -694,16 +676,6 @@ fun FileManagerScreen(
},
)
}
linuxRoot?.let { root ->
MenuItemDivider()
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_drive_linux)) },
leadingIcon = {
Icon(Icons.Filled.Terminal, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
},
onClick = { showDriveMenu = false; openDrive(root) },
)
}
}
}
@@ -1012,14 +984,13 @@ fun FileManagerScreen(
showFavorites = false; if (d.readable) openDrive(d.dir)
})
}
// The Linux system the sessions run in: its own / (the desktop's root), once installed.
linuxRoot?.let { add(locItem(stringResource(R.string.fm_drive_linux), Icons.Filled.Terminal, it)) }
}
val quickItems = buildList {
File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_downloads), Icons.Filled.Download, it, stringResource(R.string.fm_rail_downloads_short))) }
// The ROMs folder chosen on the main screen: what the session shows as /root/ROMs.
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
?.let { add(locItem(stringResource(R.string.fm_rail_roms), Icons.Filled.SportsEsports, it)) }
File("/storage/emulated/0/Download/DroidDeck").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_session_logs), Icons.Filled.Description, it)) }
File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem(stringResource(R.string.fm_rail_pictures), Icons.Filled.Image, it)) }
}
val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } }
@@ -1073,9 +1044,6 @@ fun FileManagerScreen(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(8.dp),
) {
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
ParentFolderRow(compact = compactRows, onTap = { goUp() })
}
items(shownEntries, key = { it.absolutePath }) { file ->
val isFav = remember(file.absolutePath, favTick) {
FavoritesStore.isFavorite(context, file.absolutePath)
@@ -1141,9 +1109,6 @@ fun FileManagerScreen(
}
} else
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
if (canGoUp) item(key = "..") {
ParentFolderRow(compact = compactRows, onTap = { goUp() })
}
if (entries.isEmpty()) {
item {
Box(
@@ -98,7 +98,7 @@ object AddedGames {
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 || folder.name.equals("steamapps", ignoreCase = true)) continue
if (folder.name.lowercase() in steamInstalls) continue
scanGame(context, folder, out)
}
}
@@ -126,59 +126,32 @@ object AddedGames {
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
run {
val candidates = candidates(folder)
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val found = chosen ?: candidates.firstOrNull() ?: return
val foundGuest = guestPath(context, found)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${found.path}"); return }
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val exe = chosen ?: 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 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(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
val config = accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))
val record = config?.let { shortcutRecord(it, appId) }
val rev = record?.optInt("rev", 0) ?: 0
val adopted = guestPath(context, folder)
?.let { steamTarget(folder, it, record, foundGuest, SessionPrefs.addedGameExeSeen(context, folder.path)) }
?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) }
val exe = adopted ?: found
val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
val steamId = config?.let { steamRoute(it, appId) }
val crc = CRC32().apply { update(("\"${guestExe.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
val appId = crc or 0x80000000L
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))
}
}
private fun accountConfig(root: File): File? {
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
.lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
return account?.let { File(root, "userdata/$it/config") }
}
private fun steamRoute(config: File, appId: Long): Int? = runCatching {
JSONObject(File(config, ".droiddeck-routes.json").readText()).optInt(appId.toString()).takeIf { it > 0 }
private fun steamRoute(root: File, appId: Long): Int? = runCatching {
val users = File(root, "config/loginusers.vdf").readText()
val blocks = Regex(""""(\d{5,})"\s*\{([^}]*)\}""")
val recent = blocks.findAll(users).firstOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
?: return@runCatching null
val account = recent.groupValues[1].toLong() - 76561197960265728L
JSONObject(File(root, "userdata/$account/config/.droiddeck-routes.json").readText())
.optInt(appId.toString()).takeIf { it > 0 }
}.getOrNull()
private fun shortcutRecord(config: File, appId: Long): JSONObject? = runCatching {
JSONObject(File(config, ".droiddeck-shortcuts.json").readText()).optJSONObject("games")?.optJSONObject(appId.toString())
}.getOrNull()
internal fun steamTarget(folder: File, folderGuest: String, record: JSONObject?, guestExe: String, seen: Int): File? {
if (record == null || record.optInt("rev", 0) == seen) return null
val asked = unquote(record.optJSONObject("app")?.optString("Exe"))
val steam = unquote(record.optJSONObject("steam")?.optString("Exe"))
if (asked != guestExe || steam.isEmpty() || steam == asked || !steam.startsWith("$folderGuest/")) return null
val file = File(folder, steam.removePrefix("$folderGuest/"))
val inside = runCatching { file.canonicalPath.startsWith(folder.canonicalPath + File.separator) }.getOrDefault(false)
return file.takeIf { inside && it.isFile }
}
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
/** The list the session hands the runtime's shortcuts writer; one file per session start. */
fun writeListing(context: Context, games: List<Game>): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
@@ -188,7 +161,6 @@ 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)
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
// 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)
@@ -86,20 +86,17 @@ object Library {
return listOfNotNull(
root to "internal",
GameStorage.effective(context)?.let { File(it.path) to it.label },
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
)
}
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
fun protonPrefix(
context: Context, appId: Long, preferredLibrary: File? = null,
libraries: List<File> = steamLibraries(context).map { it.first },
): File? {
fun protonPrefix(context: Context, appId: Long, preferredLibrary: File? = null): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
val secondary = GameStorage.effective(context)?.let { File(it.path) }
fun prefixRoot(root: File): File = if (secondary != null && root.canonicalPath == secondary.canonicalPath)
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
else root
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
val roots = (listOfNotNull(preferredLibrary) + steamLibraries(context).map { it.first }).map(::prefixRoot)
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
@@ -110,7 +107,6 @@ object Library {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val cache = File(root, "appcache/librarycache")
val libraries = steamLibraries(context)
val roots = libraries.map { it.first }
val out = LinkedHashMap<Int, SteamGame>()
for ((library, label) in libraries) {
val steamapps = File(library, "steamapps")
@@ -136,7 +132,7 @@ object Library {
out[appId] = SteamGame(
appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles,
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
protonPrefix = protonPrefix(context, appId.toLong(), library),
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
)
@@ -146,19 +142,16 @@ object Library {
}
/** The same installed-game inventory used for links, shortcuts and file exports. */
fun launchableGames(context: Context, strictRead: Boolean = false): List<SteamGame> {
val roots = steamLibraries(context).map { it.first }
return (steamGames(context, strictRead) + AddedGames.scan(context).map { g ->
AddedGameArt.resolve(context, g).let { art ->
SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
)
}
}).distinctBy { it.gameId }
}
fun launchableGames(context: Context, strictRead: Boolean = false): List<SteamGame> = (steamGames(context, strictRead) + AddedGames.scan(context).map { g ->
AddedGameArt.resolve(context, g).let { art ->
SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
)
}
}).distinctBy { it.gameId }
/** Steam stores current library art inside hash-named folders under the app's cache dir. */
private fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
@@ -25,7 +25,7 @@ object GuestCommand {
linkDir: File? = null, onLine: (String) -> Unit): Int {
val log = logName?.let {
try {
File(File(LinuxRuntime.debugLogDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
File(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
} catch (e: Exception) { null }
}
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
@@ -42,12 +42,12 @@ public final class LinuxRuntime {
* session ended at once. A long host path behind it is proot's to shorten.
*/
public static final String GUEST_RUNTIME_DIR = "/run/droiddeck";
private static final String SYSTEM_FONTS = "/system/fonts";
private static final String GUEST_SYSTEM_FONTS = "/usr/local/share/fonts/android";
/** Where every Linux session's debug log lands: public, so a user can just hand the folder over. */
public static final String DEBUG_LOG_DIR = "DroidDeck";
public static File debugLogDir(Context context) {
return new File(context.getFilesDir(), "logs");
public static File debugLogDir() {
return new File(android.os.Environment.getExternalStoragePublicDirectory(
android.os.Environment.DIRECTORY_DOWNLOADS), DEBUG_LOG_DIR);
}
private LinuxRuntime() {}
@@ -207,7 +207,6 @@ public final class LinuxRuntime {
File shm = new File(context.getCacheDir(), "shm");
shm.mkdirs();
bind(cmd, shm.getPath() + ":/dev/shm");
bindSystemFonts(cmd, root);
// Android denies apps these; glibc, Steam and libcap read them at startup.
File fakeProc = new File(root, "etc/droiddeck/proc");
@@ -466,15 +465,6 @@ public final class LinuxRuntime {
return byType;
}
private static void bindSystemFonts(List<String> cmd, File root) {
File fonts = new File(SYSTEM_FONTS);
File target = new File(root, GUEST_SYSTEM_FONTS.substring(1));
if (!fonts.isDirectory() || !fonts.canRead() || !new File(root, "usr/local").isDirectory()) return;
if (target.isDirectory() || target.mkdirs()) {
bind(cmd, SYSTEM_FONTS + ":" + GUEST_SYSTEM_FONTS);
}
}
private static void bind(List<String> cmd, String spec) {
cmd.add("-b");
cmd.add(spec);
@@ -6,7 +6,6 @@ import android.os.StatFs
import android.os.storage.StorageManager
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
/**
@@ -66,25 +65,6 @@ object GameStorage {
}
}
class Library(val host: File, val guest: String, val label: String)
fun gamesFolderLibraries(context: Context): List<Library> {
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
val card = effective(context)?.let { canonical(File(it.path)) }
val sm = context.getSystemService(StorageManager::class.java)
return AddedGames.roots(context).mapNotNull { root ->
val host = canonical(root.host)
if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null
if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null
val volume = try { sm?.getStorageVolume(root.host)?.getDescription(context) } catch (e: Exception) { null }
val name = root.host.name.ifEmpty { context.getString(R.string.gstore_folder) }
val label = if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume)
Library(root.host, root.guest, label.replace('"', ' ').replace('\\', ' '))
}
}
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
/** The label the client shows for a chosen folder: its last name, or the volume's. */
fun labelFor(context: Context, path: String): String =
options(context).firstOrNull { it.path == path }?.name
@@ -23,10 +23,8 @@ object SecondaryLibrary {
return File(files, "steam-libraries/$digest")
}
val CARD_GUESTS = listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd")
/** Parent binds come first; the more specific private directories override them in PRoot. */
fun binds(files: File, library: File, guests: List<String> = CARD_GUESTS): List<String> {
fun binds(files: File, library: File): List<String> {
val private = privateRoot(files, library)
val apps = File(library, "steamapps")
val tools = LinkedHashMap(bootstrapTools)
@@ -59,7 +57,7 @@ object SecondaryLibrary {
if (lower != relative) overrides.add(target to lower)
}
}
return guests.flatMap { guest ->
return listOf("/mnt/droiddeck-sd", "/mnt/bannerlator-sd").flatMap { guest ->
listOf("${library.path}:$guest") + overrides.map { (host, relative) -> "${host.path}:$guest/$relative" }
}
}
@@ -31,9 +31,21 @@ object SessionArtifacts {
/** Written last; a folder without it did not get its ending. */
const val COMPLETE_MARKER = ".complete"
/** Every file in the folder has been through the redactor, own addresses and accounts included (-2: accounts added). */
private const val SCRUBBED_MARKER = ".scrubbed-2"
/**
* Written by a session's own ending, and only when every file in the folder, subfolders
* included (whatever the session script copied into steam/ and droiddeck-esync/ as well as what
* the app wrote), went through the redactor without a failure. It lists each of those files
* with its size and modification time, under the redactor's rules version: a share copies a
* file as it is only when all three still match ([scrubbedFiles]), and scrubs anything else -
* a file added or changed since, a hidden one, or every file of a folder without it.
*/
const val SCRUBBED_TREE_MARKER = ".scrubbed-tree"
/** Everything the end of a session gathers, into [dir]. Safe to call for a dead session. */
fun collect(context: Context, dir: File, reason: String) {
SessionLogCapture.stopFor(dir)
try {
val wayland = File(dir, "wayland.log")
if (!wayland.exists()) {
@@ -42,10 +54,11 @@ object SessionArtifacts {
}
}
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
copySteamLogs(context, dir)
val record = Record(dir)
copySteamLogs(context, dir, record)
// A session the system killed leaves its trace here and nowhere else.
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
scrubTree(dir)
markScrubbed(scrubTree(record))
SessionEvents.record("session.artifacts_collected", mapOf("reason" to reason), dir)
File(dir, COMPLETE_MARKER).writeText("collected: $reason at ${now()}\n")
} catch (e: Exception) {
@@ -53,52 +66,153 @@ object SessionArtifacts {
}
}
/**
* Once, for session folders written before every file was scrubbed and before the device's own
* addresses were (network.txt listed them; the client's IPv6 check logs "external address"
* into steam/connection_log.txt): the whole folder, steam/ included, through the redactor.
* A marker records it. Runs at app start with [finishAbandoned].
*/
@Synchronized
fun scrubOlder(context: Context) {
val current = SessionPaths.current()
val dirs = LinuxRuntime.debugLogDir().listFiles { f ->
SessionPaths.isSessionFolder(f) && f != current && !File(f, SCRUBBED_MARKER).exists()
} ?: return
if (dirs.isEmpty()) return
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
SessionPaths.sessionFolders(context).filter {
it.parentFile == LinuxRuntime.debugLogDir(context) && it != SessionPaths.current() &&
!File(it, COMPLETE_MARKER).exists()
}.forEach { scrubTree(it) }
dirs.forEach { dir ->
Record(dir).let { r -> scrubFolder(dir, r); File(dir, "steam").takeIf { it.isDirectory }?.let { scrubFolder(it, r) } }
try { File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n") } catch (e: Exception) {}
}
Log.i(TAG, "scrubbed ${dirs.size} older session folder(s)")
}
internal fun scrubTree(dir: File) {
SessionLogFiles.candidates(dir).forEach { file ->
if (!SessionLogFiles.safeFile(dir, file)) return@forEach
var tmp: File? = null
try {
tmp = File.createTempFile(".redacted-", ".tmp", dir)
val size = file.length()
val modified = file.lastModified()
val limit = if (file.parentFile?.name == "steam") SessionLogFiles.STEAM_MAX_BYTES else SessionLogFiles.MAX_BYTES
tmp.bufferedWriter().use { SessionLogFiles.scrubTo(dir, file, it, limit) }
if (file.length() == size && file.lastModified() == modified) {
check(tmp.renameTo(file))
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${file.name}", e)
} finally {
tmp?.delete()
}
/**
* The session's own files (session.log, app.log, desktop.log, the Steam desktop client's
* steam-desktop.log, ...) were written as they happened, unscrubbed; this pass puts every one
* through the redactor before the folder can be shared. A file is rewritten only if a line
* changed. steam/ was scrubbed on the way in.
*/
/** A file's size and modification time as they stood right after it was scrubbed. */
private class Scrubbed(val length: Long, val modified: Long)
/** Files of a folder as they stood right after scrubbing, filled by [scrubTree] and [copySteamLogs]. */
private class Record(val dir: File) {
val files = HashMap<File, Scrubbed>()
var failed = false
}
private fun scrubFolder(dir: File, record: Record) {
dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f ->
if (!LogRedactor.isText(f)) return@forEach
val done = scrubFile(dir, f)
if (done == null) record.failed = true else record.files[f] = done
}
}
private fun copySteamLogs(context: Context, dir: File) {
/**
* Puts [f] through the redactor in place. Returns its size and modification time as it then
* stands, or null if it could not, and [f] may still hold the original. A writer still
* appending to [f] (the app's own log capture) changes its size afterwards, and a share then
* scrubs it again.
*/
private fun scrubFile(dir: File, f: File): Scrubbed? {
val tmp = File(dir, ".${f.name}.scrub")
return try {
val before = Scrubbed(f.length(), f.lastModified())
tmp.bufferedWriter().use { w -> LogRedactor.scrubTo(f, w) }
val scrubbed = tmp.readBytes()
if (scrubbed.contentEquals(f.readBytes())) {
tmp.delete()
// Unchanged by the redactor, and by anything else while it read.
before.takeIf { f.length() == it.length && f.lastModified() == it.modified }
} else {
// Shared storage can refuse a rename; then the scrubbed bytes are written over the
// original instead, so it never stays behind unscrubbed.
if (!tmp.renameTo(f)) { f.writeBytes(scrubbed); tmp.delete() }
Scrubbed(scrubbed.size.toLong(), f.lastModified()).takeIf { f.length() == it.length }
}
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${f.name}", e)
tmp.delete()
null
}
}
/**
* Records [record]'s folder as scrubbed - every file went through without a failure - or
* leaves it unmarked, so the next share and the pass over older folders scrub it again.
*/
private fun markScrubbed(record: Record) {
val dir = record.dir
val tree = File(dir, SCRUBBED_TREE_MARKER)
if (record.failed) {
tree.delete()
Log.w(TAG, "$dir is not fully scrubbed; it is scrubbed again when shared")
return
}
try {
File(dir, SCRUBBED_MARKER).writeText("scrubbed ${now()}\n")
val lines = StringBuilder("rules ${LogRedactor.RULES_VERSION}\n")
record.files.forEach { (f, s) ->
lines.append(s.length).append('\t').append(s.modified).append('\t')
.append(f.relativeTo(dir).path).append('\n')
}
tree.writeText(lines.toString())
} catch (e: Exception) {
tree.delete()
}
}
/**
* The files of [dir] that its own ending scrubbed and that are unchanged since (same size and
* modification time), by path relative to [dir]. Empty when the folder has no such record, or
* one made under other redactor rules.
*/
fun scrubbedFiles(dir: File): Set<String> {
val lines = try { File(dir, SCRUBBED_TREE_MARKER).takeIf { it.isFile }?.readLines() } catch (e: Exception) { null }
?: return emptySet()
if (lines.firstOrNull() != "rules ${LogRedactor.RULES_VERSION}") return emptySet()
return lines.drop(1).mapNotNull { line ->
val parts = line.split('\t', limit = 3)
if (parts.size != 3) return@mapNotNull null
val f = File(dir, parts[2])
parts[2].takeIf { f.isFile && f.length().toString() == parts[0] && f.lastModified().toString() == parts[1] }
}.toSet()
}
/** The end-of-session scrub of [dir] on its own (steam/ already in place), for tests. */
@androidx.annotation.VisibleForTesting
internal fun scrubAndMark(dir: File) = markScrubbed(scrubTree(Record(dir)))
/**
* [record]'s folder and every folder under it (steam/, droiddeck-esync/): the session script
* copied files there verbatim, and a Steam log the app did not copy over again (gone from the
* runtime, or past its size limit) stayed as the script left it. Files [copySteamLogs] already
* redacted on the way in are in [record] and left alone.
*/
private fun scrubTree(record: Record): Record {
record.dir.walkTopDown().filter { it.isDirectory }.forEach { scrubFolder(it, record) }
return record
}
/** Steam's logs: redacted into steam/, never copied verbatim. What it wrote goes in [record]. */
private fun copySteamLogs(context: Context, dir: File, record: Record) {
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
if (!logs.isDirectory || java.nio.file.Files.isSymbolicLink(logs.toPath())) return
val out = File(dir, "steam")
if (java.nio.file.Files.isSymbolicLink(out.toPath()) || !(out.isDirectory || out.mkdirs())) return
SessionLogFiles.steamNames.map { File(logs, it) }.filter { it.exists() }.forEach { src ->
val tmp = File.createTempFile(".redacted-", ".tmp", out)
if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() }
logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
try {
tmp.bufferedWriter().use { SessionLogFiles.scrubTo(logs, src, it, SessionLogFiles.STEAM_MAX_BYTES) }
check(tmp.renameTo(File(out, src.name)))
val dst = File(out, src.name)
dst.bufferedWriter().use { w ->
src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
}
record.files[dst] = Scrubbed(dst.length(), dst.lastModified())
} catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e)
} finally {
tmp?.delete()
}
}
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
/**
@@ -109,10 +223,10 @@ object SessionArtifacts {
*/
@Synchronized
fun finishAbandoned(context: Context) {
SessionLogMigration.run(context)
val abandoned = SessionPaths.sessionFolders(context).filter {
it.parentFile == LinuxRuntime.debugLogDir(context) && !File(it, COMPLETE_MARKER).exists()
}
val parent = LinuxRuntime.debugLogDir()
val abandoned = parent.listFiles { f ->
SessionPaths.isSessionFolder(f) && !File(f, COMPLETE_MARKER).exists()
}?.sortedWith(SessionPaths.chronological) ?: return
if (abandoned.isEmpty()) return
val current = SessionPaths.current()
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
@@ -130,10 +244,11 @@ object SessionArtifacts {
"crash.log holds Android's crash buffer as of the next app start - if this\n" +
"session died of a crash, the entry is in there unless the device rebooted.\n"
)
if (newest) copySteamLogs(context, dir)
val record = Record(dir)
if (newest) copySteamLogs(context, dir, record)
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
SessionEvents.record("session.artifacts_recovered", mapOf("newest" to newest), dir)
scrubTree(dir)
markScrubbed(scrubTree(record))
File(dir, COMPLETE_MARKER).writeText("collected: late, at next app start, ${now()}\n")
Log.i(TAG, "finished the abandoned session folder $dir")
} catch (e: Exception) {
@@ -153,7 +268,7 @@ object SessionArtifacts {
val current = SessionPaths.current()
val finished = SessionPaths.sessionFolders(context).filter { it != current && File(it, COMPLETE_MARKER).exists() }
val old = finished.dropLast(SessionPaths.KEEP_SESSIONS)
old.forEach { SessionLogFiles.deleteTree(it) }
old.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
if (old.isNotEmpty()) Log.i(TAG, "deleted ${old.size} session folder(s) past the newest ${SessionPaths.KEEP_SESSIONS}")
}
@@ -166,11 +281,10 @@ object SessionArtifacts {
fun clearAll(context: Context): Int {
val current = SessionPaths.current()
val gone = SessionPaths.sessionFolders(context).filter { it != current }
gone.forEach { SessionLogFiles.deleteTree(it) }
LinuxRuntime.debugLogDir(context).listFiles { f -> f.name == SessionPaths.TOOLS_DIR || f.name.matches(Regex("tools-\\d+")) }
?.forEach { SessionLogFiles.deleteTree(it) }
gone.forEach { com.droiddeck.launcher.core.FileUtils.delete(it) }
com.droiddeck.launcher.core.FileUtils.delete(File(LinuxRuntime.debugLogDir(), SessionPaths.TOOLS_DIR))
// Before tools/, those logs sat loose beside the session folders.
LinuxRuntime.debugLogDir(context).listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
LinuxRuntime.debugLogDir().listFiles { f -> f.isFile && f.name.endsWith(".log") }?.forEach { it.delete() }
Log.i(TAG, "cleared ${gone.size} session folder(s)")
return gone.size
}
@@ -41,6 +41,7 @@ object SessionFiles {
"libblfastpath.so" to "usr/local/lib/libblfastpath.so",
"libssbs.so" to "usr/local/lib/libssbs.so",
"usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session",
"usr/local/bin/droiddeck-xwindows" to "usr/local/bin/droiddeck-xwindows",
"usr/local/bin/steam-compatibility" to "usr/local/bin/steam-compatibility",
"usr/local/bin/droiddeck-clipboard" to "usr/local/bin/droiddeck-clipboard",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
@@ -349,9 +350,26 @@ object SessionFiles {
indent + "}",
).joinToString(newline)
fun logDirectory(context: Context): File =
LinuxRuntime.debugLogDir(context).apply {
check(!java.nio.file.Files.isSymbolicLink(toPath()))
check(isDirectory || mkdirs())
/**
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
* folder rather than dug out of app-private storage - but the session script redirects its own
* output there with `exec`, and a redirection a non-interactive shell cannot open ends that
* shell. So a public directory is used only once it is proven writable; otherwise the app's
* own files directory, which is bound into the session anyway, stands in.
*/
fun logDirectory(context: Context): File {
val public = LinuxRuntime.debugLogDir()
if (public.isDirectory || public.mkdirs()) {
val probe = File(public, ".writable")
try {
if (probe.createNewFile() || probe.isFile) {
probe.delete()
return public
}
} catch (ignored: Exception) {
}
}
Log.w(TAG, "$public is not writable (storage permission?); logging to files/logs")
return File(context.filesDir, "logs").apply { mkdirs() }
}
}
@@ -1,107 +0,0 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.LogRedactor
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Writer
import java.nio.channels.Channels
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardOpenOption.READ
internal object SessionLogFiles {
const val MAX_BYTES = 64L * 1024 * 1024
const val STEAM_MAX_BYTES = 8L * 1024 * 1024
private const val MAX_LINE_CHARS = 64 * 1024
val steamNames = setOf(
"bootstrap_log.txt", "connection_log.txt", "console_log.txt", "content_log.txt",
"controller.txt", "compat_log.txt", "cef_log.txt", "cef_log.previous.txt",
"shader_log.txt", "systemaudiomanager.txt", "steamwebhelper.log", "webhelper.txt",
"steamui_html.txt", "steamui_system.txt", "steamui_library.txt", "steamui_login.txt",
"remote_connections.txt", "streaming_log.txt", "video.txt", "vrclient_steam.txt"
)
private val paths = setOf(
"session.log", "session.log.1", "app.log", "crash.log", "crash-app.txt",
"wayland.log", "audio.log", "device.txt", "network.txt", "events.jsonl",
"desktop.log", "steam-desktop.log", "steam.log", "pad.log", "storage.log",
"ended-without-teardown.txt", "droiddeck-esync/launches.log",
"droiddeck-esync/tools.tsv", "droiddeck-esync/wanted.tsv",
"droiddeck-esync/prefixes.json", "droiddeck-fex/status.json", "droiddeck-fex/Config.json"
) + steamNames.map { "steam/$it" }
fun candidates(folder: File): List<File> = paths.map { File(folder, it) }
.filter { Files.exists(it.toPath(), NOFOLLOW_LINKS) }
fun deleteTree(file: File) {
if (!Files.exists(file.toPath(), NOFOLLOW_LINKS)) return
Files.walk(file.toPath()).use { stream ->
stream.iterator().asSequence().toList().asReversed().forEach { Files.deleteIfExists(it) }
}
}
fun safeFile(root: File, file: File): Boolean {
val base = root.toPath().toAbsolutePath().normalize()
var path = file.toPath().toAbsolutePath().normalize()
if (!path.startsWith(base) || path == base) return false
while (path != base) {
if (Files.isSymbolicLink(path)) return false
path = path.parent ?: return false
}
return !Files.isSymbolicLink(base) && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS)
}
fun scrubTo(root: File, file: File, out: Writer, maxBytes: Long = MAX_BYTES) {
if (!safeFile(root, file)) throw IOException("unsafe path")
Files.newByteChannel(file.toPath(), READ, NOFOLLOW_LINKS).use { channel ->
var remaining = channel.size()
if (remaining >= maxBytes) throw IOException("size limit")
val source = Channels.newInputStream(channel)
val snapshot = object : InputStream() {
override fun read(): Int {
val one = ByteArray(1)
return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 255
}
override fun read(bytes: ByteArray, offset: Int, length: Int): Int {
if (length == 0) return 0
if (remaining == 0L) return -1
val count = source.read(bytes, offset, minOf(length.toLong(), remaining).toInt())
if (count < 0) throw IOException("truncated snapshot")
remaining -= count
return count
}
}
val decoder = Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
val reader = InputStreamReader(snapshot, decoder)
val line = StringBuilder()
val buffer = CharArray(4096)
fun writeLine() {
out.write(LogRedactor.redact(line.toString().removeSuffix("\r")))
out.write("\n")
line.setLength(0)
}
while (true) {
val count = reader.read(buffer)
if (count < 0) break
for (i in 0 until count) {
val char = buffer[i]
if (char == '\u0000') throw IOException("binary data")
if (char == '\n') writeLine() else {
if (line.length >= MAX_LINE_CHARS) throw IOException("line limit")
line.append(char)
}
}
}
if (line.isNotEmpty()) {
if (channel.size() != channel.position()) out.write("<incomplete live line withheld>\n")
else writeLine()
}
}
}
}
@@ -1,72 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS
internal object SessionLogMigration {
fun run(context: Context) {
val old = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), LinuxRuntime.DEBUG_LOG_DIR)
val target = LinuxRuntime.debugLogDir(context)
if (!old.isDirectory || Files.isSymbolicLink(old.toPath())) return
check(target.isDirectory || target.mkdirs())
old.listFiles().orEmpty().filter {
SessionPaths.isSessionFolder(it) || it.name == SessionPaths.TOOLS_DIR ||
(it.isFile && it.name.endsWith(".log"))
}.forEach { source ->
try {
move(source, target)
} catch (e: Exception) {
Log.w("SessionLogMigration", "could not move legacy logs into private storage", e)
}
}
}
internal fun move(source: File, target: File) {
check(!Files.isSymbolicLink(target.toPath()))
val paths = Files.walk(source.toPath()).use { it.iterator().asSequence().toList() }
check(paths.all { !Files.isSymbolicLink(it) &&
(Files.isRegularFile(it, NOFOLLOW_LINKS) || Files.isDirectory(it, NOFOLLOW_LINKS)) })
var destination = File(target, source.name)
var number = 1
val stem = Regex("^session-\\d{8}-\\d{6}").find(source.name)?.value ?: source.name
while (Files.exists(destination.toPath(), NOFOLLOW_LINKS)) {
val name = if (source.isFile) "${source.nameWithoutExtension}-${number++}.${source.extension}"
else "$stem-${number++}"
destination = File(target, name)
}
if (source.renameTo(destination)) return
val stage = File.createTempFile(".migrating-", ".tmp", target)
val versions = paths.associate { it.toFile().let { file -> file to (file.length() to file.lastModified()) } }
try {
if (source.isDirectory) { check(stage.delete()); check(stage.mkdir()) }
paths.forEach { path ->
val file = path.toFile()
val out = if (file == source) stage else File(stage, file.relativeTo(source).path)
if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
check(out.isDirectory || out.mkdirs())
} else {
check(file == source || SessionLogFiles.safeFile(source, file))
Files.newByteChannel(path, java.nio.file.StandardOpenOption.READ, NOFOLLOW_LINKS).use { input ->
out.outputStream().use { output -> java.nio.channels.Channels.newInputStream(input).copyTo(output) }
}
check(out.length() == versions.getValue(file).first)
}
}
check(versions.all { (file, version) -> file.length() == version.first && file.lastModified() == version.second })
paths.asReversed().forEach { path ->
val file = path.toFile()
val out = if (file == source) stage else File(stage, file.relativeTo(source).path)
check(out.setLastModified(versions.getValue(file).second))
}
check(stage.renameTo(destination))
paths.asReversed().forEach { Files.delete(it) }
} finally {
stage.deleteRecursively()
}
}
}
@@ -17,6 +17,11 @@ import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
/**
* Zips the most recent session's log folder and hands it to Android's share sheet. Works where
* the folder could not be written to Downloads (no storage permission, or a device that refuses
* it) and landed in the app's private files instead, which a user cannot otherwise reach.
*/
object SessionLogShare {
private val main = Handler(Looper.getMainLooper())
@@ -46,57 +51,71 @@ object SessionLogShare {
/** The newest session folder in either place logs are written, or null if there is none. */
fun latest(context: Context): File? = SessionPaths.sessionFolders(context).lastOrNull()
@Synchronized
/** Builds the zip (blocking). Returns null when there is no session to share. */
/** Builds a zip for one specific session folder (blocking). */
fun zipFolder(context: Context, folder: File, onProgress: ((Float) -> Unit)? = null): File? {
if (!folder.isDirectory || java.nio.file.Files.isSymbolicLink(folder.toPath())) return null
val files = SessionLogFiles.candidates(folder).map { Triple(folder, it, it.relativeTo(folder).invariantSeparatorsPath) }
val liveRoot = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
val live = if (folder == SessionPaths.current()) SessionLogFiles.steamNames
.filter { name -> files.none { it.third == "steam/$name" } }
.map { File(liveRoot, it) }.filter { java.nio.file.Files.exists(it.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS) }
.map { Triple(liveRoot, it, "steam/${it.name}") } else emptyList()
val sources = files + live
if (sources.isEmpty()) return null
val out = File(context.cacheDir, "shared-logs").apply { SessionLogFiles.deleteTree(this); check(mkdirs()) }
val name = folder.name.replace(Regex("[^A-Za-z0-9._-]"), "_")
val zip = File(out, "DroidDeck-$name.zip")
val partial = File(out, ".export")
val stage = File.createTempFile("redacted-", ".tmp", context.cacheDir)
val omitted = ArrayList<String>()
if (!folder.isDirectory) return null
// The client's logs past STEAM_LOG_MAX_BYTES stay out, as they do from the app's own copy: a
// CEF debug log or an old *.previous.txt reached 17 MB, every share scrubbed them line by
// line, and the share sheet took ten seconds to appear.
val files = folder.walkTopDown().filter { it.isFile }
.filterNot { it.parentFile?.name == "steam" && it.length() > STEAM_LOG_MAX_BYTES }.toList()
if (files.isEmpty()) return null
val out = File(context.cacheDir, "shared-logs").apply { deleteRecursively(); mkdirs() }
val zip = File(out, "DroidDeck-${folder.name}.zip")
// Scrubbed on the way into the zip: a session shared while it runs has not had its end-of-
// session pass yet, and the redactor changes nothing in a line that is already clean.
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
try {
ZipOutputStream(partial.outputStream().buffered()).use { z ->
sources.forEachIndexed { index, (root, src, relative) ->
val limit = if (relative.startsWith("steam/")) SessionLogFiles.STEAM_MAX_BYTES else SessionLogFiles.MAX_BYTES
val failure = runCatching {
stage.bufferedWriter().use { SessionLogFiles.scrubTo(root, src, it, limit) }
}.exceptionOrNull()
if (failure == null) {
z.putNextEntry(ZipEntry("$name/$relative"))
stage.inputStream().use { it.copyTo(z) }
z.closeEntry()
} else {
omitted += "$relative: omitted because it could not be safely sanitized."
}
onProgress?.invoke((index + 1).toFloat() / sources.size)
}
if (omitted.isNotEmpty()) {
z.putNextEntry(ZipEntry("$name/omitted.txt"))
z.write((omitted.joinToString("\n") + "\n").toByteArray(Charsets.UTF_8))
z.closeEntry()
}
}
check(partial.renameTo(zip))
return zip
} catch (e: Exception) {
partial.delete()
zip.delete()
throw e
} finally {
stage.delete()
// A finished folder was scrubbed whole when it ended. A file its record lists, unchanged
// since, goes in as it is; anything else (added or changed since, hidden, or any file of a
// session still running) is scrubbed again. Scrubbing tens of MB of the client's logs on
// every share kept the share sheet from appearing for ten seconds or more.
val scrubbed = SessionArtifacts.scrubbedFiles(folder)
val live = liveSteamLogs(context, folder)
val total = (files + live).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L
var shown = -1
fun advance(f: File) {
done += f.length()
val percent = (done * 100 / total).toInt()
if (percent != shown) { shown = percent; onProgress?.invoke(percent / 100f) }
}
ZipOutputStream(zip.outputStream().buffered()).use { z ->
files.forEach { f -> addEntry(z, folder.name + "/" + f.relativeTo(folder).path, f, f.relativeTo(folder).path in scrubbed); advance(f) }
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f, false); advance(f) }
}
return zip
}
private fun addEntry(z: ZipOutputStream, name: String, f: File, scrubbed: Boolean) {
z.putNextEntry(ZipEntry(name))
if (!scrubbed && LogRedactor.isText(f)) {
val w = z.bufferedWriter()
LogRedactor.scrubTo(f, w)
w.flush()
} else {
f.inputStream().use { it.copyTo(z) }
}
z.closeEntry()
}
/**
* The client's own logs as they stand, for a session shared while it runs. The session script
* copies them into steam/ only as it exits, so a zip made from the drawer had none - and
* controller.txt (which pad the client opened, the touch mode it set) is what a controller or
* touch report needs most. Only for the running session: an older folder would get this
* session's logs. The same files the script copies; nothing holding credentials is in logs/.
*/
private fun liveSteamLogs(context: Context, folder: File): List<File> {
if (folder != SessionPaths.current() || File(folder, "steam").exists()) return emptyList()
val logs = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/logs")
return logs.listFiles()?.filter { it.isFile && it.length() <= STEAM_LOG_MAX_BYTES }.orEmpty()
}
/** The client's content and bootstrap logs grow large over months and say nothing about a session. */
private const val STEAM_LOG_MAX_BYTES = 8L * 1024 * 1024
fun shareIntent(context: Context, zip: File): Intent {
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", zip)
val send = Intent(Intent.ACTION_SEND)
@@ -7,6 +7,29 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/**
* One folder per session under `Download/DroidDeck/`, holding everything that session recorded,
* named for the day, that day's session number and what was run, so the one a report is about can
* be picked out without opening any:
*
* ```
* Download/DroidDeck/2026-09-30-03-steam/
* device.txt what this device is, and every setting the session ran with
* session.log the guest session: proot, gamescope, the client's stdout
* wayland.log the app's compositor
* steam.log the Steam client's own log, scrubbed (Steam mode)
* steam/ the rest of the client's logs, scrubbed (Steam mode)
* desktop.log labwc, the panel and the programs on it (desktop mode)
* Download/DroidDeck/tools/ one-off commands: Flatpak installs, AppImage imports
* ```
*
* Folders from before this naming (`session-20260930-180642`) are still recognised, shared and
* pruned with the rest.
*
* The folder is claimed by whoever starts first - the activity starts the compositor before the
* service starts the session - so both write into the same one, and a recreated activity (a
* foldable opening mid-session) joins the folder in progress instead of opening another.
*/
object SessionPaths {
private const val TAG = "SessionPaths"
@@ -27,6 +50,12 @@ object SessionPaths {
@Volatile
private var ended: File? = null
/**
* The folder for the session now starting, or the one already in progress. With logs turned
* off on the main screen the folder lives in the app's cache instead of Downloads - the
* scripts and the compositor still need somewhere to write - and [release] deletes it.
* [label] says what is being run (see [label]); without one it comes from the session's state.
*/
@Synchronized
fun beginOrCurrent(context: Context, label: String? = null): File {
dir?.let { if (it.isDirectory) return it }
@@ -75,8 +104,8 @@ object SessionPaths {
// next session may have claimed its own by the time the last one's collector gets here.
if (dir == ended) dir = null
// A folder kept in the cache was never meant to outlive its session.
if (ended.parentFile == File(context.cacheDir, "session-logs")) {
SessionLogFiles.deleteTree(ended)
if (ended != null && ended.path.startsWith(context.cacheDir.path)) {
com.droiddeck.launcher.core.FileUtils.delete(ended)
}
}
@@ -94,28 +123,22 @@ object SessionPaths {
/** Whether [f] is a session's folder, in either naming. */
fun isSessionFolder(f: File): Boolean =
f.isDirectory && !java.nio.file.Files.isSymbolicLink(f.toPath()) &&
(NAMED.matches(f.name) || LEGACY.matches(f.name))
f.isDirectory && (NAMED.matches(f.name) || LEGACY.matches(f.name))
/**
* Oldest first: by day, then by when in the day. A folder from before the new naming sorts
* ahead of a new one from the same day, which it always predates.
*/
val chronological: Comparator<File> = compareBy<File> { f ->
val chronological: Comparator<File> = compareBy { f ->
NAMED.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}${g[2]}${g[3]}1${g[4].padStart(6, '0')}" }
?: LEGACY.matchEntire(f.name)?.groupValues?.let { g -> "${g[1]}0${g[2]}${g[3].removePrefix("-").padStart(2, '0')}" }
?: f.name
}.thenBy { it.lastModified() }
}
/** Every session folder in the places logs are written, oldest first. */
fun sessionFolders(context: Context): List<File> =
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(context),
File(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS),
com.droiddeck.launcher.runtime.LinuxRuntime.DEBUG_LOG_DIR))
.flatMap { parent ->
if (java.nio.file.Files.isSymbolicLink(parent.toPath())) emptyList()
else parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList()
}
listOf(com.droiddeck.launcher.runtime.LinuxRuntime.debugLogDir(), File(context.filesDir, "logs"))
.flatMap { parent -> parent.listFiles { f -> isSessionFolder(f) }?.toList() ?: emptyList() }
.sortedWith(chronological)
internal fun slug(text: String): String =
@@ -13,8 +13,6 @@ object SessionPrefs {
const val SUSPEND_NATIVE = "native"
const val SUSPEND_MANUAL = "manual"
const val SUSPEND_NEVER = "never"
private const val LEGACY_SUSPEND_DOWNLOADS = "downloads"
private const val STEAM_DOWNLOADS_IN_BACKGROUND = "steamDownloadsInBackground"
const val CONTROLLER_DECK = "deck"
const val CONTROLLER_XBOX360 = "xbox360"
@@ -420,6 +418,14 @@ object SessionPrefs {
fun mangoapp(context: Context): Boolean = prefs(context).getBoolean("mangoapp", true)
fun setMangoapp(context: Context, on: Boolean) { prefs(context).edit().putBoolean("mangoapp", on).apply() }
/**
* Steam on two Xwayland servers, as SteamOS runs it: the client on one, its games on the other
* (droiddeck-session, BL_XWAYLAND_COUNT). Off puts both back on one server, for a game whose
* window opens behind the client and never takes focus. On by default.
*/
fun dualXwayland(context: Context): Boolean = prefs(context).getBoolean("dualXwayland", true)
fun setDualXwayland(context: Context, on: Boolean) { prefs(context).edit().putBoolean("dualXwayland", on).apply() }
/**
* Zink's lazy descriptor mode (ZINK_DESCRIPTORS=lazy) with its compact set layout
* (ZINK_DEBUG=compact) for the client's GL-on-Vulkan UI, as WinNative runs it. On by default.
@@ -593,25 +599,8 @@ object SessionPrefs {
/** The .exe the user chose for one game folder (by its path), "" = the scanner's pick. */
fun addedGameExe(context: Context, folderPath: String): String = prefs(context).getString("addedExe:$folderPath", "") ?: ""
private val addedGameLock = Any()
fun setAddedGameExe(context: Context, folderPath: String, path: String) {
synchronized(addedGameLock) { prefs(context).edit().putString("addedExe:$folderPath", path).apply() }
}
fun addedGameExeSeen(context: Context, folderPath: String): Int = prefs(context).getInt("addedExeSeen:$folderPath", 0)
fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean =
synchronized(addedGameLock) {
val unchanged = addedGameExe(context, folderPath) == expected
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
unchanged
}
fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) {
val p = prefs(context)
p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
?: first.also { p.edit().putLong("addedAppId:$folderPath", it).apply() }
prefs(context).edit().putString("addedExe:$folderPath", path).apply()
}
/** The app's colour theme (ui/Themes ids); Graphite unless chosen otherwise. */
@@ -798,41 +787,16 @@ object SessionPrefs {
fun suspendPolicy(context: Context, mode: String): String =
prefs(context).getString("suspendPolicy.${prefMode(mode)}", SUSPEND_MANUAL)
?.let { if (it == LEGACY_SUSPEND_DOWNLOADS) SUSPEND_AUTO else it }
?.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_NATIVE, SUSPEND_MANUAL, SUSPEND_NEVER) }
// Direct games share Steam's settings but have no Steam client to prepare.
?.let { if (mode != SessionService.MODE_STEAM && it == SUSPEND_NATIVE) SUSPEND_AUTO else it }
?.let { if (it == SUSPEND_NATIVE && mode != SessionService.MODE_STEAM) SUSPEND_AUTO else it }
?: SUSPEND_MANUAL
fun setSuspendPolicy(context: Context, mode: String, policy: String) {
val normalized = policy.takeIf { it in setOf(SUSPEND_AUTO, SUSPEND_MANUAL, SUSPEND_NEVER) ||
(it == SUSPEND_NATIVE && mode == SessionService.MODE_STEAM) }
?: SUSPEND_MANUAL
val prefs = prefs(context)
val key = "suspendPolicy.${prefMode(mode)}"
prefs.edit().apply {
if (mode == SessionService.MODE_STEAM && prefs.getString(key, null) == LEGACY_SUSPEND_DOWNLOADS) {
putBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, true)
}
putString(key, normalized)
}.apply()
}
fun steamDownloadsInBackground(context: Context): Boolean {
val prefs = prefs(context)
return prefs.getBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, false) ||
prefs.getString("suspendPolicy.${SessionService.MODE_STEAM}", null) == LEGACY_SUSPEND_DOWNLOADS
}
fun setSteamDownloadsInBackground(context: Context, enabled: Boolean) {
val prefs = prefs(context)
val policyKey = "suspendPolicy.${SessionService.MODE_STEAM}"
prefs.edit().apply {
putBoolean(STEAM_DOWNLOADS_IN_BACKGROUND, enabled)
if (prefs.getString(policyKey, null) == LEGACY_SUSPEND_DOWNLOADS) {
putString(policyKey, SUSPEND_AUTO)
}
}.apply()
prefs(context).edit().putString("suspendPolicy.${prefMode(mode)}", normalized).apply()
}
// ── Game storage ────────────────────────────────────────────────────────────────────────
@@ -13,7 +13,6 @@ import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.TrafficStats
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Environment
@@ -76,12 +75,7 @@ class SessionService : Service() {
private val auxiliaryProcessesLock = Any()
private val mainHandler = Handler(Looper.getMainLooper())
private var suspendController: SessionSuspendController? = null
private val steamDownloadMonitor = SteamDownloadMonitor()
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
private var steamDownloadsInBackground = false
private var activityVisible = true
private var screenOn = true
private var manualPauseRequested = false
@@ -173,7 +167,6 @@ class SessionService : Service() {
ACTION_ACTIVITY_VISIBLE -> {
if (!SessionState.pipActive) pipTask = false
activityVisible = true
suspendDownloadNow = false
resumeSteamSleepOnReturn()
suspendAttemptFailed = false
updateSuspendPolicy()
@@ -188,18 +181,10 @@ class SessionService : Service() {
ACTION_SUSPEND_POLICY_CHANGED -> {
if (!SessionState.running) return START_NOT_STICKY
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
updateDownloadMonitoring()
suspendAttemptFailed = false
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_SUSPEND_NOW -> {
if (!SessionState.running) return START_NOT_STICKY
suspendDownloadNow = true
updateSuspendPolicy()
return START_NOT_STICKY
}
ACTION_RESUME -> {
resumeSession()
return START_NOT_STICKY
@@ -214,13 +199,9 @@ class SessionService : Service() {
}
SessionState.mode = intent?.getStringExtra(EXTRA_MODE) ?: MODE_STEAM
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
activityVisible = true
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true
manualPauseRequested = false
suspendDownloadNow = false
steamDownloadMonitor.reset()
downloadActive = false
steamSleepToken = null
completeNativeSleep()
suspendOperationPending = false
@@ -277,6 +258,9 @@ class SessionService : Service() {
try {
SessionArtifacts.collect(this, dir, "session stopped")
} finally {
// Last, so everything above is in the file it is about - and only this session's:
// a session that replaced this one may already own the capture and the folder.
SessionLogCapture.stopFor(dir)
SessionPaths.release(this, dir)
}
}
@@ -423,7 +407,7 @@ class SessionService : Service() {
// whatever a session leaves behind. The client abandons tens of megabytes of streams a run.
FileUtils.clear(File(cacheDir, "shm"))
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest, sessionRoot, runtimeDir)
val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest)
// The fast path is told exactly the rootfs and binds proot is given (ProotFastPath).
val fastPathKey = if (ProotFastPath.enabled(this)) {
val prootBinds = LinuxRuntime.binds(
@@ -541,7 +525,6 @@ class SessionService : Service() {
},
)
mainHandler.post { updateSuspendPolicy() }
updateDownloadMonitoring()
}
}
@@ -631,6 +614,7 @@ class SessionService : Service() {
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0"))
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
if (SessionState.mode == MODE_STEAM) guest.add("BL_XWAYLAND_COUNT=" + (if (SessionPrefs.dualXwayland(this)) "2" else "1"))
if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this))
if (SessionState.mode == MODE_STEAM) {
guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0"))
@@ -774,8 +758,6 @@ class SessionService : Service() {
fakeInputDir: File,
sessionDir: File,
guest: MutableList<String>,
sessionRoot: File,
runtimeDir: File,
): ArrayList<String> {
val binds = ArrayList<String>()
if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input")
@@ -896,45 +878,6 @@ class SessionService : Service() {
} else if (roms != null) {
Log.w(TAG, "roms: $roms is not a readable folder; /root/ROMs not offered this session")
}
val libraries = ArrayList<Pair<String, String>>()
if (storageDiagnosticLibrary != null && library != null) libraries.add(SecondaryLibrary.CARD_GUESTS[0] to library.label)
val gamesLibraries = GameStorage.gamesFolderLibraries(this)
if (gamesLibraries.isNotEmpty()) {
var room = if (ProotFastPath.enabled(this)) {
ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds).size
} else Int.MAX_VALUE
for (games in gamesLibraries) {
if (games.host.path + ":" + games.guest !in binds) continue
val problem = GameStorage.prepare(this, games.host.path)
if (problem != null) {
Log.w(TAG, "steam library: $problem")
continue
}
try {
val extra = SecondaryLibrary.binds(filesDir, games.host, listOf(games.guest)).drop(1)
if (extra.size > room) {
Log.w(TAG, "steam library: ${games.host} needs ${extra.size} binds, $room left for the fast path; not a library this session")
continue
}
binds.addAll(extra)
room -= extra.size
libraries.add(games.guest to games.label)
Log.i(TAG, "steam library: ${games.host} -> ${games.guest} (\"${games.label}\")")
} catch (e: Exception) {
Log.w(TAG, "steam library: ${games.host} private directories could not be prepared", e)
}
}
}
try {
val listing = File(filesDir, "session/steam-libraries.json").apply { parentFile?.mkdirs() }
val json = org.json.JSONArray()
for ((path, label) in libraries) json.put(org.json.JSONObject().put("path", path).put("label", label.replace('"', ' ').replace('\\', ' ')))
listing.writeText(json.toString())
val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size
guest.add(envAt, "BL_STEAM_LIBRARIES=" + listing.path)
} catch (e: Exception) {
Log.w(TAG, "steam library: the list could not be written; the card alone this session", e)
}
return binds
}
@@ -1075,7 +1018,6 @@ class SessionService : Service() {
activityVisible = true
screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn
manualPauseRequested = false
suspendDownloadNow = false
if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback)) requestSteamWake()
completeNativeSleep()
completeSteamSleep()
@@ -1247,19 +1189,16 @@ class SessionService : Service() {
}
val controller = suspendController ?: return
val hidden = !activityVisible || !screenOn
val downloadsBlockingSuspend = steamDownloadsInBackground && SessionState.mode == MODE_STEAM &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER && hidden && downloadActive && !suspendDownloadNow
if (downloadsBlockingSuspend) acquireLocks()
if (suspendPolicy != SessionPrefs.SUSPEND_NATIVE || !hidden || downloadsBlockingSuspend) {
if (suspendPolicy != SessionPrefs.SUSPEND_NATIVE || !hidden) {
completeNativeSleep()
} else if (nativeSleepToken == null && steamSleepToken == null &&
!SessionState.suspended && !suspendAttemptFailed) {
prepareNativeSleep()
}
val shouldSuspend = steamSleepToken != null || when (suspendPolicy) {
SessionPrefs.SUSPEND_AUTO -> hidden && !downloadsBlockingSuspend
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady && !downloadsBlockingSuspend
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested && !downloadsBlockingSuspend
SessionPrefs.SUSPEND_AUTO -> !activityVisible || !screenOn
SessionPrefs.SUSPEND_NATIVE -> hidden && nativeSleepReady
SessionPrefs.SUSPEND_MANUAL -> manualPauseRequested
else -> false
}
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
@@ -1443,7 +1382,6 @@ class SessionService : Service() {
if (!SessionState.running) return
SessionState.running = false
}
updateDownloadMonitoring()
val stoppedGen = sessionGen
SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
@@ -1612,26 +1550,11 @@ class SessionService : Service() {
return Notification.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_session)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(
when {
SessionState.suspended -> R.string.session_notification_paused
downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER -> R.string.session_notification_downloads
else -> R.string.session_notification
}
))
.setContentText(getString(if (SessionState.suspended) R.string.session_notification_paused else R.string.session_notification))
.setContentIntent(open)
.apply {
if (SessionState.suspended) {
addAction(Notification.Action.Builder(null, getString(R.string.resume_session), resume).build())
} else if (downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER) {
val suspend = PendingIntent.getService(
this@SessionService, 3,
Intent(this@SessionService, SessionService::class.java).setAction(ACTION_SUSPEND_NOW),
PendingIntent.FLAG_IMMUTABLE,
)
addAction(Notification.Action.Builder(null, getString(R.string.suspend_now), suspend).build())
}
}
.addAction(Notification.Action.Builder(null, getString(R.string.stop_session), stop).build())
@@ -1645,40 +1568,6 @@ class SessionService : Service() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
}
private fun updateDownloadMonitoring() {
val enabled = SessionState.running && SessionState.mode == MODE_STEAM &&
steamDownloadsInBackground && suspendPolicy != SessionPrefs.SUSPEND_NEVER
if (!enabled) {
val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null
steamDownloadMonitor.reset()
downloadActive = false
if (wasActive) refreshNotification()
return
}
if (downloadMonitorTask != null) return
val poll = object : Runnable {
override fun run() {
if (downloadMonitorTask !== this || !SessionState.running ||
SessionState.mode != MODE_STEAM || !steamDownloadsInBackground ||
suspendPolicy == SessionPrefs.SUSPEND_NEVER) {
return
}
val wasActive = downloadActive
downloadActive = steamDownloadMonitor.poll(
LinuxRuntime.rootDir(this@SessionService),
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
)
if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
}
}
downloadMonitorTask = poll
mainHandler.post(poll)
}
/** The pads attached as the session starts; the activity logs the ones that come and go after. */
private fun logControllersAtStart() {
val pads = ArrayList<String>()
@@ -1703,7 +1592,6 @@ class SessionService : Service() {
private const val NOTIFICATION_ID = 1001
const val ACTION_STOP = "com.droiddeck.launcher.STOP_SESSION"
const val ACTION_RESUME = "com.droiddeck.launcher.RESUME_SESSION"
const val ACTION_SUSPEND_NOW = "com.droiddeck.launcher.SUSPEND_NOW"
private const val ACTION_PIP_BEGIN = "com.droiddeck.launcher.PIP_BEGIN"
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
@@ -1723,7 +1611,6 @@ class SessionService : Service() {
private const val STEAM_PICKUP_MS = 1500L
private const val STEAM_EXIT_MS = 10_000L
private const val GAME_LAUNCH_RETRY_MS = 250L
private const val DOWNLOAD_POLL_MS = 2_000L
private const val STEAM_GAME_REQUEST = "steam-game"
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
@@ -1,138 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
internal class SteamDownloadMonitor {
private data class ManifestState(
val bytesDownloaded: Long,
val incomplete: Boolean,
)
private var previous = emptyMap<String, ManifestState>()
private var lastProgressAt = 0L
private var contentLogOffset = 0L
private val activeContentUpdates = mutableSetOf<String>()
private var lastContentActivityAt = 0L
private var lastReceivedBytes = -1L
private var lastReceivedAt = 0L
/**
* [receivedBytes] is the app uid's received-byte counter (the guest runs as that uid), or a
* negative value when Android does not report one. Steam writes its rate line about once a
* minute and flushes manifest counters even less often, so live traffic is what bridges them.
*/
fun poll(runtimeRoot: File, now: Long = System.currentTimeMillis(), receivedBytes: Long = -1L): Boolean {
val current = manifests(runtimeRoot).associate { it.path to read(it) }
val progressed = current.any { (path, state) ->
state.incomplete && state.bytesDownloaded > (previous[path]?.bytesDownloaded ?: state.bytesDownloaded)
}
if (progressed) lastProgressAt = now
previous = current
val manifestActive = progressed || lastProgressAt > 0L && now - lastProgressAt <= MANIFEST_PROGRESS_GRACE_MS &&
current.values.any { it.incomplete }
if (receiving(receivedBytes, now)) lastContentActivityAt = now
return manifestActive || readContentActivity(runtimeRoot, now)
}
private fun receiving(receivedBytes: Long, now: Long): Boolean {
val previousBytes = lastReceivedBytes
val previousAt = lastReceivedAt
lastReceivedBytes = receivedBytes
lastReceivedAt = now
if (receivedBytes < 0L || previousBytes < 0L || receivedBytes < previousBytes || now <= previousAt) return false
return (receivedBytes - previousBytes) * 1000L / (now - previousAt) >= MIN_RECEIVE_BYTES_PER_SEC
}
fun reset() {
previous = emptyMap()
lastProgressAt = 0L
contentLogOffset = 0L
activeContentUpdates.clear()
lastContentActivityAt = 0L
lastReceivedBytes = -1L
lastReceivedAt = 0L
}
private fun readContentActivity(runtimeRoot: File, now: Long): Boolean {
val log = File(runtimeRoot, "root/.local/share/Steam/logs/content_log.txt")
if (!log.isFile) return false
if (log.length() < contentLogOffset) {
contentLogOffset = 0L
activeContentUpdates.clear()
lastContentActivityAt = 0L
}
runCatching {
RandomAccessFile(log, "r").use { input ->
input.seek(contentLogOffset)
while (true) {
val line = input.readLine() ?: break
when {
"Client version:" in line -> {
activeContentUpdates.clear()
lastContentActivityAt = 0L
}
CONTENT_UPDATE.find(line)?.let { match ->
val appId = match.groupValues[1]
val updateType = match.groupValues[2]
val state = match.groupValues[3]
val updateId = "$updateType:$appId"
if ("Running Update" in state && "Stopping" !in state) {
activeContentUpdates += updateId
lastContentActivityAt = now
} else {
activeContentUpdates -= updateId
}
true
} == true -> Unit
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
lastContentActivityAt = now
"Downloading " in line && " chunks for depot " in line ->
lastContentActivityAt = now
}
if (activeContentUpdates.isNotEmpty()) lastContentActivityAt = now
}
contentLogOffset = input.filePointer
}
}
return activeContentUpdates.isNotEmpty() && lastContentActivityAt > 0L &&
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
}
private fun manifests(runtimeRoot: File): List<File> {
val steamRoots = linkedSetOf(File(runtimeRoot, "root/.local/share/Steam"))
val primary = steamRoots.first()
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
runCatching {
PATH.findAll(libraryFolders.readText()).forEach { match ->
steamRoots += File(runtimeRoot, match.groupValues[1].removePrefix("/"))
}
}
return steamRoots.flatMap { root ->
File(root, "steamapps").listFiles { file ->
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
}.orEmpty().toList()
}
}
private fun read(file: File): ManifestState {
val text = runCatching { file.readText() }.getOrDefault("")
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
val downloaded = value(text, "BytesDownloaded")?.toLongOrNull() ?: 0L
val total = value(text, "BytesToDownload")?.toLongOrNull() ?: 0L
return ManifestState(downloaded, flags != 4L && (total <= 0L || downloaded < total))
}
private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
private companion object {
const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
// Longer than Steam's ~60 s between rate lines, for when no traffic counter is available.
const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
}
}
@@ -67,7 +67,6 @@ class ModeSettings(
val upscaleSharpness: Int = 75,
val touchMode: String,
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val pipSupported: Boolean = false,
val pipAutoEnter: Boolean = false,
/** Steam only. */
@@ -95,6 +94,8 @@ class ModeSettings(
val steamRepairQueued: Boolean = false,
/** Steam, Deck mode: the QAM's performance overlay (mangoapp) is started. */
val mangoapp: Boolean = true,
/** Steam only: the client and its games on separate Xwayland servers. */
val dualXwayland: Boolean = true,
/** Steam only: what the pad is to the client (SessionPrefs.CONTROLLER_*); null outside Steam. */
val steamController: String? = null,
/** Steam only: start a Steam session when DroidDeck opens. */
@@ -135,7 +136,6 @@ class ModeSettingsActions(
val onUpscaleSharpness: (Int) -> Unit = {},
val onTouch: (String) -> Unit,
val onSuspendPolicy: (String) -> Unit,
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val onOsc: (String) -> Unit,
val onBackActionsInverted: (Boolean) -> Unit = {},
@@ -154,6 +154,7 @@ class ModeSettingsActions(
val onSteamRepair: () -> Unit = {},
val onSteamDeckMode: (Boolean) -> Unit = {},
val onMangoapp: (Boolean) -> Unit = {},
val onDualXwayland: (Boolean) -> Unit = {},
val onSteamController: (String) -> Unit = {},
val onRunSteamAtStartup: (Boolean) -> Unit = {},
val onWifiDiscovery: (Boolean) -> Unit = {},
@@ -304,18 +305,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
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),
) + if (steam) listOf(
SessionPrefs.SUSPEND_NATIVE to stringResource(R.string.mode_suspend_native),
) else emptyList(),
) + if (steam) listOf(SessionPrefs.SUSPEND_NATIVE to stringResource(R.string.mode_suspend_native)) else emptyList(),
s.suspendPolicy,
note = stringResource(if (steam) R.string.mode_suspend_steam_note else R.string.mode_suspend_note),
onPick = a.onSuspendPolicy,
)
if (steam && s.suspendPolicy != SessionPrefs.SUSPEND_NEVER) ToggleRow(
host, "background-downloads", stringResource(R.string.mode_background_downloads),
stringResource(R.string.mode_background_downloads_hint),
s.steamDownloadsInBackground, onChange = a.onSteamDownloadsInBackground,
)
}
if (s.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) {
ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null,
@@ -399,6 +393,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
stringResource(R.string.mode_mangoapp_hint),
s.mangoapp, onChange = a.onMangoapp,
)
ToggleRow(
host, "dualxwayland", stringResource(R.string.mode_dual_xwayland),
stringResource(R.string.mode_dual_xwayland_hint),
s.dualXwayland, onChange = a.onDualXwayland,
)
// Deck mode fixes the branch (SessionPrefs.steamChannel); the choice is for Deck mode off.
if (s.steamDeckMode) SettingsRow(stringResource(R.string.mode_branch), stringResource(R.string.mode_branch_deck)) {}
else ChoiceRow(
@@ -191,7 +191,6 @@ class DrawerActions(
val oscMode: String,
val onScreenButtonsVisible: Boolean,
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val backActionsInverted: Boolean,
val touchMode: String,
val touchAuto: String,
@@ -222,7 +221,6 @@ class DrawerActions(
val onQamButton: (Boolean) -> Unit = {},
val onKeyboardButton: (Boolean) -> Unit = {},
val onSuspendPolicy: (String) -> Unit,
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
val onBackActionsInverted: (Boolean) -> Unit,
val onTouch: (String) -> Unit,
val onFexPreset: (String) -> Unit,
@@ -501,20 +499,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
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),
) + if (a.steam) listOf(
SessionPrefs.SUSPEND_NATIVE to stringResource(R.string.mode_suspend_native),
) else emptyList(),
) + if (a.steam) listOf(SessionPrefs.SUSPEND_NATIVE to stringResource(R.string.mode_suspend_native)) else emptyList(),
a.suspendPolicy,
note = stringResource(if (a.steam) R.string.mode_suspend_steam_note else R.string.mode_suspend_note),
chipModifier = focus.track(page, "suspend"),
onPick = a.onSuspendPolicy,
)
if (a.steam && a.suspendPolicy != SessionPrefs.SUSPEND_NEVER) ToggleRow(
host, "background-downloads", stringResource(R.string.mode_background_downloads),
stringResource(R.string.mode_background_downloads_hint),
a.steamDownloadsInBackground,
onChange = a.onSteamDownloadsInBackground,
)
}
SettingsGroup(stringResource(R.string.drawer_support)) {
SettingsRow(stringResource(R.string.drawer_logs), stringResource(R.string.drawer_logs_hint)) {
@@ -115,9 +115,8 @@ internal fun UpdatesPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie
}
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
// Landscape has the width for channels and status side by side; a narrow pane, or a small
// phone's (where each channel's name and date would be cut to a word), stacks them. The
// Thor's top screen leaves about 690dp here and keeps them side by side.
val stacked = LocalNarrowPane.current || maxWidth < 600.dp
// phone's (where each channel's name and date would be cut to a word), stacks them.
val stacked = LocalNarrowPane.current || maxWidth < 720.dp
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
if (stacked) {
StatusPanel(s, u, ua, me)
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s: falló el motor</string>
<string name="hud_fg_needs_lossless">%1$s: requiere Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · iniciando</string>
<string name="added_games_import_hint">Una carpeta con una subcarpeta por cada juego de Windows. Los juegos que tienes en Steam usan sus entradas de Steam tras reiniciar Steam; el resto se convierten en accesos directos ajenos a Steam. Con Segunda biblioteca en Automático, Steam también puede instalar juegos en esta carpeta.</string>
<string name="added_games_import_hint">Una carpeta con una subcarpeta por cada juego de Windows. Los juegos que tienes en Steam usan sus entradas de Steam tras reiniciar Steam; el resto se convierten en accesos directos ajenos a Steam.</string>
<string name="second_library_import_hint">Añade una biblioteca de Steam y busca juegos de Windows en ella. Los juegos que tienes usan sus entradas de Steam; el resto se convierten en accesos directos ajenos a Steam.</string>
<string name="added_games_forget_hint">Olvidar quita los accesos directos en la próxima sesión. Los archivos se conservan.</string>
<string name="game_env_title">Entorno del juego</string>
@@ -289,6 +289,8 @@
<string name="mode_deck_mode_hint">La interfaz Deck de Steam y los controles de rendimiento de Quick Access. Se aplica en la próxima sesión.</string>
<string name="mode_mangoapp">Overlay de rendimiento</string>
<string name="mode_mangoapp_hint">Desactívalo si los juegos fallan o se quedan en negro en modo Deck. Se aplica en la próxima sesión.</string>
<string name="mode_dual_xwayland">Dos servidores Xwayland</string>
<string name="mode_dual_xwayland_hint">Ejecuta los juegos en su propio servidor X, como SteamOS. Desactívalo si un juego se abre detrás de Steam y nunca toma el foco. Se aplica en la próxima sesión.</string>
<string name="mode_branch">Rama del cliente</string>
<string name="mode_branch_deck">Beta pública de Steam Deck (requerida por el modo Deck).</string>
<string name="mode_branch_hint">Se aplica en la próxima sesión. Steam puede actualizarse una vez.</string>
@@ -353,8 +355,8 @@
<string name="mode_wifi_explain_title">¿Activar la detección de Wi-Fi?</string>
<string name="mode_wifi_explain_text">Android exige el permiso de ubicación para leer los nombres de Wi-Fi y detectar redes cercanas. DroidDeck usa este acceso para mostrar esas redes en Steam. No rastreamos tu ubicación. El acceso a internet funciona sin este permiso.</string>
<string name="mode_storage">Almacenamiento de juegos</string>
<string name="mode_storage_auto">Automático - la tarjeta SD si está presente, y tus carpetas de juegos</string>
<string name="mode_storage_auto_none">Automático - tus carpetas de juegos, y la tarjeta SD si está presente (ninguna ahora)</string>
<string name="mode_storage_auto">Automático - la tarjeta SD si está presente</string>
<string name="mode_storage_auto_none">Automático - la tarjeta SD si está presente (ninguna ahora)</string>
<string name="mode_storage_internal">Solo interno</string>
<string name="mode_storage_folder">Carpeta: %1$s</string>
<string name="mode_second_library">Segunda biblioteca</string>
@@ -640,7 +642,7 @@
<string name="setup_choose">Elegir</string>
<string name="setup_linux_apps">Apps de Linux (beta)</string>
<string name="setup_store">Tienda Flathub</string>
<string name="setup_store_on">En el menú. Algunas apps pueden no iniciarse.</string>
<string name="setup_store_on">En el menú. Algunas apps pueden no iniciarse; los registros están en Download/DroidDeck.</string>
<string name="setup_store_off">Instala apps y juegos de Linux desde Flathub</string>
<string name="setup_tool_files">Archivos</string>
<string name="setup_tool_files_hint">Explorar y gestionar archivos</string>
@@ -1401,7 +1403,6 @@
<!-- File manager -->
<string name="fm_drive_internal">Interno</string>
<string name="fm_drive_linux">Sistema Linux</string>
<string name="fm_drive_sd">Tarjeta SD</string>
<string name="fm_drive_storage">Almacenamiento</string>
<string name="fm_select">Seleccionar</string>
@@ -1568,7 +1569,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">Se quitó \"%1$s\" de Favoritos</string>
<string name="fm_empty_directory">Carpeta vacía</string>
<string name="fm_up_one_level">Subir un nivel</string>
<string name="fm_choose_folder">Elige una carpeta</string>
<string name="fm_choose_file">Elige un archivo</string>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s : échec du moteur</string>
<string name="hud_fg_needs_lossless">%1$s : nécessite Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · Démarrage en cours</string>
<string name="added_games_import_hint">Un dossier contenant plusieurs sous-dossiers, chaque sous-dossier correspondant à un jeu Windows. Les jeux que vous possédez sur Steam utiliseront les entrées Steam correspondantes après le redémarrage de Steam ; les autres jeux deviendront des raccourcis non-Steam. Si Bibliothèque secondaire est sur Auto, Steam peut aussi installer des jeux dans ce dossier.</string>
<string name="added_games_import_hint">Un dossier contenant plusieurs sous-dossiers, chaque sous-dossier correspondant à un jeu Windows. Les jeux que vous possédez sur Steam utiliseront les entrées Steam correspondantes après le redémarrage de Steam ; les autres jeux deviendront des raccourcis non-Steam.</string>
<string name="second_library_import_hint">Ajoutez une bibliothèque Steam et analysez-y les jeux Windows. Les jeux déjà possédés utiliseront les entrées Steam correspondantes, les autres deviendront des raccourcis non-Steam.</string>
<string name="added_games_forget_hint">« Oublier » supprimera ces raccourcis lors de la prochaine session. Mais les fichiers resteront sur le disque.</string>
<string name="game_env_title">Environnement de jeu</string>
@@ -263,6 +263,8 @@
<string name="mode_deck_mode_hint">Interface Steam Deck et contrôles de performance à accès rapide. Prendra effet à la prochaine session.</string>
<string name="mode_mangoapp">Superposition de performance</string>
<string name="mode_mangoapp_hint">Désactivez cette option si les jeux plantent ou affichent un écran noir en mode Deck. Prendra effet à la prochaine session.</string>
<string name="mode_dual_xwayland">Deux serveurs Xwayland</string>
<string name="mode_dual_xwayland_hint">Lance les jeux sur leur propre serveur X, comme SteamOS. Désactivez cette option si un jeu s’ouvre derrière Steam et ne prend jamais le focus. Prendra effet à la prochaine session.</string>
<string name="mode_branch">Branche du client</string>
<string name="mode_branch_deck">Bêta Steam Deck (requis pour le mode Deck).</string>
<string name="mode_branch_hint">Prendra effet à la prochaine session. Steam peut se mettre à jour une fois de lui-même.</string>
@@ -300,8 +302,8 @@
<string name="mode_wifi_explain_title">Activer la découverte Wi-Fi ?</string>
<string name="mode_wifi_explain_text">Android a besoin de l\'autorisation de localisation pour lire les noms Wi-Fi et découvrir les réseaux à proximité. DroidDeck utilise cette autorisation pour afficher ces réseaux dans Steam. Nous ne suivons pas votre position. L\'accès à Internet reste possible sans cette autorisation.</string>
<string name="mode_storage">Stockage des jeux</string>
<string name="mode_storage_auto">Auto - Utiliser la carte SD si disponible, ainsi que vos dossiers de jeux</string>
<string name="mode_storage_auto_none">Auto - Utiliser vos dossiers de jeux, ainsi que la carte SD si disponible (aucune carte SD actuellement)</string>
<string name="mode_storage_auto">Auto - Utiliser la carte SD si disponible</string>
<string name="mode_storage_auto_none">Auto - Utiliser la carte SD si disponible (aucune carte SD actuellement)</string>
<string name="mode_storage_internal">Stockage interne uniquement</string>
<string name="mode_storage_folder">Dossier : %1$s</string>
<string name="mode_second_library">Bibliothèque secondaire</string>
@@ -534,7 +536,7 @@
<string name="setup_choose">Choisir</string>
<string name="setup_linux_apps">Applications Linux (bêta)</string>
<string name="setup_store">Boutique Flathub</string>
<string name="setup_store_on">Affiché dans le menu. Certaines applications peuvent ne pas se lancer.</string>
<string name="setup_store_on">Affiché dans le menu. Certaines applications peuvent ne pas se lancer ; les journaux se trouvent dans Download/DroidDeck.</string>
<string name="setup_store_off">Installer des applications et des jeux Linux depuis Flathub</string>
<string name="setup_tool_files">Fichiers</string>
<string name="setup_tool_files_hint">Parcourir et gérer les fichiers</string>
@@ -946,6 +948,4 @@
<string name="game_file_folder">Choisir un dossier pour les fichiers du jeu frontal</string>
<string name="game_file_exported">Fichiers du jeu enregistrés dans %1$s</string>
<string name="game_frontend_files">Fichiers frontaux</string>
<string name="fm_up_one_level">Remonter d\'un niveau</string>
<string name="fm_drive_linux">Système Linux</string>
</resources>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s:エンジンエラー</string>
<string name="hud_fg_needs_lossless">%1$s:Lossless Scalingが必要です</string>
<string name="hud_fg_starting">%1$s %2$s · 起動中</string>
<string name="added_games_import_hint">複数のサブフォルダを含むフォルダ。各サブフォルダはWindowsゲームに対応します。Steamで所有しているゲームはSteamの再起動後にSteamの項目を使用し、それ以外のゲームは非Steamショートカットになります。第2ライブラリが自動の場合、Steamはこのフォルダにもゲームをインストールできます。</string>
<string name="added_games_import_hint">複数のサブフォルダを含むフォルダ。各サブフォルダはWindowsゲームに対応します。Steamで所有しているゲームはSteamの再起動後にSteamの項目を使用し、それ以外のゲームは非Steamショートカットになります。</string>
<string name="second_library_import_hint">Steamライブラリを追加し、その中のWindowsゲームをスキャンします。所有しているゲームはSteamの項目を使用し、それ以外のゲームは非Steamショートカットになります。</string>
<string name="added_games_forget_hint">「忘れる」を選択すると、次回のセッションでこれらのショートカットが削除されます。ただし、ファイルはディスク上に残ります。</string>
<string name="game_env_title">ゲーム環境</string>
@@ -289,6 +289,8 @@
<string name="mode_deck_mode_hint">Steam DeckのUIとクイックアクセスパフォーマンスコントロール。次回のセッションで有効になります。</string>
<string name="mode_mangoapp">パフォーマンスオーバーレイ</string>
<string name="mode_mangoapp_hint">Deckモードでゲームがクラッシュしたり画面が真っ暗になる場合は、これをオフにしてください。次回のセッションで有効になります。</string>
<string name="mode_dual_xwayland">2つのXwaylandサーバー</string>
<string name="mode_dual_xwayland_hint">SteamOSと同様に、ゲームを専用のXサーバーで実行します。ゲームがSteamの背後で開き、フォーカスされない場合はオフにしてください。次回のセッションで有効になります。</string>
<string name="mode_branch">クライアントブランチ</string>
<string name="mode_branch_deck">Steam Deckベータ版(Deckモードに必要)。</string>
<string name="mode_branch_hint">次回のセッションで有効になります。Steamが自動的に一度アップデートされる場合があります。</string>
@@ -353,8 +355,8 @@
<string name="mode_wifi_explain_title">Wi-Fi検出を有効にしますか?</string>
<string name="mode_wifi_explain_text">AndroidがWi-Fi名を読み取り、付近のネットワークを検出するには位置情報の権限が必要です。DroidDeckはこの権限を使用してSteamにこれらのネットワークを表示します。位置情報を追跡することはありません。この権限がなくてもインターネットにアクセスできます。</string>
<string name="mode_storage">ゲームストレージ</string>
<string name="mode_storage_auto">自動 - SDカードがあればSDカード、およびゲームフォルダ</string>
<string name="mode_storage_auto_none">自動 - ゲームフォルダ、およびSDカードがあればSDカード(現在なし)</string>
<string name="mode_storage_auto">自動 - SDカードがあればSDカード</string>
<string name="mode_storage_auto_none">自動 - SDカードがあればSDカード(現在なし)</string>
<string name="mode_storage_internal">内部ストレージのみ</string>
<string name="mode_storage_folder">フォルダ:%1$s</string>
<string name="mode_second_library">第2ライブラリ</string>
@@ -638,7 +640,7 @@
<string name="setup_choose">選択</string>
<string name="setup_linux_apps">Linuxアプリ(ベータ版)</string>
<string name="setup_store">Flathubストア</string>
<string name="setup_store_on">メニューに表示されます。一部のアプリは起動できない場合があります。</string>
<string name="setup_store_on">メニューに表示されます。一部のアプリは起動できない場合があります。ログはDownload/DroidDeckにあります。</string>
<string name="setup_store_off">FlathubからLinuxアプリとゲームをインストール</string>
<string name="setup_tool_files">ファイル</string>
<string name="setup_tool_files_hint">ファイルの閲覧と管理</string>
@@ -1377,7 +1379,6 @@
<!-- File manager -->
<string name="fm_drive_internal">内部</string>
<string name="fm_drive_linux">Linux システム</string>
<string name="fm_drive_sd">SDカード</string>
<string name="fm_drive_storage">ストレージ</string>
<string name="fm_select">選択</string>
@@ -1532,7 +1533,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">「%1$s」をお気に入りから削除しました</string>
<string name="fm_empty_directory">空のフォルダ</string>
<string name="fm_up_one_level">1つ上の階層へ</string>
<string name="fm_choose_folder">フォルダを選択</string>
<string name="fm_choose_file">ファイルを選択</string>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s: 엔진 실패</string>
<string name="hud_fg_needs_lossless">%1$s: Lossless Scaling 필요</string>
<string name="hud_fg_starting">%1$s %2$s · 시작 중</string>
<string name="added_games_import_hint">여러 하위 폴더가 포함된 폴더이며, 각 하위 폴더는 Windows 게임에 해당합니다. Steam에서 소유한 게임은 Steam 재시작 후 해당 Steam 항목을 사용하고, 나머지 게임은 비 Steam 바로 가기가 됩니다. 보조 라이브러리가 자동이면 Steam이 이 폴더에도 게임을 설치할 수 있습니다.</string>
<string name="added_games_import_hint">여러 하위 폴더가 포함된 폴더이며, 각 하위 폴더는 Windows 게임에 해당합니다. Steam에서 소유한 게임은 Steam 재시작 후 해당 Steam 항목을 사용하고, 나머지 게임은 비 Steam 바로 가기가 됩니다.</string>
<string name="second_library_import_hint">Steam 라이브러리를 추가하고 그 안의 Windows 게임을 검사합니다. 소유한 게임은 해당 Steam 항목을 사용하고, 나머지 게임은 비 Steam 바로 가기가 됩니다.</string>
<string name="added_games_forget_hint">\"잊기\"를 누르면 다음 세션에서 이 바로 가기가 제거됩니다. 하지만 파일은 디스크에 그대로 남습니다.</string>
<string name="game_env_title">게임 환경</string>
@@ -289,6 +289,8 @@
<string name="mode_deck_mode_hint">Steam Deck UI 및 빠른 액세스 성능 제어. 다음 세션에 적용됩니다.</string>
<string name="mode_mangoapp">성능 오버레이</string>
<string name="mode_mangoapp_hint">Deck 모드에서 게임이 충돌하거나 화면이 검게 변하면 이 옵션을 끄세요. 다음 세션에 적용됩니다.</string>
<string name="mode_dual_xwayland">Xwayland 서버 2개</string>
<string name="mode_dual_xwayland_hint">SteamOS처럼 게임을 별도의 X 서버에서 실행합니다. 게임이 Steam 뒤에서 열리고 포커스를 받지 못하면 이 옵션을 끄세요. 다음 세션에 적용됩니다.</string>
<string name="mode_branch">클라이언트 브랜치</string>
<string name="mode_branch_deck">Steam Deck 베타(Deck 모드에 필요).</string>
<string name="mode_branch_hint">다음 세션에 적용됩니다. Steam이 자체적으로 한 번 업데이트될 수 있습니다.</string>
@@ -353,8 +355,8 @@
<string name="mode_wifi_explain_title">Wi-Fi 검색을 활성화하시겠습니까?</string>
<string name="mode_wifi_explain_text">Android는 Wi-Fi 이름을 읽고 주변 네트워크를 검색하려면 위치 권한이 필요합니다. DroidDeck은 이 권한을 사용하여 Steam에 이러한 네트워크를 표시합니다. 위치를 추적하지 않습니다. 이 권한 없이도 인터넷에 액세스할 수 있습니다.</string>
<string name="mode_storage">게임 저장 공간</string>
<string name="mode_storage_auto">자동 - SD 카드가 있으면 SD 카드 사용, 게임 폴더도 사용</string>
<string name="mode_storage_auto_none">자동 - 게임 폴더 사용, SD 카드가 있으면 SD 카드도 사용(현재 SD 카드 없음)</string>
<string name="mode_storage_auto">자동 - SD 카드가 있으면 SD 카드 사용</string>
<string name="mode_storage_auto_none">자동 - SD 카드가 있으면 SD 카드 사용(현재 SD 카드 없음)</string>
<string name="mode_storage_internal">내부 저장 공간만</string>
<string name="mode_storage_folder">폴더: %1$s</string>
<string name="mode_second_library">보조 라이브러리</string>
@@ -638,7 +640,7 @@
<string name="setup_choose">선택</string>
<string name="setup_linux_apps">Linux 앱(베타)</string>
<string name="setup_store">Flathub 스토어</string>
<string name="setup_store_on">메뉴에 표시됩니다. 일부 앱은 실행되지 않을 수 있습니다.</string>
<string name="setup_store_on">메뉴에 표시됩니다. 일부 앱은 실행되지 않을 수 있습니다. 로그는 Download/DroidDeck에 있습니다.</string>
<string name="setup_store_off">Flathub에서 Linux 앱 및 게임 설치</string>
<string name="setup_tool_files">파일</string>
<string name="setup_tool_files_hint">파일 탐색 및 관리</string>
@@ -1377,7 +1379,6 @@
<!-- File manager -->
<string name="fm_drive_internal">내부</string>
<string name="fm_drive_linux">Linux 시스템</string>
<string name="fm_drive_sd">SD 카드</string>
<string name="fm_drive_storage">저장소</string>
<string name="fm_select">선택</string>
@@ -1532,7 +1533,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">\"%1$s\"을(를) 즐겨찾기에서 제거했습니다</string>
<string name="fm_empty_directory">빈 폴더</string>
<string name="fm_up_one_level">상위 폴더로</string>
<string name="fm_choose_folder">폴더 선택</string>
<string name="fm_choose_file">파일 선택</string>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s: сбой движка</string>
<string name="hud_fg_needs_lossless">%1$s: требуется Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · Запуск</string>
<string name="added_games_import_hint">Папка, содержащая несколько подпапок, каждая из которых соответствует игре Windows. Игры, которыми вы владеете в Steam, будут использовать соответствующие записи Steam после перезапуска Steam, остальные игры станут ярлыками, отличными от Steam. Если для параметра «Вторая библиотека» выбрано «Авто», Steam также может устанавливать игры в эту папку.</string>
<string name="added_games_import_hint">Папка, содержащая несколько подпапок, каждая из которых соответствует игре Windows. Игры, которыми вы владеете в Steam, будут использовать соответствующие записи Steam после перезапуска Steam, остальные игры станут ярлыками, отличными от Steam.</string>
<string name="second_library_import_hint">Добавьте библиотеку Steam и отсканируйте в ней игры Windows. Имеющиеся игры будут использовать соответствующие записи Steam, остальные станут ярлыками, отличными от Steam.</string>
<string name="added_games_forget_hint">«Забыть» удалит эти ярлыки в следующей сессии. Но файлы останутся на диске.</string>
<string name="game_env_title">Игровая среда</string>
@@ -263,6 +263,8 @@
<string name="mode_deck_mode_hint">Интерфейс Steam Deck и управление производительностью через быстрый доступ. Вступит в силу в следующей сессии.</string>
<string name="mode_mangoapp">Оверлей производительности</string>
<string name="mode_mangoapp_hint">Отключите, если игры падают или появляется черный экран в режиме Deck. Вступит в силу в следующей сессии.</string>
<string name="mode_dual_xwayland">Два сервера Xwayland</string>
<string name="mode_dual_xwayland_hint">Запускает игры на отдельном X-сервере, как в SteamOS. Отключите, если игра открывается позади Steam и не получает фокус. Вступит в силу в следующей сессии.</string>
<string name="mode_branch">Ветка клиента</string>
<string name="mode_branch_deck">Бета-версия Steam Deck (требуется для режима Deck).</string>
<string name="mode_branch_hint">Вступит в силу в следующей сессии. Steam может обновиться самостоятельно один раз.</string>
@@ -300,8 +302,8 @@
<string name="mode_wifi_explain_title">Включить обнаружение Wi-Fi?</string>
<string name="mode_wifi_explain_text">Android требует разрешение на определение местоположения для чтения имен Wi-Fi и обнаружения ближайших сетей. DroidDeck использует это разрешение для отображения этих сетей в Steam. Мы не отслеживаем ваше местоположение. Доступ в интернет возможен и без этого разрешения.</string>
<string name="mode_storage">Хранилище игр</string>
<string name="mode_storage_auto">Авто - Использовать SD-карту при наличии, а также ваши папки с играми</string>
<string name="mode_storage_auto_none">Авто - Использовать ваши папки с играми, а также SD-карту при наличии (сейчас нет SD-карты)</string>
<string name="mode_storage_auto">Авто - Использовать SD-карту при наличии</string>
<string name="mode_storage_auto_none">Авто - Использовать SD-карту при наличии (сейчас нет SD-карты)</string>
<string name="mode_storage_internal">Только внутреннее хранилище</string>
<string name="mode_storage_folder">Папка: %1$s</string>
<string name="mode_second_library">Вторая библиотека</string>
@@ -536,7 +538,7 @@
<string name="setup_choose">Выбрать</string>
<string name="setup_linux_apps">Приложения Linux (бета)</string>
<string name="setup_store">Магазин Flathub</string>
<string name="setup_store_on">Показывается в меню. Некоторые приложения могут не запускаться.</string>
<string name="setup_store_on">Показывается в меню. Некоторые приложения могут не запускаться; журналы в Download/DroidDeck.</string>
<string name="setup_store_off">Устанавливать приложения и игры Linux из Flathub</string>
<string name="setup_tool_files">Файлы</string>
<string name="setup_tool_files_hint">Просмотр и управление файлами</string>
@@ -954,6 +956,4 @@
<string name="game_file_folder">Выбрать папку для файлов игры фронтенда</string>
<string name="game_file_exported">Файлы игры сохранены в %1$s</string>
<string name="game_frontend_files">Файлы фронтенда</string>
<string name="fm_up_one_level">На уровень вверх</string>
<string name="fm_drive_linux">Система Linux</string>
</resources>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s:引擎失败</string>
<string name="hud_fg_needs_lossless">%1$s:需要 Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · 启动中</string>
<string name="added_games_import_hint">一个文件夹,其中每个 Windows 游戏各占一个子文件夹。你在 Steam 拥有的游戏会在 Steam 重启后使用其 Steam 条目;其余会变成非 Steam 快捷方式。第二个库设为自动时,Steam 也可以把游戏安装到此文件夹。</string>
<string name="added_games_import_hint">一个文件夹,其中每个 Windows 游戏各占一个子文件夹。你在 Steam 拥有的游戏会在 Steam 重启后使用其 Steam 条目;其余会变成非 Steam 快捷方式。</string>
<string name="second_library_import_hint">添加一个 Steam 库并扫描其中的 Windows 游戏。已拥有的游戏使用其 Steam 条目;其余变成非 Steam 快捷方式。</string>
<string name="added_games_forget_hint">“移除”会在下次会话删除这些快捷方式。文件仍保留在磁盘上。</string>
<string name="game_env_title">游戏环境</string>
@@ -289,6 +289,8 @@
<string name="mode_deck_mode_hint">Steam 的 Deck 界面和快捷访问性能控制。将在下次会话生效。</string>
<string name="mode_mangoapp">性能覆盖层</string>
<string name="mode_mangoapp_hint">若游戏在 Deck 模式下崩溃或黑屏,请关闭性能覆盖层。将在下次会话生效。</string>
<string name="mode_dual_xwayland">双 Xwayland 服务器</string>
<string name="mode_dual_xwayland_hint">像 SteamOS 一样在独立的 X 服务器上运行游戏。若游戏在 Steam 后面打开且始终无法获得焦点,请关闭此项。将在下次会话生效。</string>
<string name="mode_branch">客户端分支</string>
<string name="mode_branch_deck">Steam Deck 公开测试版(Deck 模式所必需)。</string>
<string name="mode_branch_hint">将在下次会话生效。Steam 可能会自行更新一次。</string>
@@ -353,8 +355,8 @@
<string name="mode_wifi_explain_title">启用 Wi-Fi 网络发现?</string>
<string name="mode_wifi_explain_text">Android 需要位置权限才能读取 Wi-Fi 名称并发现附近网络。DroidDeck 用此权限在 Steam 中显示这些网络。我们不会跟踪你的位置。没有此权限互联网访问也能正常工作。</string>
<string name="mode_storage">游戏存储</string>
<string name="mode_storage_auto">自动 — 有 SD 卡时使用 SD 卡,以及你的游戏文件夹</string>
<string name="mode_storage_auto_none">自动 — 使用你的游戏文件夹,有 SD 卡时也使用 SD 卡(当前没有)</string>
<string name="mode_storage_auto">自动 — 有 SD 卡时使用 SD 卡</string>
<string name="mode_storage_auto_none">自动 — 有 SD 卡时使用 SD 卡(当前没有)</string>
<string name="mode_storage_internal">仅内部存储</string>
<string name="mode_storage_folder">文件夹:%1$s</string>
<string name="mode_second_library">第二个库</string>
@@ -638,7 +640,7 @@
<string name="setup_choose">选择</string>
<string name="setup_linux_apps">Linux 应用(测试版)</string>
<string name="setup_store">Flathub 商店</string>
<string name="setup_store_on">显示在菜单中。部分应用可能无法启动。</string>
<string name="setup_store_on">显示在菜单中。部分应用可能无法启动;日志位于 Download/DroidDeck。</string>
<string name="setup_store_off">从 Flathub 安装 Linux 应用和游戏</string>
<string name="setup_tool_files">文件</string>
<string name="setup_tool_files_hint">浏览和管理文件</string>
@@ -1377,7 +1379,6 @@
<!-- File manager -->
<string name="fm_drive_internal">内部存储</string>
<string name="fm_drive_linux">Linux 系统</string>
<string name="fm_drive_sd">SD 卡</string>
<string name="fm_drive_storage">存储</string>
<string name="fm_select">选择</string>
@@ -1532,7 +1533,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">已将“%1$s”从收藏夹移除</string>
<string name="fm_empty_directory">空文件夹</string>
<string name="fm_up_one_level">返回上一级</string>
<string name="fm_choose_folder">选择文件夹</string>
<string name="fm_choose_file">选择文件</string>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s:引擎故障</string>
<string name="hud_fg_needs_lossless">%1$s:需要 Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · 正在啟動</string>
<string name="added_games_import_hint">一個資料夾,每個 Windows 遊戲各佔一個子資料夾。你在 Steam 上擁有的遊戲會在 Steam 重新啟動後使用其 Steam 項目,其餘遊戲則成為非 Steam 捷徑。第二個收藏庫設為自動時,Steam 亦可以將遊戲安裝到此資料夾。</string>
<string name="added_games_import_hint">一個資料夾,每個 Windows 遊戲各佔一個子資料夾。你在 Steam 上擁有的遊戲會在 Steam 重新啟動後使用其 Steam 項目,其餘遊戲則成為非 Steam 捷徑。</string>
<string name="second_library_import_hint">新增一個 Steam 收藏庫並掃描其中的 Windows 遊戲。已擁有的遊戲會使用其 Steam 項目,其餘遊戲則成為非 Steam 捷徑。</string>
<string name="added_games_forget_hint">「忘記」會在下次會話移除這些捷徑,檔案仍會保留在磁碟上。</string>
<string name="game_env_title">遊戲環境</string>
@@ -289,6 +289,8 @@
<string name="mode_deck_mode_hint">Steam 的 Deck 介面及快速存取效能控制。下次會話生效。</string>
<string name="mode_mangoapp">效能疊加層</string>
<string name="mode_mangoapp_hint">如果在 Deck 模式下遊戲當機或黑畫面,請關閉此項。下次會話生效。</string>
<string name="mode_dual_xwayland">雙 Xwayland 伺服器</string>
<string name="mode_dual_xwayland_hint">像 SteamOS 一樣在獨立的 X 伺服器上執行遊戲。如果遊戲在 Steam 後面開啟且一直無法取得焦點,請關閉此項。下次會話生效。</string>
<string name="mode_branch">用戶端分支</string>
<string name="mode_branch_deck">Steam Deck 公開測試版(Deck 模式需要)。</string>
<string name="mode_branch_hint">下次會話生效。Steam 可能會自行更新一次。</string>
@@ -353,8 +355,8 @@
<string name="mode_wifi_explain_title">啟用 Wi-Fi 探索?</string>
<string name="mode_wifi_explain_text">Android 需要位置權限才能讀取 Wi-Fi 名稱和尋找附近網絡。DroidDeck 只會用此權限在 Steam 中顯示這些網絡,不會追蹤你的位置。沒有此權限亦可正常上網。</string>
<string name="mode_storage">遊戲儲存位置</string>
<string name="mode_storage_auto">自動 - 有 SD 卡時使用 SD 卡,以及你的遊戲資料夾</string>
<string name="mode_storage_auto_none">自動 - 使用你的遊戲資料夾,有 SD 卡時亦使用 SD 卡(目前沒有)</string>
<string name="mode_storage_auto">自動 - 有 SD 卡時使用 SD 卡</string>
<string name="mode_storage_auto_none">自動 - 有 SD 卡時使用 SD 卡(目前沒有)</string>
<string name="mode_storage_internal">只限內部儲存空間</string>
<string name="mode_storage_folder">資料夾:%1$s</string>
<string name="mode_second_library">第二個收藏庫</string>
@@ -638,7 +640,7 @@
<string name="setup_choose">選擇</string>
<string name="setup_linux_apps">Linux 應用程式(測試版)</string>
<string name="setup_store">Flathub 商店</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動。</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動;記錄位於 Download/DroidDeck。</string>
<string name="setup_store_off">從 Flathub 安裝 Linux 應用程式和遊戲</string>
<string name="setup_tool_files">檔案</string>
<string name="setup_tool_files_hint">瀏覽及管理檔案</string>
@@ -1377,7 +1379,6 @@
<!-- File manager -->
<string name="fm_drive_internal">內部</string>
<string name="fm_drive_linux">Linux 系統</string>
<string name="fm_drive_sd">SD 卡</string>
<string name="fm_drive_storage">儲存空間</string>
<string name="fm_select">選取</string>
@@ -1532,7 +1533,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">已將「%1$s」從我的最愛移除</string>
<string name="fm_empty_directory">空白目錄</string>
<string name="fm_up_one_level">返回上一層</string>
<string name="fm_choose_folder">選擇資料夾</string>
<string name="fm_choose_file">選擇檔案</string>
+6 -6
View File
@@ -41,7 +41,7 @@
<string name="hud_fg_failed">%1$s:引擎失敗</string>
<string name="hud_fg_needs_lossless">%1$s:需要 Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · 正在啟動</string>
<string name="added_games_import_hint">一個包含多個子資料夾的資料夾,每個子資料夾對應一個 Windows 遊戲。你在 Steam 上擁有的遊戲會在 Steam 重啟後使用對應的 Steam 項目,其餘遊戲會成為非 Steam 捷徑。第二收藏庫設為自動時,Steam 也可以將遊戲安裝到此資料夾。</string>
<string name="added_games_import_hint">一個包含多個子資料夾的資料夾,每個子資料夾對應一個 Windows 遊戲。你在 Steam 上擁有的遊戲會在 Steam 重啟後使用對應的 Steam 項目,其餘遊戲會成為非 Steam 捷徑。</string>
<string name="second_library_import_hint">新增一個 Steam 收藏庫,並掃描其中的 Windows 遊戲。已擁有的遊戲會使用對應的 Steam 項目,其餘遊戲會成為非 Steam 捷徑。</string>
<string name="added_games_forget_hint">「忘記」會在下次工作階段中移除這些捷徑。但檔案仍保留在磁碟上。</string>
<string name="game_env_title">遊戲環境</string>
@@ -289,6 +289,8 @@
<string name="mode_deck_mode_hint">Steam Deck 介面和快速存取效能控制。下次工作階段生效。</string>
<string name="mode_mangoapp">效能重疊層</string>
<string name="mode_mangoapp_hint">如果 Deck 模式下遊戲崩潰或黑畫面,請關閉此項。下次工作階段生效。</string>
<string name="mode_dual_xwayland">雙 Xwayland 伺服器</string>
<string name="mode_dual_xwayland_hint">像 SteamOS 一樣在獨立的 X 伺服器上執行遊戲。如果遊戲在 Steam 後面開啟且一直無法取得焦點,請關閉此項。下次工作階段生效。</string>
<string name="mode_branch">用戶端分支</string>
<string name="mode_branch_deck">Steam Deck 公開測試版(Deck 模式所需)。</string>
<string name="mode_branch_hint">下次工作階段生效。Steam 可能會自行更新一次。</string>
@@ -353,8 +355,8 @@
<string name="mode_wifi_explain_title">啟用 Wi-Fi 探索?</string>
<string name="mode_wifi_explain_text">Android 需要定位權限才能讀取 Wi-Fi 名稱並探索附近網路。DroidDeck 使用此權限在 Steam 中顯示這些網路。我們不會追蹤你的位置。沒有此權限也可以存取網際網路。</string>
<string name="mode_storage">遊戲儲存空間</string>
<string name="mode_storage_auto">自動 - 有 SD 卡時使用 SD 卡,以及你的遊戲資料夾</string>
<string name="mode_storage_auto_none">自動 - 使用你的遊戲資料夾,有 SD 卡時也使用 SD 卡(目前無 SD 卡)</string>
<string name="mode_storage_auto">自動 - 有 SD 卡時使用 SD 卡</string>
<string name="mode_storage_auto_none">自動 - 有 SD 卡時使用 SD 卡(目前無 SD 卡)</string>
<string name="mode_storage_internal">僅內部儲存空間</string>
<string name="mode_storage_folder">資料夾:%1$s</string>
<string name="mode_second_library">第二收藏庫</string>
@@ -638,7 +640,7 @@
<string name="setup_choose">選擇</string>
<string name="setup_linux_apps">Linux 應用程式(測試版)</string>
<string name="setup_store">Flathub 商店</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動。</string>
<string name="setup_store_on">顯示在選單中。部分應用程式可能無法啟動;日誌位於 Download/DroidDeck。</string>
<string name="setup_store_off">從 Flathub 安裝 Linux 應用程式和遊戲</string>
<string name="setup_tool_files">檔案</string>
<string name="setup_tool_files_hint">瀏覽和管理檔案</string>
@@ -1377,7 +1379,6 @@
<!-- File manager -->
<string name="fm_drive_internal">內部</string>
<string name="fm_drive_linux">Linux 系統</string>
<string name="fm_drive_sd">SD 卡</string>
<string name="fm_drive_storage">儲存空間</string>
<string name="fm_select">選取</string>
@@ -1532,7 +1533,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">已將「%1$s」從我的最愛移除</string>
<string name="fm_empty_directory">空的資料夾</string>
<string name="fm_up_one_level">返回上一層</string>
<string name="fm_choose_folder">選擇資料夾</string>
<string name="fm_choose_file">選擇檔案</string>
+6 -11
View File
@@ -15,10 +15,8 @@
<string name="session_channel">Session</string>
<string name="session_channel_description">Shows while a Steam or desktop session is open</string>
<string name="session_notification">Steam is running</string>
<string name="session_notification_downloads">Steam download active</string>
<string name="session_notification_paused">Session paused - tap Resume when ready</string>
<string name="resume_session">Resume</string>
<string name="suspend_now">Suspend now</string>
<string name="stop_session">Stop session</string>
<string name="frame_gen_title">Frame generation</string>
<string name="frame_gen_hint">Select the frame generation mode</string>
@@ -43,7 +41,7 @@
<string name="hud_fg_failed">%1$s: engine failed</string>
<string name="hud_fg_needs_lossless">%1$s: needs Lossless Scaling</string>
<string name="hud_fg_starting">%1$s %2$s · starting</string>
<string name="added_games_import_hint">A folder with one subfolder per Windows game. Games you own on Steam use their Steam entries after Steam restarts; the rest become non-Steam shortcuts. With Second library on Automatic, Steam can install games into this folder too.</string>
<string name="added_games_import_hint">A folder with one subfolder per Windows game. Games you own on Steam use their Steam entries after Steam restarts; the rest become non-Steam shortcuts.</string>
<string name="second_library_import_hint">Adds a Steam library and scans it for Windows games. Owned games use their Steam entries; the rest become non-Steam shortcuts.</string>
<string name="added_games_forget_hint">Forget removes the shortcuts next session. Files stay on disk.</string>
<string name="game_env_title">Game environment</string>
@@ -269,8 +267,6 @@
<string name="mode_suspend_manual">Manual</string>
<string name="mode_suspend_native">Native</string>
<string name="mode_suspend_steam_note">Auto pauses and resumes when shown. Native prepares Steam for sleep first. Manual waits for Resume. Never keeps running.</string>
<string name="mode_background_downloads">Keep downloads running</string>
<string name="mode_background_downloads_hint">Delay background suspension while Steam is actively downloading.</string>
<string name="mode_suspend_note">Auto pauses in the background and resumes when shown. Manual waits for Resume. Never keeps running.</string>
<string name="mode_startup">Startup</string>
<string name="mode_steam_startup">Start Steam with DroidDeck</string>
@@ -293,6 +289,8 @@
<string name="mode_deck_mode_hint">Steam\'s Deck interface and Quick Access performance controls. Applies next session.</string>
<string name="mode_mangoapp">Performance overlay</string>
<string name="mode_mangoapp_hint">Turn off if games crash or go black in Deck mode. Applies next session.</string>
<string name="mode_dual_xwayland">Two Xwayland servers</string>
<string name="mode_dual_xwayland_hint">Runs games on their own X server, as SteamOS does. Turn off if a game opens behind Steam and never takes focus. Applies next session.</string>
<string name="mode_branch">Client branch</string>
<string name="mode_branch_deck">Steam Deck public beta (required by Deck mode).</string>
<string name="mode_branch_hint">Applies next session. Steam may update itself once.</string>
@@ -357,8 +355,8 @@
<string name="mode_wifi_explain_title">Enable Wi-Fi discovery?</string>
<string name="mode_wifi_explain_text">Android requires Location permission to read Wi-Fi names and discover nearby networks. DroidDeck uses this access to show those networks in Steam. We don\'t track your location. Internet access works without this permission.</string>
<string name="mode_storage">Game storage</string>
<string name="mode_storage_auto">Automatic - the SD card when present, plus your Games folders</string>
<string name="mode_storage_auto_none">Automatic - your Games folders, plus the SD card when present (none now)</string>
<string name="mode_storage_auto">Automatic - the SD card when present</string>
<string name="mode_storage_auto_none">Automatic - the SD card when present (none now)</string>
<string name="mode_storage_internal">Internal only</string>
<string name="mode_storage_folder">Folder: %1$s</string>
<string name="mode_second_library">Second library</string>
@@ -643,7 +641,7 @@
<string name="setup_choose">Choose</string>
<string name="setup_linux_apps">Linux apps (beta)</string>
<string name="setup_store">Flathub Store</string>
<string name="setup_store_on">In the menu. Some apps may not start.</string>
<string name="setup_store_on">In the menu. Some apps may not start; logs are in Download/DroidDeck.</string>
<string name="setup_store_off">Install Linux apps and games from Flathub</string>
<string name="setup_tool_files">Files</string>
<string name="setup_tool_files_hint">Browse and manage files</string>
@@ -1345,7 +1343,6 @@
<string name="content_system_many">Many systems</string>
<!-- File manager -->
<string name="fm_drive_internal">Internal</string>
<string name="fm_drive_linux">Linux system</string>
<string name="fm_drive_sd">SD card</string>
<string name="fm_drive_storage">Storage</string>
<string name="fm_select">Select</string>
@@ -1486,7 +1483,6 @@
<!-- %1$s is a folder name -->
<string name="fm_favorite_removed">Removed \"%1$s\" from Favorites</string>
<string name="fm_empty_directory">Empty directory</string>
<string name="fm_up_one_level">Up one level</string>
<string name="fm_choose_folder">Choose a folder</string>
<string name="fm_choose_file">Choose a file</string>
<!-- On-screen controller tint colors -->
@@ -1851,7 +1847,6 @@
<string name="gstore_sd_card">SD card</string>
<!-- %1$s is a size, like 12.3 GB -->
<string name="gstore_folder">Folder</string>
<string name="gstore_folder_on_volume" translatable="false">%1$s (%2$s)</string>
<string name="logshare_chooser">Share session logs</string>
<!-- Stands in for the Steam account name when the client did not record one -->
@@ -55,37 +55,4 @@ class LogRedactorTest {
assertEquals(once, LogRedactor.redact(once))
}
}
@Test fun quotedAndShortSecretsAreRedacted() {
for (line in listOf("\"access_token\": \"short-secret\"", "\"password\"=\"abc\"", "pwd=x")) {
val out = LogRedactor.redact(line)
assertTrue(out.contains("<redacted:token>"))
assertEquals(out, LogRedactor.redact(out))
}
}
@Test fun authorizationHeadersAreRedacted() {
for (line in listOf("Authorization: Bearer secret-value", "Proxy-Authorization: Basic dXNlcjpwYXNz",
"\"Authorization\":\"Bearer secret-value\"")) {
val out = LogRedactor.redact(line)
assertFalse(out.contains("secret-value"))
assertFalse(out.contains("dXNlcjpwYXNz"))
assertTrue(out.contains("<redacted:authorization>"))
assertEquals(out, LogRedactor.redact(out))
}
}
@Test fun quotedSecretsWithSpacesAndEscapedQuotesAreFullyWithheld() {
val lines = listOf(
"password=\"my secret phrase\"",
"password='my secret phrase'",
"\"access_token\":\"my \\\"secret\\\" phrase\"",
)
for (line in lines) {
val out = LogRedactor.redact(line)
assertFalse(out.contains("phrase"))
assertFalse(out.contains("secret"))
assertTrue(out.contains("<redacted:token>"))
assertEquals(out, LogRedactor.redact(out))
}
}
}
@@ -1,30 +0,0 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
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
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGamesScanTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Test fun theSteamLibraryInsideAGamesFolderIsNotAGame() {
val games = tmp.newFolder("PC")
File(games, "Example").mkdirs()
File(games, "Example/Example.exe").writeText("game")
File(games, "steamapps/downloading").mkdirs()
File(games, "steamapps/downloading/Depot.exe").writeText("depot")
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
assertEquals(listOf("Example"), AddedGames.scan(app).map { it.name })
}
}
@@ -1,113 +0,0 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
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.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class AddedGamesSteamEditsTest {
@get:Rule val tmp = TemporaryFolder()
private lateinit var context: Context
private lateinit var games: File
private lateinit var folder: File
private lateinit var main: File
private lateinit var other: File
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
games = tmp.newFolder("PC")
folder = File(games, "Example").apply { mkdirs() }
main = File(folder, "Example.exe").apply { writeBytes(ByteArray(64)) }
other = File(folder, "bin/Other.exe").apply { parentFile!!.mkdirs(); writeBytes(ByteArray(8)) }
SessionPrefs.setGameStorage(context, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(context, listOf(games.path))
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config").mkdirs()
}
private fun record(appId: Long, asked: String, steam: String, rev: Int) {
val game = JSONObject()
.put("app", JSONObject().put("Exe", "\"$asked\""))
.put("steam", JSONObject().put("Exe", "\"$steam\""))
.put("rev", rev)
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/userdata/123/config/.droiddeck-shortcuts.json")
.writeText(JSONObject().put("games", JSONObject().put(appId.toString(), game)).toString())
}
private fun scanned() = AddedGames.scan(context).single { it.folder == folder }
@Test fun aTargetChangedInSteamBecomesTheAppsChoiceOnce() {
val first = scanned()
assertEquals(main, first.exe)
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 1)
val adopted = scanned()
assertEquals(other, adopted.exe)
assertEquals("/root/Games/PC/Example/bin/Other.exe", adopted.guestExe)
assertEquals(first.appId, adopted.appId)
assertEquals(other.path, SessionPrefs.addedGameExe(context, folder.path))
assertEquals(1, SessionPrefs.addedGameExeSeen(context, folder.path))
SessionPrefs.setAddedGameExe(context, folder.path, main.path)
val chosen = scanned()
assertEquals(main, chosen.exe)
assertEquals(first.appId, chosen.appId)
assertEquals(main.path, SessionPrefs.addedGameExe(context, folder.path))
}
@Test fun theListingTellsTheSessionWhichSteamEditTheAppHasTaken() {
val first = scanned()
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/bin/Other.exe", 3)
val listing = JSONObject(AddedGames.writeListing(context, listOf(scanned())).readText().removePrefix("[").removeSuffix("]"))
assertEquals("/root/Games/PC/Example/bin/Other.exe", listing.getString("exe"))
assertEquals("/root/Games/PC/Example/bin", listing.getString("dir"))
assertEquals(3, listing.getInt("seen"))
assertEquals(first.appId, listing.getLong("appid"))
}
@Test fun theAppidStaysWithTheFolderWhenItsExeChanges() {
val first = scanned()
SessionPrefs.setAddedGameExe(context, folder.path, other.path)
val changed = scanned()
assertEquals(other, changed.exe)
assertEquals(first.appId, changed.appId)
assertEquals(first.gameId, changed.gameId)
}
@Test fun aSteamTargetOutsideTheFolderIsNotTaken() {
val outside = File(games, "Elsewhere/Game.exe").apply { parentFile!!.mkdirs(); writeBytes(ByteArray(8)) }
val first = scanned()
record(first.appId, "/root/Games/PC/Example/Example.exe", "/root/Games/PC/Example/../Elsewhere/Game.exe", 1)
assertEquals(main, scanned().exe)
assertEquals("", SessionPrefs.addedGameExe(context, folder.path))
assertEquals(0, SessionPrefs.addedGameExeSeen(context, folder.path))
assertTrue(outside.isFile)
}
@Test fun steamTargetNeedsANewEditThatStartsFromTheAppsExe() {
val guest = "/root/Games/PC/Example"
fun game(asked: String, steam: String, rev: Int) = JSONObject()
.put("app", JSONObject().put("Exe", "\"$guest/$asked\""))
.put("steam", JSONObject().put("Exe", "\"$guest/$steam\""))
.put("rev", rev)
assertEquals(other, AddedGames.steamTarget(folder, guest, game("Example.exe", "bin/Other.exe", 2), "$guest/Example.exe", 1))
assertNull(AddedGames.steamTarget(folder, guest, game("Example.exe", "bin/Other.exe", 2), "$guest/Example.exe", 2))
assertNull(AddedGames.steamTarget(folder, guest, game("Example.exe", "bin/Other.exe", 2), "$guest/bin/Other.exe", 0))
assertNull(AddedGames.steamTarget(folder, guest, game("Example.exe", "Example.exe", 2), "$guest/Example.exe", 0))
assertNull(AddedGames.steamTarget(folder, guest, game("Example.exe", "Missing.exe", 2), "$guest/Example.exe", 0))
assertNull(AddedGames.steamTarget(folder, guest, null, "$guest/Example.exe", 0))
}
}
@@ -1,42 +0,0 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.frontend.AddedGames
import java.io.File
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
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GameStorageTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Test fun gamesFoldersBecomeLibrariesOnAutomatic() {
val pc = tmp.newFolder("PC")
val missing = File(tmp.root, "Unplugged")
SessionPrefs.setAddedGamesDirs(app, listOf(pc.path, missing.path))
val libraries = GameStorage.gamesFolderLibraries(app)
assertEquals(listOf(pc), libraries.map { it.host })
assertEquals(listOf(AddedGames.GUEST_DIR + "/PC"), libraries.map { it.guest })
assertEquals(listOf("PC"), libraries.map { it.label })
}
@Test fun aChosenLibraryOrInternalKeepsGamesFoldersPlain() {
SessionPrefs.setAddedGamesDirs(app, listOf(tmp.newFolder("PC").path))
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
SessionPrefs.setGameStorage(app, tmp.newFolder("chosen").path, "Chosen")
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
}
@Test fun namesTheClientCannotStoreAreLeftOut() {
SessionPrefs.setAddedGamesDirs(app, listOf(tmp.newFolder("Quote\"d").path, tmp.newFolder("Back\\slash").path))
assertTrue(GameStorage.gamesFolderLibraries(app).isEmpty())
}
}
@@ -25,17 +25,6 @@ class SecondaryLibraryTest {
}
}
@Test fun aGamesFolderLibraryIsBoundOnlyAtItsOwnPath() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("PC")
val binds = SecondaryLibrary.binds(files, library, listOf("/root/Games/PC"))
val private = SecondaryLibrary.privateRoot(files, library)
assertEquals("${library.path}:/root/Games/PC", binds.first())
assertTrue(binds.contains("$private/steamapps/compatdata:/root/Games/PC/steamapps/compatdata"))
assertTrue(binds.drop(1).all { it.substringAfter(':').startsWith("/root/Games/PC/steamapps/") })
assertFalse(binds.any { it.contains("/mnt/") })
}
@Test fun migrationPreservesSavesLinksAndOriginalAndNeverOverwritesNewSaves() {
val files = tmp.newFolder("files")
val library = tmp.newFolder("card")
@@ -33,27 +33,4 @@ class SessionBackgroundPrefsTest {
assertEquals(SessionPrefs.SUSPEND_AUTO, SessionPrefs.suspendPolicy(context, SessionService.MODE_RUN))
assertEquals(SessionPrefs.SUSPEND_NATIVE, SessionPrefs.suspendPolicy(context, SessionService.MODE_STEAM))
}
@Test fun backgroundDownloadsAreOptInAndMigrateTheTestBuildPolicy() {
assertEquals(false, SessionPrefs.steamDownloadsInBackground(context))
SessionPrefs.setSteamDownloadsInBackground(context, true)
assertEquals(true, SessionPrefs.steamDownloadsInBackground(context))
clearSettings()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putString("suspendPolicy.steam", "downloads").commit()
assertEquals(SessionPrefs.SUSPEND_AUTO, SessionPrefs.suspendPolicy(context, SessionService.MODE_STEAM))
assertEquals(true, SessionPrefs.steamDownloadsInBackground(context))
SessionPrefs.setSuspendPolicy(context, SessionService.MODE_STEAM, SessionPrefs.SUSPEND_MANUAL)
assertEquals(SessionPrefs.SUSPEND_MANUAL, SessionPrefs.suspendPolicy(context, SessionService.MODE_STEAM))
assertEquals(true, SessionPrefs.steamDownloadsInBackground(context))
clearSettings()
context.getSharedPreferences("session", Context.MODE_PRIVATE).edit()
.putString("suspendPolicy.steam", "downloads").commit()
SessionPrefs.setSteamDownloadsInBackground(context, false)
assertEquals(SessionPrefs.SUSPEND_AUTO, SessionPrefs.suspendPolicy(context, SessionService.MODE_STEAM))
assertEquals(false, SessionPrefs.steamDownloadsInBackground(context))
}
}
@@ -1,100 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.nio.file.Files
class SessionLogMigrationTest {
@get:Rule val tmp = TemporaryFolder()
private fun source(name: String = "2026-10-06-01-steam"): File = tmp.newFolder(name).apply {
File(this, "steam").mkdir()
File(this, "session.log").writeText("Using JWT 25484942796017334\n")
File(this, "steam/console_log.txt").writeText("password=private\n")
File(this, ".complete").writeText("done")
}
@Test fun legacySessionsMoveIntoPrivateStorage() {
val source = source()
val target = tmp.newFolder("private")
SessionLogMigration.move(source, target)
assertFalse(source.exists())
val moved = File(target, source.name)
assertTrue(SessionPaths.isSessionFolder(moved))
assertTrue(File(moved, "steam/console_log.txt").readText().contains("password=private"))
assertTrue(File(moved, ".complete").isFile)
}
@Test fun crossFilesystemFallbackCopiesEverythingBeforeRemovingTheOriginal() {
val original = source()
val source = object : File(original.path) {
override fun renameTo(dest: File): Boolean = false
}
val target = tmp.newFolder("private")
SessionLogMigration.move(source, target)
assertFalse(original.exists())
assertEquals("Using JWT 25484942796017334\n", File(target, "${original.name}/session.log").readText())
assertEquals(listOf(original.name), target.list()!!.toList())
}
@Test fun aCopyFailurePreservesAllOriginalFiles() {
val original = source()
val source = object : File(original.path) {
override fun renameTo(dest: File): Boolean = false
}
val target = tmp.newFolder("private")
target.setWritable(false)
try {
assertThrows(java.io.IOException::class.java) { SessionLogMigration.move(source, target) }
} finally {
target.setWritable(true)
}
assertTrue(File(original, "session.log").isFile)
assertTrue(File(original, "steam/console_log.txt").isFile)
assertTrue(target.list()!!.isEmpty())
}
@Test fun collisionsPreserveBothSessionsAndKeepLegacyNamesRecognizable() {
val original = source("session-20260930-180642-2")
val target = tmp.newFolder("private")
File(target, original.name).mkdir()
SessionLogMigration.move(original, target)
assertEquals(2, target.listFiles()!!.size)
assertTrue(target.listFiles()!!.all { SessionPaths.isSessionFolder(it) })
}
@Test fun linksAreRejectedWithoutReadingOrDeletingTheirTargets() {
val source = source()
val outside = tmp.newFile("outside").apply { writeText("outside data") }
Files.createSymbolicLink(File(source, "steam/connection_log.txt").toPath(), outside.toPath())
val target = tmp.newFolder("private")
assertThrows(IllegalStateException::class.java) { SessionLogMigration.move(source, target) }
assertTrue(File(source, "session.log").exists())
assertTrue(target.list()!!.isEmpty())
assertEquals("outside data", outside.readText())
}
@Test fun cleanupDoesNotFollowNestedDirectoryLinks() {
val source = source()
val outside = tmp.newFolder("outside")
val preserved = File(outside, "session.log").apply { writeText("outside data") }
Files.createSymbolicLink(File(source, "linked").toPath(), outside.toPath())
SessionLogFiles.deleteTree(source)
assertFalse(source.exists())
assertEquals("outside data", preserved.readText())
}
@Test fun aCopiedCollisionKeepsTheNewerSessionAsTheLatest() {
val original = source()
original.setLastModified(1000L)
val source = object : File(original.path) {
override fun renameTo(dest: File): Boolean = false
}
val target = tmp.newFolder("private")
val newer = File(target, original.name).apply { mkdir(); setLastModified(2000L) }
SessionLogMigration.move(source, target)
assertEquals(newer, target.listFiles()!!.sortedWith(SessionPaths.chronological).last())
}
}
@@ -1,7 +1,9 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.junit.Assert.*
import com.droiddeck.launcher.core.LogRedactor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
@@ -10,197 +12,114 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
import java.io.RandomAccessFile
import java.io.StringWriter
import java.io.Writer
import java.nio.file.Files
import java.util.zip.ZipFile
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class SessionLogShareTest {
@get:Rule val tmp = TemporaryFolder()
private val context get() = RuntimeEnvironment.getApplication()
private val secret = "Using JWT 25484942796017334 sessionid=abcdef123456 password=secret123"
private val leaked = listOf("25484942796017334", "abcdef123456", "secret123")
private fun write(folder: File, path: String, text: String = "$secret\n"): File =
File(folder, path).apply { parentFile!!.mkdirs(); writeText(text) }
private val secret = "GET /x?sessionid=abcdef123456 200"
private val leaked = "abcdef123456"
private fun zip(folder: File): Map<String, String> =
ZipFile(SessionLogShare.zipFolder(context, folder)!!).use { z ->
ZipFile(SessionLogShare.zipFolder(RuntimeEnvironment.getApplication(), folder)!!).use { z ->
z.entries().toList().associate { it.name.substringAfter('/') to z.getInputStream(it).bufferedReader().readText() }
}
private fun assertSafe(files: Map<String, String>) {
files.forEach { (name, text) -> leaked.forEach { assertFalse(name, text.contains(it)) } }
/** A record as the session's ending writes it, listing [files] as they stand now. */
private fun record(folder: File, vararg files: String, rules: Int = LogRedactor.RULES_VERSION) {
File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).writeText(
"rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" })
}
@Test fun workingLogsAndCommandLogsUsePrivateStorage() {
assertEquals(File(context.filesDir, "logs"), SessionFiles.logDirectory(context))
assertEquals(SessionFiles.logDirectory(context), LinuxRuntime.debugLogDir(context))
assertTrue(File(LinuxRuntime.debugLogDir(context), SessionPaths.TOOLS_DIR).path.startsWith(context.filesDir.path + "/"))
val dir = SessionPaths.beginOrCurrent(context, "privacy-test")
try {
assertTrue(dir.path.startsWith(context.filesDir.path + "/") || dir.path.startsWith(context.cacheDir.path + "/"))
} finally {
SessionPaths.take()
SessionPaths.release(context, dir)
dir.deleteRecursively()
}
}
@Test fun forgedAndStaleScrubRecordsNeverBypassRedaction() {
@Test fun aRecordedUnchangedFileGoesInAsItIs() {
val folder = tmp.newFolder("2026-10-06-01-steam")
val file = write(folder, "session.log")
write(folder, ".scrubbed-tree", "rules 1\n${file.length()}\t${file.lastModified()}\tsession.log\n")
write(folder, ".complete", "done")
assertSafe(zip(folder))
val modified = file.lastModified()
file.writeText("$secret\n")
file.setLastModified(modified)
assertSafe(zip(folder))
assertEquals(setOf("session.log"), zip(folder).keys)
// Stands in for a file the ending scrubbed; the share must not pass it through again.
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log")
assertTrue(zip(folder).getValue("session.log").contains(leaked))
}
@Test fun allowlistIncludesDiagnosticsAndExcludesCredentialStoresAndUnknownFiles() {
@Test fun anythingTheRecordDoesNotVouchForIsScrubbed() {
val folder = tmp.newFolder("2026-10-06-02-steam")
val allowed = listOf("session.log", "app.log", "crash-app.txt", "events.jsonl",
"steam/console_log.txt", "droiddeck-esync/launches.log", "droiddeck-fex/status.json")
val excluded = listOf(".hidden.txt", ".session.log.scrub", "steam/deep/nested.txt",
"steam/loginusers.vdf", "steam/config.vdf", "ssfn123", "arbitrary.txt",
"steam/token.txt", "droiddeck-fex/config/secrets.json")
(allowed + excluded).forEach { write(folder, it) }
val files = zip(folder)
assertEquals(allowed.toSet(), files.keys)
assertSafe(files)
File(folder, "app.log").writeText("ok\n")
File(folder, "session.log").writeText("ok\n")
File(folder, "steam/deep").mkdirs()
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
File(folder, ".hidden.txt").writeText("$secret\n")
record(folder, "app.log", "session.log")
// Appended to after the ending (the app's log capture), and touched with an older time.
File(folder, "app.log").appendText("$secret\n")
File(folder, "session.log").apply { writeText("$secret\n".padEnd(3, ' ')); setLastModified(1_000L) }
File(folder, "events.jsonl").writeText("$secret\n")
val out = zip(folder)
for (name in listOf("app.log", "session.log", "steam/deep/nested.txt", ".hidden.txt", "events.jsonl"))
assertFalse(name, out.getValue(name).contains(leaked))
}
@Test fun oversizedLiveAndFinishedLogsAreOmittedWithoutRawFallback() {
for (finished in listOf(false, true)) for (size in listOf(SessionLogFiles.MAX_BYTES, SessionLogFiles.MAX_BYTES + 1)) {
val folder = tmp.newFolder("2026-10-06-${if (finished) "03" else "04"}-steam-$size")
write(folder, "app.log")
val large = write(folder, "session.log")
RandomAccessFile(large, "rw").use { it.setLength(size) }
if (finished) write(folder, ".complete", "done")
val files = zip(folder)
assertFalse(files.containsKey("session.log"))
assertTrue(files.getValue("omitted.txt").contains("session.log"))
assertSafe(files)
}
@Test fun aRecordUnderOtherRedactorRulesVouchesForNothing() {
val folder = tmp.newFolder("2026-10-06-03-steam")
File(folder, "session.log").writeText("$secret\n")
record(folder, "session.log", rules = LogRedactor.RULES_VERSION - 1)
assertFalse(zip(folder).getValue("session.log").contains(leaked))
}
@Test fun binaryDataPastTheProbeMalformedUtf8AndLongLinesAreOmitted() {
@Test fun withoutARecordEveryFileIsScrubbed() {
val folder = tmp.newFolder("2026-10-06-04-steam")
File(folder, "session.log").writeText("$secret\n")
File(folder, "steam").mkdirs()
File(folder, "steam/console_log.txt").writeText("$secret\n")
val out = zip(folder)
assertFalse(out.getValue("session.log").contains(leaked))
assertFalse(out.getValue("steam/console_log.txt").contains(leaked))
}
@Test fun theEndingScrubsEveryFolderAndRecordsWhatItScrubbed() {
val folder = tmp.newFolder("2026-10-06-05-steam")
write(folder, "session.log", "safe\n".repeat(2000) + "$secret\n\u0000")
File(folder, "app.log").writeBytes(byteArrayOf(0xc3.toByte(), 0x28))
write(folder, "crash.log", "x".repeat(65537) + secret)
val files = zip(folder)
assertEquals(setOf("omitted.txt"), files.keys)
assertSafe(files)
File(folder, "session.log").writeText("$secret\n")
File(folder, "droiddeck-esync").mkdirs()
File(folder, "droiddeck-esync/launches.log").writeText("$secret\n")
File(folder, "steam/deep").mkdirs()
File(folder, "steam/deep/nested.txt").writeText("$secret\n")
SessionArtifacts.scrubAndMark(folder)
for (name in listOf("session.log", "droiddeck-esync/launches.log", "steam/deep/nested.txt"))
assertFalse(name, File(folder, name).readText().contains(leaked))
assertEquals(setOf("session.log", "droiddeck-esync/launches.log", "steam/deep/nested.txt"),
SessionArtifacts.scrubbedFiles(folder))
assertTrue(zip(folder).values.none { it.contains(leaked) })
}
@Test fun symlinkFilesAndDirectoriesCannotExportOutsideData() {
@Test fun aFileThatCouldNotBeScrubbedLeavesTheFolderUnrecorded() {
val folder = tmp.newFolder("2026-10-06-06-steam")
val outside = tmp.newFolder("outside")
val target = write(outside, "console_log.txt", "outside data\n")
Files.createSymbolicLink(File(folder, "session.log").toPath(), target.toPath())
Files.createSymbolicLink(File(folder, "steam").toPath(), outside.toPath())
val files = zip(folder)
assertEquals(setOf("omitted.txt"), files.keys)
assertTrue(files.values.none { it.contains("outside data") })
val alias = File(tmp.root, "2026-10-06-07-steam")
Files.createSymbolicLink(alias.toPath(), folder.toPath())
assertFalse(SessionPaths.isSessionFolder(alias))
assertNull(SessionLogShare.zipFolder(context, alias))
}
@Test fun failedTeardownScrubbingStillRedactsExports() {
val folder = tmp.newFolder("2026-10-06-08-steam")
val file = write(folder, "session.log")
File(folder, "session.log").writeText("$secret\n")
// A folder the scrubbed copy cannot be written into: the scrub fails, the original stays.
folder.setWritable(false)
try {
SessionArtifacts.scrubTree(folder)
SessionArtifacts.scrubAndMark(folder)
} finally {
folder.setWritable(true)
}
assertTrue(file.readText().contains(leaked.first()))
assertSafe(zip(folder))
assertTrue(File(folder, "session.log").readText().contains(leaked))
assertFalse(File(folder, SessionArtifacts.SCRUBBED_TREE_MARKER).exists())
assertTrue(SessionArtifacts.scrubbedFiles(folder).isEmpty())
assertTrue(zip(folder).values.none { it.contains(leaked) })
}
@Test fun unreadableAllowedFilesAreOmitted() {
val folder = tmp.newFolder("2026-10-06-09-steam")
val file = write(folder, "session.log")
file.setReadable(false)
try {
val files = zip(folder)
assertEquals(setOf("omitted.txt"), files.keys)
assertSafe(files)
} finally {
file.setReadable(true)
@Test fun steamLogsPastTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-07-steam")
File(folder, "session.log").writeText("ok\n")
File(folder, "steam").mkdirs()
File(folder, "steam/console_log.txt").writeText("ok\n")
File(folder, "steam/cef_log.previous.txt").outputStream().use { out ->
val line = ByteArray(1024) { 'x'.code.toByte() }.also { it[it.size - 1] = '\n'.code.toByte() }
repeat(9 * 1024) { out.write(line) }
}
}
@Test fun successfulTeardownScrubsNestedDiagnosticsWithoutRecords() {
val folder = tmp.newFolder("2026-10-06-10-steam")
val paths = listOf("session.log", "crash-app.txt", "droiddeck-esync/launches.log", "steam/console_log.txt")
paths.forEach { write(folder, it) }
SessionArtifacts.scrubTree(folder)
paths.forEach { path -> leaked.forEach { assertFalse(File(folder, path).readText().contains(it)) } }
assertSafe(zip(folder))
assertTrue(folder.walkTopDown().none { it.name.startsWith(".redacted-") })
}
@Test fun steamLogsAtTheSizeLimitStayOut() {
val folder = tmp.newFolder("2026-10-06-11-steam")
write(folder, "session.log")
val file = write(folder, "steam/console_log.txt")
RandomAccessFile(file, "rw").use { it.setLength(SessionLogFiles.STEAM_MAX_BYTES) }
val files = zip(folder)
assertFalse(files.containsKey("steam/console_log.txt"))
assertTrue(files.containsKey("omitted.txt"))
assertSafe(files)
}
@Test fun aGrowingFileIsLimitedToItsOpeningSnapshot() {
val folder = tmp.newFolder("2026-10-06-12-steam")
val file = write(folder, "session.log", "safe\n".repeat(2000) + "$secret\nunfinished")
val output = StringWriter()
var appended = false
val writer = object : Writer() {
override fun write(chars: CharArray, offset: Int, length: Int) {
if (!appended) { appended = true; file.appendText("appended-marker $secret\n") }
output.write(chars, offset, length)
}
override fun flush() = Unit
override fun close() = Unit
}
SessionLogFiles.scrubTo(folder, file, writer)
assertFalse(output.toString().contains("appended-marker"))
assertFalse(output.toString().contains("unfinished"))
assertTrue(output.toString().contains("<incomplete live line withheld>"))
leaked.forEach { assertFalse(output.toString().contains(it)) }
}
@Test fun aTruncatedFileFailsInsteadOfExportingAPartialSnapshot() {
val folder = tmp.newFolder("2026-10-06-13-steam")
val file = write(folder, "session.log", "safe\n".repeat(20000))
val writer = object : Writer() {
override fun write(chars: CharArray, offset: Int, length: Int) { file.writeText("") }
override fun flush() = Unit
override fun close() = Unit
}
assertThrows(java.io.IOException::class.java) { SessionLogFiles.scrubTo(folder, file, writer) }
}
@Test fun anOutputFailureDoesNotLeaveAShareableArchive() {
val folder = tmp.newFolder("2026-10-06-14-steam")
write(folder, "session.log")
assertThrows(IllegalStateException::class.java) {
SessionLogShare.zipFolder(context, folder) { throw IllegalStateException("failed output") }
}
val out = File(context.cacheDir, "shared-logs")
assertTrue(out.listFiles().orEmpty().isEmpty())
assertTrue(context.cacheDir.listFiles().orEmpty().none { it.name.startsWith("redacted-") })
val names = zip(folder).keys
assertTrue("steam/console_log.txt" in names)
assertFalse("steam/cef_log.previous.txt" in names)
}
}
@@ -1,138 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class SteamDownloadMonitorTest {
@Test fun reportsOnlyProgressingIncompleteManifests() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val steam = File(root, "root/.local/share/Steam")
val manifest = manifest(steam, "42", downloaded = 10, total = 100, flags = 6)
val monitor = SteamDownloadMonitor()
assertFalse(monitor.poll(root, now = 1_000L))
manifest.writeText(appManifest(downloaded = 20, total = 100, flags = 6))
assertTrue(monitor.poll(root, now = 3_000L))
assertTrue(monitor.poll(root, now = 9_000L))
assertFalse(monitor.poll(root, now = 11_001L))
} finally {
root.deleteRecursively()
}
}
@Test fun findsDownloadsInAdditionalSteamLibraries() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val library = File(root, "mnt/droiddeck-sd").apply { mkdirs() }
File(root, "root/.local/share/Steam/steamapps").apply { mkdirs() }
.resolve("libraryfolders.vdf")
.writeText("\"libraryfolders\" { \"1\" { \"path\" \"/mnt/droiddeck-sd\" } }")
val manifest = manifest(library, "43", downloaded = 1, total = 2, flags = 6)
val monitor = SteamDownloadMonitor()
assertFalse(monitor.poll(root, now = 1_000L))
manifest.writeText(appManifest(downloaded = 2, total = 2, flags = 4))
assertFalse(monitor.poll(root, now = 3_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun followsSteamContentActivityWhenManifestProgressIsNotFlushed() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val steam = File(root, "root/.local/share/Steam")
manifest(steam, "44", downloaded = 0, total = 10_000, flags = 10)
val contentLog = File(steam, "logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[2026-10-06 14:44:17] AppID 44 App update changed : Running Update,Downloading,Staging,\n")
}
val monitor = SteamDownloadMonitor()
assertTrue(monitor.poll(root, now = 1_000L))
assertTrue(monitor.poll(root, now = 90_000L))
assertFalse(monitor.poll(root, now = 91_001L))
contentLog.appendText("[2026-10-06 14:45:02] Current download rate: 27.178 Mbps\n")
assertTrue(monitor.poll(root, now = 92_000L))
contentLog.appendText("[2026-10-06 14:45:03] AppID 44 App update changed : None\n")
assertFalse(monitor.poll(root, now = 93_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun receivedTrafficBridgesSteamRateLines() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val contentLog = File(root, "root/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[2026-10-06 16:06:30] AppID 44 App update changed : Running Update,Downloading,\n")
}
val monitor = SteamDownloadMonitor()
var received = 1_000_000L
var now = 1_000L
assertTrue(monitor.poll(root, now, received))
// Five minutes of a download Steam no longer logs, at 4 MB/s.
while (now < 300_000L) {
now += 2_000L
received += 8_000_000L
assertTrue(monitor.poll(root, now, received))
}
// Traffic stops: the session may suspend once the grace runs out.
assertTrue(monitor.poll(root, now + 90_000L, received))
assertFalse(monitor.poll(root, now + 92_001L, received))
contentLog.appendText("[2026-10-06 16:12:00] AppID 44 App update changed : None\n")
assertFalse(monitor.poll(root, now + 94_000L, received + 8_000_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun trafficAloneIsNotADownload() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val monitor = SteamDownloadMonitor()
assertFalse(monitor.poll(root, now = 1_000L, receivedBytes = 0L))
assertFalse(monitor.poll(root, now = 3_000L, receivedBytes = 50_000_000L))
} finally {
root.deleteRecursively()
}
}
@Test fun newSteamSessionClearsStaleContentActivity() {
val root = Files.createTempDirectory("droiddeck-steam-download-").toFile()
try {
val log = File(root, "root/.local/share/Steam/logs/content_log.txt").apply {
check(parentFile?.mkdirs() != false)
writeText("[old] AppID 44 App update changed : Running Update,Downloading,\n")
appendText("[new] Client version: 1\n")
}
val monitor = SteamDownloadMonitor()
assertFalse(monitor.poll(root, now = 1_000L))
log.appendText("[new] AppID 44 App update changed : Running Update,Downloading,\n")
assertTrue(monitor.poll(root, now = 2_000L))
} finally {
root.deleteRecursively()
}
}
private fun manifest(root: File, appId: String, downloaded: Long, total: Long, flags: Int): File {
val file = File(root, "steamapps/appmanifest_$appId.acf")
check(file.parentFile?.mkdirs() != false)
file.writeText(appManifest(downloaded, total, flags))
return file
}
private fun appManifest(downloaded: Long, total: Long, flags: Int) =
"\"AppState\" { \"StateFlags\" \"$flags\" \"BytesDownloaded\" \"$downloaded\" \"BytesToDownload\" \"$total\" }"
}
+1 -3
View File
@@ -28,7 +28,7 @@ tools/droiddeckctl start desktop
tools/droiddeckctl run /usr/bin/foo -- arg1 arg2
tools/droiddeckctl stop
tools/droiddeckctl resume
tools/droiddeckctl logs latest ./session-logs.zip
tools/droiddeckctl logs latest ./session-artifacts
tools/droiddeckctl screenshot ./screen.png
```
@@ -39,5 +39,3 @@ Every command writes JSON to stdout and reports its resolved ADB serial to stder
The `state` response uses schema 1 and includes the build label, runtime version, session ID and phase, mode, requested program, suspend and first-frame state, output size, guest PID, failure details, and artifact paths. Phases are `IDLE`, `PREPARING`, `INSTALLING_RUNTIME`, `STARTING_COMPOSITOR`, `STARTING_GUEST`, `STARTING_STEAM`, `READY`, `SUSPENDED`, `STOPPING`, and `FAILED`. Each session also writes `events.jsonl` alongside its existing artifacts.
`tools/deploy_local.sh` uses the same device resolver. If multiple distinct devices are connected, select one with `ADB_SERIAL` or `ANDROID_SERIAL`.
`logs latest` exports the same sanitized ZIP as Share logs. Working logs stay in app-private storage; the command retrieves the ZIP through `run-as` on debug builds.
-89
View File
@@ -1,89 +0,0 @@
# Steam session focus: how it works and how to debug it
Written 2026-10-07 after the "game opens behind Steam" reports (Skyrim SE, A Plague Tale:
Innocence, Burnout Paradise Remastered), fixed by gamescope patch 0114 (#401). It records what a
game needs to get focus in a Steam session and how to inspect a live session on a device, for the
next report that looks like this.
## How a game gets focus
The Steam session runs two Xwayland servers, as SteamOS does: the client on `:0`, games on `:1`
(`--xwayland-count 2`, `STEAM_MULTIPLE_XWAYLANDS=1` in `droiddeck-session`). Focus is decided in
three steps, and a window can drop out at each one:
1. **gamescope lists candidates.** For each server it collects windows that are mapped, of class
InputOutput, not fully transparent (`_NET_WM_WINDOW_OPACITY` above 0), not an overlay, and
carry an app id (`STEAM_GAME`). It publishes them on `:0`'s root as `GAMESCOPE_FOCUSABLE_APPS`
and `GAMESCOPE_FOCUSABLE_WINDOWS` (window, app id, pid triples). It leaves out of that published
list any window it believes is override-redirect, 1x1, or skip-taskbar-and-pager without
fullscreen.
2. **Steam picks an order.** The client reads those lists and writes
`GAMESCOPECTRL_BASELAYER_APPID`, for example `413091, 489830, 769`. When the running game has
no window in the focusable list, Steam puts itself (769) ahead of it.
3. **gamescope follows Steam.** The virtual connector strategy in a Steam session is
SteamControlled: the first app id in the base layer with a candidate window wins.
gamescope works from its own cached copy of each window's attributes, not from X. A window that X
shows mapped and tagged can still be missing in step 1 if that cache is stale.
## What the bug looked like
- On screen: Steam's black loading screen with only **ABORT GAME**, the game audible underneath.
Resume from the Steam menu does not help.
- `GAMESCOPE_FOCUSED_APP` stays `769`; `GAMESCOPECTRL_BASELAYER_APPID` has `769` ahead of the
game's app id; the game's window is missing from `GAMESCOPE_FOCUSABLE_WINDOWS`.
- On `:1` the game window is mapped, `WM_STATE` Normal, `STEAM_GAME` set, with no opacity,
`_NET_WM_STATE` or overlay properties.
- gamescope's `focus_info` shows server 1's own focus on the game while the global focus is Steam.
Cause: wine creates the game's window override-redirect and makes it managed before mapping it,
which sends no X event. gamescope read the attributes when the window was created and refreshed
`override_redirect` only from ConfigureNotify, so when its read came before wine's change it kept
the window as override-redirect and left it out of the list Steam reads. It is a race: Skyrim
failed about once in six launches on the Thor, on the first launch after a session start. Upstream
fixed it by taking the flag from MapNotify (ValveSoftware/gamescope 3829340, our patch 0114).
The launcher and the game both had window id `0x1c00003` on `:1`: with few clients on that server
the X server hands the game the launcher's freed id. That was not the cause (the game window came
7 s after the launcher's was destroyed), but it makes logs easy to misread.
## Inspecting a live session from adb
Everything below runs on the device as the app's uid (`su 10195` on the Thor, `u0_a195`), using
the rootfs's own binaries through its loader, so nothing has to enter proot:
```sh
R=/data/user/0/com.droiddeck.launcher/files/linuxfs
$R/usr/lib/ld-linux-aarch64.so.1 --library-path $R/usr/lib $R/usr/bin/xprop -display :0 -root \
GAMESCOPE_FOCUSED_APP GAMESCOPE_FOCUSABLE_WINDOWS GAMESCOPECTRL_BASELAYER_APPID
```
- The X servers answer on their **abstract** sockets (`\0/tmp/.X11-unix/X0`, `X1`); xprop finds
them by itself. The socket files under `linuxfs/tmp/.X11-unix` can be stale. Nothing answers
while the session is in the background or the screen is off (the session is stopped).
- The `VAR=… cmd` prefix does not survive `timeout` or `nohup`; put the command in a small
`/system/bin/sh` script in `/data/local/tmp` and run that.
- gamescope's focus state, written to the session's `session.log` (in
`Download/DroidDeck/<date>-NN-steam/`):
```sh
export XDG_RUNTIME_DIR=/data/user/0/com.droiddeck.launcher/files/.wayland-rt WAYLAND_DISPLAY=gamescope-0
G="$R/usr/lib/ld-linux-aarch64.so.1 --library-path $R/usr/lib $R/usr/bin/gamescopectl"
$G log_focus debug; $G focus_info
```
It prints the global focus, input, keyboard and override windows, the connector strategy, and
each server's own focus and keyboard focus. Disagreement between a server's focus and the
global one points at step 1 or 2 above.
- To tell a stale gamescope cache from a real X problem, make gamescope re-read the window: move it
by 1 px and back (ConfigureNotify), or unmap and map it (MapNotify). If the game comes forward,
gamescope's cache was wrong. A restack of a window already on top sends no event and proves
nothing.
- To test gamescope with a candidate binary without rebuilding the apk, put it in the rootfs (for
example `/opt/gstest/gamescope`, owned by the app's uid) and add
`PATH=/opt/gstest:/usr/local/bin:/usr/bin:/bin` to `Download/droiddeck-env`. The session log's
first lines name the gamescope that ran. Remove the line afterwards: the app stages its own
gamescope over `/usr/local/bin` at every session start.
- Never `pkill -f <pattern>` inside `su -c '…'`: the pattern matches that shell's own command line.
Killing `SkyrimSE.exe` that way took the whole session down. Kill by pid.
- Skyrim's menus take adb key events (`input keyevent 20` down, `66` enter); taps do nothing.
+1 -1
View File
@@ -220,7 +220,7 @@ cached() {
if [[ -f "${repo_root}/tools/gamescope/release.env" ]]; then
. "${repo_root}/tools/gamescope/release.env"
gamescope_archive=$(cached "${GAMESCOPE_SHA256}" gamescope.tzst \
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${GAMESCOPE_REPO:-${github_repo}}")
bash -c 'gh release download "$0" -R "$1" -p gamescope.tzst -O "$out"' "${GAMESCOPE_TAG}" "${github_repo}")
zstd -dc "${gamescope_archive}" | tar -xf - -C "${linuxfs_dir}"
test -f "${linuxfs_dir}/usr/local/bin/gamescope"
fi
+11 -14
View File
@@ -71,14 +71,14 @@ def _content_result(output: str) -> dict:
raise ControlError("Could not decode the agent provider response", "INVALID_PROVIDER_RESPONSE") from exc
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None, timeout: int = 30) -> dict:
def provider_call(adb: str, serial: str, method: str, arg: str | None = None, request: dict | None = None) -> dict:
command = ["shell", "content", "call", "--uri", AUTHORITY, "--method", method]
if arg is not None:
command.extend(["--arg", arg])
if request is not None:
encoded = base64.b64encode(json.dumps(request, separators=(",", ":")).encode()).decode()
command.extend(["--extra", f"request:s:{encoded}"])
result = run_adb(adb, serial, *command, timeout=timeout)
result = run_adb(adb, serial, *command)
output = (result.stdout + result.stderr).decode(errors="replace")
response = _content_result(output)
if result.returncode != 0 and response.get("ok") is not False:
@@ -248,18 +248,15 @@ def execute(args: argparse.Namespace, adb: str, serial: str) -> dict:
if not session.get("running") and session.get("artifactsAvailable") and not session.get("artifactsComplete"):
state = wait_for_artifacts(adb, serial, state, args.timeout)
session = state.get("session", {})
response = provider_call(adb, serial, "logs", timeout=120)
if response.get("ok") is False:
error = response.get("error", {})
raise ControlError(error.get("message", "log export failed"), error.get("code", "LOG_EXPORT_FAILED"))
destination = Path(args.destination or f"{response['sessionId']}.zip").expanduser().resolve()
result = run_adb(adb, serial, "exec-out", "run-as", "com.droiddeck.launcher", "cat", response["path"], timeout=120)
remote_dir = session.get("logDir")
if not remote_dir or not session.get("id") or not session.get("artifactsAvailable"):
raise ControlError("No session artifact directory is available", "NO_SESSION_LOGS")
destination = Path(args.destination or session["id"]).expanduser().resolve()
result = run_adb(adb, serial, "pull", remote_dir, str(destination), timeout=120)
if result.returncode != 0:
detail = result.stderr.decode(errors="replace").strip()
raise ControlError(detail or "log export failed", "LOG_PULL_FAILED")
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(result.stdout)
return add_serial({"ok": True, "command": "logs", "sessionId": response["sessionId"], "path": str(destination)}, serial)
detail = (result.stderr or result.stdout).decode(errors="replace").strip()
raise ControlError(detail or "adb pull failed", "LOG_PULL_FAILED")
return add_serial({"ok": True, "command": "logs", "sessionId": session["id"], "path": str(destination)}, serial)
if args.command == "screenshot":
destination = Path(args.path).expanduser().resolve()
@@ -305,7 +302,7 @@ def build_parser() -> argparse.ArgumentParser:
stop.add_argument("--timeout", type=float, default=90)
commands.add_parser("resume", help="resume a suspended session")
logs = commands.add_parser("logs", help="export sanitized session logs as a ZIP")
logs = commands.add_parser("logs", help="pull the latest session artifact directory")
logs.add_argument("which", choices=["latest"])
logs.add_argument("destination", nargs="?")
logs.add_argument("--timeout", type=float, default=90)
+8 -6
View File
@@ -38,12 +38,14 @@ library list, before anything is published.
iconify request is remembered and the window goes back to NormalState before input returns to it,
then focus is handed over again. `GAMESCOPE_RESTORE_FOCUS_WINDOW` on the root window asks for the
same restore from outside (the session script's resume watcher).
- `0114-take-override-redirect-from-mapnotify.patch` - upstream (ValveSoftware/gamescope 3829340),
verbatim; drop it once the runtime's gamescope includes it. Wine creates a game's window
override-redirect and makes it managed before mapping it, which sends no X event. When gamescope
read the window's attributes first, it kept the window as override-redirect and left it out of
`GAMESCOPE_FOCUSABLE_WINDOWS`, so the client kept its loading screen over the running game
(Skyrim SE, A Plague Tale: Innocence, on the games' own Xwayland). MapNotify now refreshes the flag.
- `0113-steam-overlay-keeps-game-keyboard-focus.patch` - this app: the Steam client opens the Quick
Access Menu and Steam menu over a game with `STEAM_INPUT_FOCUS` 1, which moves X keyboard focus to
its overlay; wine then deactivates the game and a fullscreen game minimizes itself, freezing
behind the menu instead of running on as on a Steam Deck. Steam's own overlay taking input now
keeps keyboard focus on the game, as mode 2 does; its input comes from the controller through
Steam Input, not the X keyboard. The pointer warps gamescope makes as input moves to Steam and
back are skipped around it, since the game - still taking input - saw them as a mouse jump.
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
@@ -0,0 +1,104 @@
From: DroidDeck
Subject: [PATCH] steamcompmgr: keep the game's keyboard focus under Steam's overlay
The Steam client opens its Quick Access Menu and Steam menu over a game by setting
STEAM_OVERLAY 1 and STEAM_INPUT_FOCUS 1 on its window. Mode 1 moves X keyboard focus to the
overlay, so the game's window gets FocusOut: wine moves the foreground to the desktop, a fullscreen
game deactivates and minimizes itself (WM_CHANGE_STATE IconicState), and it stops rendering behind
the menu - frozen, all threads asleep, until the menu closes (Alan Wake's American Nightmare,
Proton Experimental ARM64). On a Steam Deck the game runs on behind the menu.
Mode 2 already means "input to the overlay, keyboard focus stays on the focus window". Treat
Steam's own overlay taking input in mode 1 the same way at the three places mode 2 is honoured.
The overlay's input does not need X keyboard focus: the controller drives it through Steam Input.
Measured by rewriting the property to 2 by hand: the game kept running behind the menu and the
controller still moved only the menu.
With the game keeping focus, the pointer resets gamescope makes when input moves to Steam (warp
to the centre, park in the corner) and back (warp to the centre) reached it as a sudden mouse
move: a mouse-look camera spun every time the menu opened and closed. Skip them while Steam's
overlay opens over a game that keeps focus, and as it closes - by then the overlay has dropped its
STEAM_INPUT_FOCUS, so whether the opening kept focus is remembered.
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 372a82c..3fab3c6 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -1321,6 +1321,22 @@ window_is_steam( steamcompmgr_win_t *w )
return w && ( w->isSteamLegacyBigPicture || w->appID == 769 );
}
+// Whether keyboard focus stays on the focus window while this window has input focus.
+// STEAM_INPUT_FOCUS 2 asks for that. The Steam client also opens its Quick Access Menu and Steam
+// menu over a game with 1, which moves X keyboard focus to the overlay: wine then deactivates the
+// game, a fullscreen game minimizes itself, and it froze behind the menu instead of running on as
+// on a Steam Deck. The overlay's own input does not need X keyboard focus (the controller drives
+// it through Steam Input), so Steam's overlay keeps the game's keyboard focus too.
+static bool
+window_keeps_game_keyboard_focus( steamcompmgr_win_t *w )
+{
+ if ( !w )
+ return false;
+ if ( w->inputFocusMode == 2 )
+ return true;
+ return w->inputFocusMode == 1 && w->isOverlay && window_is_steam( w );
+}
+
static bool
window_is_vr_scene_app( steamcompmgr_win_t *w )
{
@@ -4728,7 +4744,7 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
if ( gamescope::VirtualConnectorIsSingleOutput() )
{
- if ( inputFocus && inputFocus->inputFocusMode == 2 )
+ if ( window_keeps_game_keyboard_focus( inputFocus ) )
keyboardFocusWin = ctx->focus.focusWindow;
}
else
@@ -4834,12 +4850,26 @@ void xwayland_ctx_t::DetermineAndApplyFocus( const std::vector< steamcompmgr_win
if ( ctx->focus.inputFocusWindow != inputFocus ||
ctx->focus.inputFocusMode != inputFocus->inputFocusMode )
{
+ // Steam's overlay opening over a game, or closing again, while the game keeps keyboard focus
+ // (window_keeps_game_keyboard_focus): the game is still taking input, so a pointer warp
+ // reaches it as a sudden mouse move - the camera of a mouse-look game spun as the Quick
+ // Access Menu opened and as it closed. The overlay is driven by the controller and the
+ // cursor is hidden, so leave the pointer where it is. Closing, the overlay has already
+ // dropped its STEAM_INPUT_FOCUS, so whether the opening kept focus is remembered.
+ static bool s_bOverlayKeptGameFocus = false;
+ bool bOverlayKeepsGameFocus = window_keeps_game_keyboard_focus( inputFocus ) &&
+ ctx->focus.focusWindow && !window_is_steam( ctx->focus.focusWindow );
+ bool bSkipPointerReset = bOverlayKeepsGameFocus || s_bOverlayKeptGameFocus;
+ s_bOverlayKeptGameFocus = bOverlayKeepsGameFocus;
+
// If the window doesn't want focus when hidden, move it away
// as we are going to hide it straight after.
// otherwise, if we switch from wanting it to not
// (steam -> game)
// put us back in the centre of the screen.
- if (window_wants_no_focus_when_mouse_hidden(inputFocus))
+ if ( bSkipPointerReset )
+ ;
+ else if (window_wants_no_focus_when_mouse_hidden(inputFocus))
ctx->focus.bResetToCorner = true;
else if ( window_wants_no_focus_when_mouse_hidden(inputFocus) != window_wants_no_focus_when_mouse_hidden(ctx->focus.inputFocusWindow) )
ctx->focus.bResetToCenter = true;
@@ -5340,7 +5370,7 @@ determine_and_apply_focus( global_focus_t *pFocus )
pFocus->inputFocusMode = pFocus->inputFocusWindow->inputFocusMode;
if ( gamescope::VirtualConnectorIsSingleOutput() &&
- pFocus->inputFocusMode == 2 )
+ window_keeps_game_keyboard_focus( pFocus->inputFocusWindow ) )
{
pFocus->keyboardFocusWindow = pFocus->overrideWindow
? pFocus->overrideWindow
@@ -6485,7 +6515,7 @@ handle_wl_surface_id(xwayland_ctx_t *ctx, steamcompmgr_win_t *w, uint32_t surfac
steamcompmgr_win_t *keyboardFocusWindow = pCurrentFocus->inputFocusWindow;
if ( gamescope::VirtualConnectorIsSingleOutput() &&
- keyboardFocusWindow && keyboardFocusWindow->inputFocusMode == 2 )
+ window_keeps_game_keyboard_focus( keyboardFocusWindow ) )
keyboardFocusWindow = pCurrentFocus->focusWindow;
if ( w == keyboardFocusWindow )
@@ -1,35 +0,0 @@
From: Matthew Schwartz <matthew.schwartz@linux.dev>
Subject: [PATCH] steamcompmgr: take override-redirect from MapNotify
Wine creates a toplevel as override-redirect and flips it to managed with
XChangeWindowAttributes while it is unmapped, which generates no X event.
When add_win reads the attributes before the flip, the window stays cached
as override-redirect and is left out of GAMESCOPE_FOCUSABLE_APPS. Steam
then keeps its loading screen over the game, as with A Plague Tale:
Innocence (752590). Before 2238420d, the focus nudge's move usually
refreshed the flag.
MapNotify carries the current override-redirect state, so refresh the
cached flag there rather than re-reading the attributes.
Closes: #2457
---
src/steamcompmgr.cpp | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index f00b62c..cb3b9c6 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -8778,7 +8778,11 @@ void xwayland_ctx_t::Dispatch()
steamcompmgr_win_t * w = find_win(ctx, ev.xmap.window);
if (w && w->xwayland().id == ev.xmap.window)
+ {
+ // Wine flips override-redirect while unmapped and the flip itself sends no event.
+ w->xwayland().a.override_redirect = ev.xmap.override_redirect;
map_win(ctx, ev.xmap.window, ev.xmap.serial);
+ }
break;
}
case UnmapNotify:
+2 -3
View File
@@ -1,3 +1,2 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-p9
GAMESCOPE_SHA256=7123a37bdbcd0d76d4bd1d7490e5d2017221e036395fdd48c1e92458594ca769
GAMESCOPE_TAG=gamescope-3.16.29-p5
GAMESCOPE_SHA256=188144e5564e020d0bc485a1f4f90e1c5fd61d0d1d6dd29db21e8b019036a5c6
+1 -1
View File
@@ -92,7 +92,7 @@ find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'ke
# fontconfig's rules (sans-serif -> DejaVu Sans and the rest) live as links in /etc/fonts/conf.d,
# and the rootfs has none: applications then find fonts but no default font. Firefox logs
# "no fonts" and draws pages without text.
if [ -d /usr/share/fontconfig/conf.default ] && ! ls /etc/fonts/conf.d/*.conf 2>/dev/null | grep -qv droiddeck; then
if [ -d /usr/share/fontconfig/conf.default ] && ! ls /etc/fonts/conf.d/*.conf >/dev/null 2>&1; then
for f in /usr/share/fontconfig/conf.default/*.conf; do ln -sf "$f" /etc/fonts/conf.d/; done
echo "== fontconfig: linked $(ls /etc/fonts/conf.d/*.conf | wc -l) default rules"
fi
@@ -73,19 +73,11 @@ def client_entries():
return found
def registered():
try:
with open(os.path.join(STEAM_ROOT, "steamapps", "libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
return [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', f.read())]
except OSError:
return []
def write_entries():
os.makedirs(APPS_DIR, exist_ok=True)
wanted = {}
theirs = client_entries()
for library in dict.fromkeys([library for library, _ in LIBRARIES] + registered()):
for library, _ in LIBRARIES:
for appid, name in games(library):
if appid not in theirs:
wanted.setdefault(appid, name)
@@ -954,19 +954,8 @@ def choose(root, command, env, tool, stock):
return command, env
def libraries(steam_root):
found = [steam_root]
try:
with open(os.path.join(steam_root, "steamapps", "libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
found += [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', f.read())]
except OSError:
pass
found.append(SD_LIBRARY)
return list(dict.fromkeys(found))
def find_tools(steam_root):
candidates = [os.path.join(library, "steamapps", "common", name) for library in libraries(steam_root) for name in SOURCES]
candidates = [os.path.join(library, "steamapps", "common", name) for library in (steam_root, SD_LIBRARY) for name in SOURCES]
folder = os.path.join(steam_root, "compatibilitytools.d")
try:
names = sorted(os.listdir(folder))
@@ -72,7 +72,6 @@ cache="$steam_root/.droiddeck-game-scripts"
libraries="$steam_root"
for library in $LIBRARIES; do libraries="$libraries
$library"; done
libraries=$(printf '%s\n%s\n' "$libraries" "$(sed -n 's/^[[:space:]]*"path"[[:space:]]*"\(.*\)"[[:space:]]*$/\1/p' "$steam_root/steamapps/libraryfolders.vdf" 2>/dev/null)" | awk 'NF && !seen[$0]++')
sig=$(while IFS= read -r library; do ls -l --time-style=+%s "$library"/steamapps/appmanifest_*.acf 2>/dev/null; done <<<"$libraries" | cksum)
if [ "$(head -n 1 "$cache" 2>/dev/null)" != "$sig" ]; then
{
@@ -134,12 +133,9 @@ $(vcrt "$(date +%s)")"
# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a
# changed one as a new template and upgrades every prefix made from the old.
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
"$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] || continue
seeded=$(dirname "$reg")/.droiddeck-redists
legacy=$(dirname "$reg")/.bannerlator-redists
@@ -136,26 +136,6 @@ program_cores() {
}
if [ -z "${BL_INSIDE:-}" ]; then
device_fonts=/usr/local/share/fonts/android
if [ -d "$device_fonts" ] && [ -d /etc/fonts/conf.d ] && command -v fc-cache >/dev/null 2>&1; then
fonts_rules=$(
echo '<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"><fontconfig>'
for pair in "zh-cn=Noto Sans CJK SC" "zh-sg=Noto Sans CJK SC" "zh-tw=Noto Sans CJK TC" "zh-hk=Noto Sans CJK HK" \
"zh-mo=Noto Sans CJK HK" "ja=Noto Sans CJK JP" "ko=Noto Sans CJK KR" "th=Noto Sans Thai"; do
printf '<match target="pattern"><test name="lang" compare="contains"><string>%s</string></test><edit name="family" mode="prepend_first"><string>%s</string></edit></match>\n' \
"${pair%%=*}" "${pair#*=}"
done
echo '</fontconfig>'
)
fonts_conf=/etc/fonts/conf.d/66-droiddeck-device-fonts.conf
[ "$fonts_rules" = "$(cat "$fonts_conf" 2>/dev/null)" ] || printf '%s\n' "$fonts_rules" > "$fonts_conf"
fonts_seen=$(ls -lL "$device_fonts" 2>/dev/null | md5sum)
fonts_stamp=/var/cache/fontconfig/.droiddeck-android-fonts
if [ "$fonts_seen" != "$(cat "$fonts_stamp" 2>/dev/null)" ]; then
fc-cache -f "${device_fonts%/*}" >/dev/null 2>&1 && printf '%s\n' "$fonts_seen" > "$fonts_stamp"
echo "== fontconfig: indexed $(ls "$device_fonts" | wc -l) device fonts, zh falls back to $(fc-match -f '%{family[0]}' ':lang=zh-cn' 2>/dev/null)"
fi
fi
# The compositor may still be starting, and a socket left by an earlier session is not
# a compositor: probe until a connection succeeds.
for _ in $(seq 1 100); do
@@ -202,7 +182,8 @@ if [ -z "${BL_INSIDE:-}" ]; then
# Resolution never reaches its display (docs/development/steam-display-scaling.md). The client's
# overlay is also on another server than the game, so opening it no longer takes the game's X
# keyboard focus, which made games like FlatOut shrink their window.
# BL_XWAYLAND_COUNT=1 in Download/droiddeck-env goes back to one.
# The app sends BL_XWAYLAND_COUNT from Steam settings (Two Xwayland servers); 1 goes back to one,
# and a line in Download/droiddeck-env still wins.
if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then
args+=(--xwayland-count "${BL_XWAYLAND_COUNT:-2}")
export STEAM_MULTIPLE_XWAYLANDS=1
@@ -535,6 +516,26 @@ case $mode in
v=${v# }
echo "${v:-$2}"
}
# What gamescope had to choose from when focus moved, and again as late windows map:
# the apps and windows it counts as focusable (window, app id, pid; on the client's
# server, for every server), the one it picked, and the client's base-layer order; then
# each server's top-level windows with the app id they carry (STEAM_GAME) and their
# WM_STATE (droiddeck-xwindows). A game window that opens behind the client and never
# takes focus shows here as missing from the focusable list, or listed with no app id.
focus_snapshot() {
local d
echo "== focus state (after $1 at $2s):" \
$(xprop -root GAMESCOPE_FOCUSED_APP GAMESCOPE_FOCUSED_WINDOW GAMESCOPE_FOCUSABLE_APPS \
GAMESCOPE_FOCUSABLE_WINDOWS GAMESCOPECTRL_BASELAYER_APPID 2>/dev/null | sed 's/(CARDINAL)//' | tr '\n' ' ')
for d in $(bl_displays); do droiddeck-xwindows "$d" 2>/dev/null; done
}
focus_snapshots() {
local at=0 t
for t in 0 5 15 30; do
nap $((t - at)); at=$t
focus_snapshot "$1" "$t"
done
}
tmode= app=
xprop -spy -root STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP 2>/dev/null | while read -r line; do
case $line in
@@ -549,6 +550,7 @@ case $mode in
[ "$v" = "$app" ] && continue
app=$v
echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)"
focus_snapshots "$app" &
;;
esac
done
@@ -568,7 +570,7 @@ case $mode in
local d
[ -e "$compat_stamp" ] && [ "$((beat % 12))" -ne 0 ] || return 0
for d in "$steam_root/steamapps" "$steam_root/steamapps/common" "$steam_root/config" \
"$steam_root/compatibilitytools.d" /mnt/droiddeck-sd/steamapps /root/Games/*/steamapps; do
"$steam_root/compatibilitytools.d" /mnt/droiddeck-sd/steamapps; do
[ "$d" -nt "$compat_stamp" ] && return 0
done
return 1
@@ -839,13 +841,13 @@ BUSCONF
-cef-use-gl=angle -cef-use-angle=vulkan "$@"
rc=$?
echo "== steam exited rc=$rc"
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
collect_steam_logs
if [ -f "$HOME/.config/droiddeck/fex-wanted" ] && [ -x /usr/local/bin/droiddeck-fex ]; then
/usr/local/bin/droiddeck-fex status >/dev/null 2>&1 || true
fi
if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then
droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true
fi
if [ -f "$HOME/.bl-stop-requested" ]; then
rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once"
break
@@ -16,7 +16,6 @@ STATE = ".droiddeck-games.json"
WINNATIVE = ".winnative-steam/steamapps"
LIBRARY = "/mnt/droiddeck-sd"
LEGACY_LIBRARY = "/mnt/bannerlator-sd"
PARKED = ".droiddeck-parked"
BASE_ID = 76561197960265728
@@ -283,42 +282,6 @@ def update_not_started(text, steamapps, appid, installdir):
and not (steamapps / "downloading" / str(appid)).exists())
def libraries(steam_root):
try:
text = (Path(steam_root) / "steamapps/libraryfolders.vdf").read_text(errors="replace")
except OSError:
text = ""
paths = [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', text)]
return list(dict.fromkeys([Path(steam_root), Path(LIBRARY)] + [Path(path) for path in paths]))
def ours(manifest, appid):
try:
return re.search(rf'"installdir"\s*"DroidDeck-{appid}"', manifest.read_text(errors="replace")) is not None
except OSError:
return False
def unpark(steamapps):
for manifest in sorted((steamapps / PARKED).glob("appmanifest_*.acf")):
appid = manifest.stem.removeprefix("appmanifest_")
live = steamapps / manifest.name
if os.path.lexists(live):
manifest.unlink(missing_ok=True)
elif (steamapps / "common" / f"DroidDeck-{appid}").is_dir():
os.replace(manifest, live)
def park(steamapps):
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
manifest = steamapps / f"appmanifest_{appid}.acf"
if appid.isdigit() and target.is_symlink() and not target.exists() and manifest.is_file() and ours(manifest, appid):
(steamapps / PARKED).mkdir(exist_ok=True)
os.replace(manifest, steamapps / PARKED / manifest.name)
print(f"droiddeck-steam-games: {appid} is not here this session; its install is set aside until it is")
def seed_install(steam_root, game, appid):
steamapps = Path(steam_root) / "steamapps"
common = steamapps / "common"
@@ -342,7 +305,7 @@ def seed_install(steam_root, game, appid):
relink.unlink(missing_ok=True)
relink.symlink_to(source, target_is_directory=True)
os.replace(relink, target)
for root in libraries(steam_root):
for root in [Path(steam_root), Path(LIBRARY)]:
existing = root / "steamapps" / manifest.name
if existing.is_file():
if (existing == manifest and source.is_dir() and target.is_symlink()
@@ -380,11 +343,6 @@ def route(steam_root, acct, games):
if not all(isinstance(value, dict) for value in (owned, candidates, sources)):
owned, candidates, sources = {}, {}, {}
shortcuts, routes = [], {}
steamapps = Path(steam_root) / "steamapps"
try:
unpark(steamapps)
except OSError as error:
print(f"droiddeck-steam-games: set-aside installs not restored ({error})")
for game in games:
folder = game.get("folder", "")
appid = candidates.get(folder, candidates.get(legacy_path(folder)))
@@ -401,10 +359,6 @@ def route(steam_root, acct, games):
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
shortcuts.append(game)
try:
park(steamapps)
except OSError as error:
print(f"droiddeck-steam-games: missing installs not set aside ({error})")
save_json(Path(acct) / "config/.droiddeck-routes.json", routes)
return shortcuts, routes
@@ -5,7 +5,6 @@
# droiddeck-steam-library <steam root>
#
# Ported from WinNative's gamescope runtime (GPL-3.0).
import json
import os
import re
import sys
@@ -169,29 +168,6 @@ def relabel(steam_root, target, label):
print("droiddeck-steam-library: labelled %s in its own marker too" % target)
GAMES_DIR = "/root/Games/"
def wanted():
listing = os.environ.get("BL_STEAM_LIBRARIES")
if not listing:
return None
try:
with open(listing, encoding="utf-8") as f:
entries = json.load(f)
return [(str(e["path"]), str(e["label"]).replace('"', " ").replace("\\", " ")) for e in entries]
except (OSError, ValueError, KeyError, TypeError):
return None
def registered(steam_root):
try:
with open(os.path.join(steam_root, "steamapps", "libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
return re.findall(r'"path"\s+"([^"]*)"', f.read())
except OSError:
return []
def main():
steam_root = sys.argv[1]
for library in RETIRED:
@@ -199,19 +175,12 @@ def main():
for old, new in RENAMED:
rename(steam_root, old, new)
relabel(steam_root, steam_root, MAIN_LABEL)
libraries = wanted()
managed = libraries is not None
for library, label in libraries if managed else LIBRARIES:
for library, label in LIBRARIES:
if os.path.isdir(os.path.join(library, "steamapps")):
register(steam_root, library, label)
relabel(steam_root, library, label)
else:
forget(steam_root, library)
if managed:
keep = {library for library, _ in libraries}
for library in registered(steam_root):
if library not in keep and (library == LIBRARIES[0][0] or library.startswith(GAMES_DIR)):
forget(steam_root, library)
if __name__ == "__main__":
@@ -120,114 +120,6 @@ def shortcut(game, launch_options=""):
}
RECORD = ".droiddeck-shortcuts.json"
AWAY_LIMIT = 256
FIELDS = ("AppName", "Exe", "StartDir", "icon")
def unquoted(value):
return value.strip().strip('"') if isinstance(value, str) else ""
def read_record(path):
try:
with open(path, encoding="utf-8") as f:
record = json.load(f)
except (OSError, ValueError):
record = {}
if not isinstance(record, dict):
record = {}
games, away = record.get("games"), record.get("away")
return {
"games": {k: v for k, v in games.items() if isinstance(v, dict)} if isinstance(games, dict) else {},
"away": {k: v for k, v in away.items() if isinstance(v, dict) and isinstance(v.get("entry"), dict)} if isinstance(away, dict) else {},
}
def merge(fresh, current, state, seen):
state = state if isinstance(state, dict) else {}
rev = state.get("rev") if isinstance(state.get("rev"), int) else 0
if current is None:
return fresh, rev
base = state.get("app") if isinstance(state.get("app"), dict) else {field: current.get(field) for field in FIELDS}
before = state.get("steam") if isinstance(state.get("steam"), dict) else {"Exe": current.get("Exe")}
if unquoted(current.get("Exe")) != unquoted(before.get("Exe")):
rev += 1
entry = dict(current)
entry["appid"] = fresh["appid"]
exe = unquoted(fresh["Exe"])
if exe != unquoted(current.get("Exe")) and (exe != unquoted(base.get("Exe")) or seen == rev):
entry["Exe"], entry["StartDir"] = fresh["Exe"], fresh["StartDir"]
for field in ("AppName", "icon"):
if current.get(field) == base.get(field):
entry[field] = fresh[field]
tags = dict(current["tags"]) if isinstance(current.get("tags"), dict) else {}
if TAG not in tags.values():
slot = 0
while str(slot) in tags:
slot += 1
tags[str(slot)] = TAG
entry["tags"] = tags
for key, value in fresh.items():
entry.setdefault(key, value)
return entry, rev
def reconcile(existing, wanted, seen, record):
games, away = record["games"], dict(record["away"])
kept, ours, placed = [], [], {}
for value in existing.values():
if not isinstance(value, dict):
continue
tags = value.get("tags")
if not isinstance(tags, dict) or TAG not in tags.values():
kept.append(value)
continue
appid = value.get("appid")
if not isinstance(appid, int) or appid in placed:
continue
key = str(appid & 0xFFFFFFFF)
fresh = wanted.get(appid)
if fresh is None:
away.pop(key, None)
away[key] = {"entry": value, "state": games.get(key)}
continue
entry, rev = merge(fresh, value, games.get(key), seen.get(appid, 0))
placed[appid] = (len(ours), rev)
ours.append(entry)
for appid, fresh in wanted.items():
if appid in placed:
continue
key = str(appid & 0xFFFFFFFF)
stashed = away.get(key)
if stashed:
entry, rev = merge(fresh, stashed["entry"], stashed.get("state"), seen.get(appid, 0))
else:
entry, rev = merge(fresh, None, games.get(key), seen.get(appid, 0))
placed[appid] = (len(ours), rev)
ours.append(entry)
for appid in placed:
away.pop(str(appid & 0xFFFFFFFF), None)
while len(away) > AWAY_LIMIT:
away.pop(next(iter(away)))
state = {}
for appid, (index, rev) in placed.items():
entry = ours[index]
state[str(appid & 0xFFFFFFFF)] = {
"app": {field: wanted[appid][field] for field in FIELDS},
"steam": {"Exe": entry.get("Exe", ""), "StartDir": entry.get("StartDir", "")},
"rev": rev,
}
return kept, ours, {"games": state, "away": away}
def save_record(path, record):
tmp = path + ".droiddeck"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(record, f)
os.replace(tmp, path)
ART_MANIFEST = ".droiddeck-art.json"
# listing key -> the client's grid file suffix: <appid>p = portrait capsule, <appid> = header,
# <appid>_hero, <appid>_logo.
@@ -316,21 +208,27 @@ def main():
routing = importlib.util.module_from_spec(spec)
loader.exec_module(routing)
games, routes = routing.route(steam_root, acct, games)
wanted, seen = {}, {}
# Steam saves Big Picture's per-shortcut launch options in shortcuts.vdf. Keep them when
# refreshing our entries, keyed by the appid that stays stable across session starts.
managed = {
v.get("appid"): v for v in existing.values()
if isinstance(v, dict) and TAG in (v.get("tags") or {}).values()
}
kept = [v for v in existing.values() if isinstance(v, dict) and TAG not in (v.get("tags") or {}).values()]
ours = []
for game in games:
if game.get("exe") and game.get("name"):
entry = shortcut(game)
if entry["appid"] not in wanted:
wanted[entry["appid"]] = entry
seen[entry["appid"]] = game["seen"] if isinstance(game.get("seen"), int) else 0
record_path = os.path.join(config, RECORD)
kept, ours, record = reconcile(existing, wanted, seen, read_record(record_path))
if not game.get("exe") or not game.get("name"):
continue
entry = shortcut(game)
previous = managed.get(entry["appid"])
if previous and isinstance(previous.get("LaunchOptions"), str):
entry["LaunchOptions"] = previous["LaunchOptions"]
ours.append(entry)
entries = {str(i): v for i, v in enumerate(kept + ours)}
tmp = path + ".droiddeck"
with open(tmp, "wb") as f:
f.write(write({"shortcuts": entries}))
os.replace(tmp, path)
save_record(record_path, record)
print("droiddeck-steam-shortcuts: %d added game(s) written, %d of the client's own kept" % (len(ours), len(kept)))
install_art(acct, [g for g in games if g.get("exe") and g.get("name")])
# Each added game runs under the ARM64 Proton: the compat registrar's own mapping writer.
@@ -1,10 +1,5 @@
#!/usr/bin/python3
"""Initialize Steam's own Gamescope display settings once; subsequent choices belong to Steam.
The UI scale, and native resolution: the client treats our gamescope as an external display and,
unless "Enable Native Resolution on External Displays" is on, draws itself at 1920x1080 on any
larger output - a 2340x1080 session came up as 16:9 with bars. The session's size is already the
user's Resolution choice, so the client should use all of it."""
"""Initialize Steam's own Gamescope UI scale once; subsequent choices belong to Steam."""
import math
import os
from pathlib import Path
@@ -14,7 +9,6 @@ import tempfile
DISPLAY = "External: gamescope|||Windowed"
NATIVE_RESOLUTION = "EnableSteamNativeExternalResolution"
TOKEN = re.compile(r'\s+|//[^\n]*|"(?:\\.|[^"\\])*"|[{}]')
@@ -108,25 +102,6 @@ def seed_text(text, scale):
return text[:at] + insertion + text[at:], True
def seed_native_resolution(text):
root = parse(text).get('InstallConfigStore')
if not isinstance(root, Block):
raise ValueError("missing InstallConfigStore")
gamescope = root.get('Gamescope')
if gamescope is not None and not isinstance(gamescope, Block):
raise ValueError("invalid Gamescope settings")
if gamescope is not None and gamescope.get(NATIVE_RESOLUTION) is not None:
return text, False
entry = f'"{NATIVE_RESOLUTION}" "1"'
if gamescope is not None:
at, indent = gamescope.end, 2
else:
entry = '"Gamescope"\n{\n' + entry + '\n}'
at, indent = root.end, 1
insertion = '\n' + '\n'.join('\t' * indent + line for line in entry.splitlines()) + '\n'
return text[:at] + insertion + text[at:], True
def atomic_write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
@@ -153,30 +128,9 @@ def initialize(steam_root, width, height):
return changed
def initialize_native_resolution(steam_root):
config = Path(steam_root) / 'config/config.vdf'
marker = config.with_name('droiddeck-native-resolution-initialized')
if marker.exists():
return False
text = config.read_text() if config.exists() else '"InstallConfigStore"\n{\n}\n'
updated, changed = seed_native_resolution(text)
if changed:
atomic_write(config, updated)
print('== steam: native resolution on the session display')
atomic_write(marker, '1\n')
return changed
if __name__ == '__main__':
status = 0
try:
initialize(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
except (OSError, ValueError, RecursionError) as error:
print('== steam: left UI scale unchanged: ' + str(error), file=sys.stderr)
status = 1
try:
initialize_native_resolution(sys.argv[1])
except (OSError, ValueError, RecursionError) as error:
print('== steam: left native resolution unchanged: ' + str(error), file=sys.stderr)
status = 1
sys.exit(status)
sys.exit(1)
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/python3
# The top-level windows of one Xwayland server, one line each, for the session log: what gamescope
# had to pick focus from. Each line has the window, whether it is mapped, override-redirect, its
# geometry, the app id it carries (STEAM_GAME, which gamescope focuses by), its WM_STATE, pid and
# class. Then whatever is set of what else gamescope weighs before it counts a mapped window as
# focusable: an InputOnly class, _NET_WM_WINDOW_OPACITY (0 is never focusable), STEAM_OVERLAY,
# GAMESCOPE_EXTERNAL_OVERLAY, STEAM_INPUT_FOCUS and _NET_WM_STATE (skip taskbar and pager without
# fullscreen is left out of the focusable list the client reads). Windows that are neither mapped
# nor tagged with an app id are left out - wine keeps many hidden ones. The rootfs has xprop but no xwininfo, so this speaks the X protocol itself.
#
# droiddeck-xwindows :1
import os
import socket
import struct
import sys
MAP_STATE = ("unmapped", "unviewable", "viewable")
WM_STATES = {0: "Withdrawn", 1: "Normal", 3: "Iconic"}
class X:
def __init__(self, display):
num = display.lstrip(":").split(".")[0]
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.s.settimeout(2)
self.s.connect("/tmp/.X11-unix/X" + num)
self.s.sendall(struct.pack("<BxHHHHxx", 0x6C, 11, 0, 0, 0))
head = self.read(8)
if head[0] != 1:
raise OSError("X connection refused")
setup = self.read(struct.unpack_from("<H", head, 6)[0] * 4)
vendor_len = struct.unpack_from("<H", setup, 16)[0]
formats = setup[21]
self.root = struct.unpack_from("<I", setup, 32 + (vendor_len + 3) // 4 * 4 + formats * 8)[0]
def read(self, n):
buf = b""
while len(buf) < n:
chunk = self.s.recv(n - len(buf))
if not chunk:
raise OSError("X connection closed")
buf += chunk
return buf
def request(self, data):
"""Send one request and return its reply, or None for an X error (a window that went)."""
self.s.sendall(data)
while True:
head = self.read(32)
if head[0] == 0:
return None
if head[0] == 1:
return head + self.read(struct.unpack_from("<I", head, 4)[0] * 4)
# an event; none are selected, but skip anything that arrives
def atom(self, name):
n = name.encode()
pad = (4 - len(n) % 4) % 4
r = self.request(struct.pack("<BBHHxx", 16, 1, 2 + (len(n) + pad) // 4, len(n)) + n + b"\0" * pad)
return struct.unpack_from("<I", r, 8)[0] if r else 0
def children(self, win):
r = self.request(struct.pack("<BxHI", 15, 2, win))
if not r:
return []
n = struct.unpack_from("<H", r, 16)[0]
return list(struct.unpack_from("<%dI" % n, r, 32))
def attributes(self, win):
r = self.request(struct.pack("<BxHI", 3, 2, win))
return (r[26], r[27], struct.unpack_from("<H", r, 12)[0]) if r else None
def atom_name(self, atom):
r = self.request(struct.pack("<BxHI", 17, 2, atom))
if not r:
return str(atom)
return r[32:32 + struct.unpack_from("<H", r, 8)[0]].decode(errors="replace")
def geometry(self, win):
r = self.request(struct.pack("<BxHI", 14, 2, win))
return struct.unpack_from("<hhHH", r, 12) if r else None
def prop(self, win, atom):
if not atom:
return None
r = self.request(struct.pack("<BBHIIIII", 20, 0, 6, win, atom, 0, 0, 64))
if not r or r[1] == 0:
return None
fmt, n = r[1], struct.unpack_from("<I", r, 16)[0]
data = r[32:32 + n * fmt // 8]
if fmt == 32:
return list(struct.unpack("<%dI" % n, data))
return data
def main():
display = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("DISPLAY", ":0")
try:
x = X(display)
except OSError as e:
print("== %s: %s" % (display, e))
return
atoms = {name: x.atom(name) for name in (
"STEAM_GAME", "WM_STATE", "_NET_WM_PID", "WM_CLASS", "_NET_WM_WINDOW_OPACITY", "STEAM_OVERLAY",
"GAMESCOPE_EXTERNAL_OVERLAY", "STEAM_INPUT_FOCUS", "_NET_WM_STATE")}
for win in x.children(x.root):
attrs = x.attributes(win)
if not attrs:
continue
game = x.prop(win, atoms["STEAM_GAME"])
if attrs[0] != 2 and not game:
continue
geo = x.geometry(win)
state = x.prop(win, atoms["WM_STATE"])
pid = x.prop(win, atoms["_NET_WM_PID"])
cls = x.prop(win, atoms["WM_CLASS"])
extra = []
if attrs[2] == 2:
extra.append("InputOnly")
for label, name in (("opacity", "_NET_WM_WINDOW_OPACITY"), ("overlay", "STEAM_OVERLAY"),
("external-overlay", "GAMESCOPE_EXTERNAL_OVERLAY"),
("input-focus", "STEAM_INPUT_FOCUS")):
value = x.prop(win, atoms[name])
if value:
extra.append("%s 0x%x" % (label, value[0]) if label == "opacity" else "%s %d" % (label, value[0]))
net_state = x.prop(win, atoms["_NET_WM_STATE"])
if net_state:
extra.append("net-state " + ",".join(
x.atom_name(a).replace("_NET_WM_STATE_", "") for a in net_state))
print("== %s window 0x%x: %s%s %s app %s state %s pid %s class %s" % (
display, win, MAP_STATE[attrs[0]] if attrs[0] < 3 else attrs[0],
" override-redirect" if attrs[1] else "",
"%dx%d+%d+%d" % (geo[2], geo[3], geo[0], geo[1]) if geo else "?",
game[0] if game else "-",
WM_STATES.get(state[0], state[0]) if state else "-",
pid[0] if pid else "-",
cls.split(b"\0")[-2].decode(errors="replace") if cls and b"\0" in cls else "-",
) + "".join(" " + e for e in extra))
main()
@@ -277,10 +277,9 @@ done
# The depot this tool is named after, newest across the libraries that hold it; the others in the
# list stand in only when it is missing.
depot=
libraries=$(printf '%%s\\n' "$steam_root" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$steam_root/steamapps/libraryfolders.vdf" 2>/dev/null)
for name in %s; do
best=0
while IFS= read -r library; do
for library in "$steam_root" /mnt/droiddeck-sd; do
candidate="$library/steamapps/common/$name"
[ -d "$candidate/files/bin-arm64" ] && [ -x "$candidate/proton" ] || continue
build=0
@@ -290,7 +289,7 @@ for name in %s; do
depot=$candidate
best=$build
fi
done <<< "$libraries"
done
[ -n "$depot" ] && break
done
if [ -n "$depot" ]; then
@@ -616,21 +615,10 @@ NOT_GAMES = frozenset((
))
def libraries(steam_root):
found = [steam_root]
try:
with open(os.path.join(steam_root, "steamapps", "libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
found += [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', f.read())]
except OSError:
pass
found.append(LIBRARY + "-sd")
return list(dict.fromkeys(found))
def installed_apps(steam_root):
"""App ids of the titles the client has installed, tools and runtimes excluded."""
apps = set()
for library in libraries(steam_root):
for library in (steam_root, LIBRARY + "-sd"):
steamapps = os.path.join(library, "steamapps")
try:
names = os.listdir(steamapps)
@@ -790,7 +778,7 @@ def fex_missing(steam_root):
missing = []
for app in FEX_DEPENDENCIES:
if not any(os.path.isfile(os.path.join(library, "steamapps", "appmanifest_%s.acf" % app))
for library in libraries(steam_root)):
for library in (steam_root, LIBRARY + "-sd")):
missing.append(app)
return missing
@@ -1077,7 +1065,7 @@ def depot_build(depot):
def find_source(steam_root, sources=SOURCES):
"""The first of `sources` the client has downloaded, newest across the libraries holding it."""
for name in sources:
found = [os.path.join(root, "steamapps", "common", name) for root in libraries(steam_root)
found = [os.path.join(root, "steamapps", "common", name) for root in (steam_root, "/mnt/droiddeck-sd")
if os.path.isdir(os.path.join(root, "steamapps", "common", name, "files", "bin-arm64"))]
if found:
return max(found, key=depot_build)
+12 -63
View File
@@ -1,6 +1,8 @@
/*
* Opt-in observations for file allocation and writes to the selected Steam library.
*
* Steam's allocation failure and any later fallback are left entirely to the caller. These
* wrappers only forward the same arguments, record the result and restore errno after logging.
* The session enables them only when storage diagnostics are turned on. Counters are local to
* each process, allocation details are capped, writes are sampled, and storage.log has a global
* size limit because every Steam child shares it.
@@ -152,56 +154,19 @@ static void allocation_line(const char *api, int result, int error, int flags,
if (n > 0 && (size_t)n < sizeof(line)) append_line(line, (size_t)n);
}
static int steam_client(void) {
static int cached = -1;
if (cached < 0)
cached = strcmp(program_invocation_short_name, "steam") == 0 &&
strstr(program_invocation_name, "steamrtarm64") != NULL;
return cached;
}
static int staging_file(int fd) {
char link[32], path[PATH_MAX];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
long n = syscall(SYS_readlinkat, (long)AT_FDCWD, (long)link, (long)path, (long)sizeof(path) - 1);
if (n <= 0) return 0;
path[n] = '\0';
return strstr(path, "/steamapps/downloading/") != NULL;
}
static long long unreserved[16];
static unsigned int unreserved_count;
static int cannot_reserve(long long device) {
unsigned int n = __atomic_load_n(&unreserved_count, __ATOMIC_ACQUIRE);
for (unsigned int i = 0; i < n && i < 16; i++)
if (__atomic_load_n(&unreserved[i], __ATOMIC_RELAXED) == device) return 1;
return 0;
}
static void note_cannot_reserve(int fd) {
struct stat st;
if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat");
if (next_fstat == NULL || next_fstat(fd, &st) != 0 || cannot_reserve((long long)st.st_dev)) return;
unsigned int slot = __atomic_load_n(&unreserved_count, __ATOMIC_RELAXED);
while (slot < 16 && !__atomic_compare_exchange_n(&unreserved_count, &slot, slot + 1, 0, __ATOMIC_ACQ_REL,
__ATOMIC_RELAXED)) {
}
if (slot < 16) __atomic_store_n(&unreserved[slot], (long long)st.st_dev, __ATOMIC_RELEASE);
}
int fallocate(int fd, int mode, off_t offset, off_t length) {
int entry_errno = errno;
if (next_fallocate == NULL) next_fallocate = dlsym(RTLD_NEXT, "fallocate");
if (next_fallocate == NULL) { errno = ENOSYS; return -1; }
int selected = on_selected_device(fd, NULL);
errno = entry_errno;
uint64_t start = selected ? now_ns() : 0;
if (!selected) return next_fallocate(fd, mode, offset, length);
uint64_t start = now_ns();
errno = entry_errno;
int result = next_fallocate(fd, mode, offset, length);
int call_errno = errno;
if (result != 0 && (call_errno == EOPNOTSUPP || call_errno == ENOSYS) && steam_client()) note_cannot_reserve(fd);
if (selected) allocation_line("fallocate", result, call_errno, mode, offset, length, now_ns() - start);
uint64_t elapsed = now_ns() - start;
allocation_line("fallocate", result, call_errno, mode, offset, length, elapsed);
errno = call_errno;
return result;
}
@@ -257,28 +222,12 @@ int ftruncate(int fd, off_t length) {
if (next_ftruncate == NULL) next_ftruncate = dlsym(RTLD_NEXT, "ftruncate");
if (next_ftruncate == NULL) { errno = ENOSYS; return -1; }
int selected = on_selected_device(fd, NULL);
uint64_t start = selected ? now_ns() : 0;
struct stat st;
int known = 0;
if (steam_client()) {
if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat");
known = next_fstat != NULL && next_fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && staging_file(fd);
}
int result = 0, call_errno = entry_errno;
if (!known || length <= st.st_size || !cannot_reserve((long long)st.st_dev)) {
errno = entry_errno;
result = next_ftruncate(fd, length);
call_errno = errno;
if (result != 0 && known && length >= st.st_size && (call_errno == EPERM || call_errno == EOPNOTSUPP)) {
if (length > st.st_size) note_cannot_reserve(fd);
result = 0;
call_errno = entry_errno;
}
}
if (!selected) {
errno = call_errno;
return result;
}
errno = entry_errno;
if (!selected) return next_ftruncate(fd, length);
uint64_t start = now_ns();
errno = entry_errno;
int result = next_ftruncate(fd, length);
int call_errno = errno;
uint64_t elapsed = now_ns() - start;
add(&stats.ftruncate_calls, 1);
if (result != 0) add(&stats.ftruncate_failures, 1);
-51
View File
@@ -1,51 +0,0 @@
import argparse
import importlib.machinery
import importlib.util
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
loader = importlib.machinery.SourceFileLoader("droiddeckctl", str(TOOLS / "droiddeckctl"))
spec = importlib.util.spec_from_loader(loader.name, loader)
ctl = importlib.util.module_from_spec(spec)
loader.exec_module(ctl)
class LogExportTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.destination = Path(self.tmp.name) / "session.zip"
self.args = argparse.Namespace(command="logs", timeout=90, destination=str(self.destination))
self.state = {"session": {"running": True, "id": "session1", "artifactsAvailable": True}}
def test_logs_fetch_only_the_provider_sanitized_zip(self):
response = {"ok": True, "sessionId": "session1", "path": "/data/user/0/com.droiddeck.launcher/cache/shared-logs/session.zip"}
result = subprocess.CompletedProcess([], 0, b"sanitized ZIP", b"")
with patch.object(ctl, "get_state", return_value=self.state), patch.object(ctl, "provider_call", return_value=response) as provider, patch.object(ctl, "run_adb", return_value=result) as adb:
output = ctl.execute(self.args, "adb", "device")
provider.assert_called_once_with("adb", "device", "logs", timeout=120)
adb.assert_called_once_with("adb", "device", "exec-out", "run-as", "com.droiddeck.launcher", "cat", response["path"], timeout=120)
self.assertEqual(b"sanitized ZIP", self.destination.read_bytes())
self.assertEqual(str(self.destination.resolve()), output["path"])
def test_export_failure_never_falls_back_to_pulling_raw_logs(self):
response = {"ok": False, "error": {"code": "NO_SESSION_LOGS", "message": "unavailable"}}
with patch.object(ctl, "get_state", return_value=self.state), patch.object(ctl, "provider_call", return_value=response), patch.object(ctl, "run_adb") as adb:
with self.assertRaises(ctl.ControlError):
ctl.execute(self.args, "adb", "device")
adb.assert_not_called()
self.assertFalse(self.destination.exists())
def test_failed_retrieval_does_not_write_a_partial_zip(self):
response = {"ok": True, "sessionId": "session1", "path": "/private/session.zip"}
result = subprocess.CompletedProcess([], 1, b"partial data", b"read failure")
with patch.object(ctl, "get_state", return_value=self.state), patch.object(ctl, "provider_call", return_value=response), patch.object(ctl, "run_adb", return_value=result):
with self.assertRaises(ctl.ControlError):
ctl.execute(self.args, "adb", "device")
self.assertFalse(self.destination.exists())
-40
View File
@@ -1,7 +1,6 @@
import importlib.machinery
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import tempfile
@@ -232,45 +231,6 @@ class ImportsTest(unittest.TestCase):
self.folder.rmdir()
self.assertEqual(([self.game], {}), imports.route(self.steam, self.acct, [self.game]))
def test_absent_folder_sets_its_install_aside_until_it_returns(self):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
manifest = self.steam / 'steamapps/appmanifest_42.acf'
manifest.write_text(manifest.read_text().replace('}', ' "buildid" "99"\n}'))
state = manifest.read_text()
away = self.root / 'unplugged'
self.folder.rename(away)
with patch('builtins.print'):
self.assertEqual(([], {}), imports.route(self.steam, self.acct, []))
self.assertFalse(manifest.exists())
self.assertEqual(state, (self.steam / 'steamapps' / imports.PARKED / manifest.name).read_text())
away.rename(self.folder)
self.assertEqual(([], {str(self.game['appid']): 42}), imports.route(self.steam, self.acct, [self.game]))
self.assertEqual(state, manifest.read_text())
self.assertFalse((self.steam / 'steamapps' / imports.PARKED / manifest.name).exists())
def test_steam_installs_are_never_set_aside(self):
manifest = self.steam / 'steamapps/appmanifest_42.acf'
manifest.parent.mkdir(parents=True)
manifest.write_text('"AppState"\n{\n "appid" "42"\n "installdir" "Example"\n}\n')
link = self.steam / 'steamapps/common/DroidDeck-42'
link.parent.mkdir(parents=True)
link.symlink_to(self.root / 'missing', target_is_directory=True)
imports.route(self.steam, self.acct, [])
self.assertTrue(manifest.is_file())
def test_install_in_another_library_is_used_as_is(self):
other = self.root / 'Games/PC'
(other / 'steamapps').mkdir(parents=True)
(other / 'steamapps/appmanifest_42.acf').write_text('Steam installed it here')
vdf = self.steam / 'steamapps/libraryfolders.vdf'
vdf.parent.mkdir(parents=True)
vdf.write_text('"libraryfolders"\n{\n\t"1"\n\t{\n\t\t"path"\t\t"%s"\n\t}\n}\n' % other)
self.snapshot()
self.assertEqual(([], {str(self.game['appid']): 42}), imports.route(self.steam, self.acct, [self.game]))
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
self.assertFalse(os.path.lexists(self.steam / 'steamapps/common/DroidDeck-42'))
def test_replaced_game_does_not_inherit_cached_ownership(self):
self.snapshot()
self.exe.write_bytes(b'a different game')
-152
View File
@@ -1,152 +0,0 @@
import importlib.machinery
import importlib.util
import json
import os
import re
import runpy
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
def load(name):
loader = importlib.machinery.SourceFileLoader(name.replace("-", "_"), str(BIN / name))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
library = load("droiddeck-steam-library")
desktop = load("droiddeck-desktop-games")
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
def entry(index, path, label=""):
return '\t"%d"\n\t{\n\t\t"path"\t\t"%s"\n\t\t"label"\t\t"%s"\n\t}\n' % (index, path, label)
def manifest(steamapps, appid, name="Game", installdir="Game", flags="4"):
steamapps.mkdir(parents=True, exist_ok=True)
(steamapps / ("appmanifest_%s.acf" % appid)).write_text(
'"AppState"\n{\n\t"appid"\t\t"%s"\n\t"name"\t\t"%s"\n\t"StateFlags"\t\t"%s"\n\t"installdir"\t\t"%s"\n}\n'
% (appid, name, flags, installdir))
class LibraryListTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / "Steam"
self.vdf = self.steam / "steamapps/libraryfolders.vdf"
self.vdf.parent.mkdir(parents=True)
self.games = self.root / "Games"
self.card = self.root / "card"
self.pc = self.games / "PC"
self.old = self.games / "Old"
self.user = self.root / "user-library"
for folder in (self.pc, self.old, self.user, self.card):
(folder / "steamapps").mkdir(parents=True)
manifest(self.pc / "steamapps", 10)
self.vdf.write_text('"libraryfolders"\n{\n' + entry(0, self.steam) + entry(1, self.old, "Old")
+ entry(2, self.user, "Mine") + entry(3, self.card, "SD Card") + "}\n")
self.listing = self.root / "steam-libraries.json"
for target in (patch.object(library, "GAMES_DIR", str(self.games) + "/"),
patch.object(library, "LIBRARIES", ((str(self.card), "SD Card"),)),
patch("builtins.print")):
target.start()
self.addCleanup(target.stop)
def run_main(self, listing=True):
with patch.dict(os.environ), patch("sys.argv", ["droiddeck-steam-library", str(self.steam)]):
os.environ.pop("BL_STEAM_LIBRARIES", None)
if listing:
os.environ["BL_STEAM_LIBRARIES"] = str(self.listing)
library.main()
return self.vdf.read_text()
def paths(self, text):
return [Path(p) for p in re.findall(r'"path"\s+"([^"]*)"', text)]
def test_listed_games_folder_is_registered_and_the_rest_are_forgotten(self):
self.listing.write_text(json.dumps([{"path": str(self.pc), "label": "PC (PNY USB drive)"}]))
text = self.run_main()
self.assertEqual([self.steam, self.user, self.pc], self.paths(text))
self.assertIn('"label"\t\t"PC (PNY USB drive)"', text)
self.assertIn('"10"\t\t"0"', text)
self.assertIn('"label"\t\t"PC (PNY USB drive)"', (self.pc / "libraryfolder.vdf").read_text())
def test_absent_listed_folder_is_forgotten_and_comes_back(self):
self.listing.write_text(json.dumps([{"path": str(self.pc), "label": "PC"}, {"path": str(self.card), "label": "SD Card"}]))
self.run_main()
moved = self.root / "unplugged"
self.pc.rename(moved)
self.assertNotIn(self.pc, self.paths(self.run_main()))
moved.rename(self.pc)
self.assertIn(self.pc, self.paths(self.run_main()))
self.assertIn(self.card, self.paths(self.vdf.read_text()))
def test_without_a_list_only_the_card_is_managed(self):
text = self.run_main(listing=False)
self.assertEqual([self.steam, self.old, self.user, self.card], self.paths(text))
def test_unreadable_list_keeps_games_folder_entries(self):
self.listing.write_text("{not json")
text = self.run_main()
self.assertEqual([self.steam, self.old, self.user, self.card], self.paths(text))
def test_labels_cannot_break_the_vdf(self):
self.listing.write_text(json.dumps([{"path": str(self.pc), "label": 'P"C\\'}]))
text = self.run_main()
self.assertIn('"label"\t\t"P C "', text)
class CompatLibrariesTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.steam = self.root / "Steam"
self.pc = self.root / "Games/My PC"
(self.steam / "steamapps").mkdir(parents=True)
(self.steam / "steamapps/libraryfolders.vdf").write_text(
'"libraryfolders"\n{\n' + entry(0, self.steam) + entry(1, self.pc, "PC") + "}\n")
def test_titles_and_tools_in_a_registered_library_are_found(self):
manifest(self.steam / "steamapps", 20)
manifest(self.pc / "steamapps", 30)
manifest(self.pc / "steamapps", 3127680, installdir="FEX")
self.assertEqual(["20", "30"], COMPAT["installed_apps"](str(self.steam)))
self.assertEqual(["1628350"], COMPAT["fex_missing"](str(self.steam)))
def test_newest_proton_across_libraries_wins(self):
for root, build in ((self.steam, "100"), (self.pc, "200")):
depot = root / "steamapps/common/Proton Experimental (ARM64)"
(depot / "files/bin-arm64").mkdir(parents=True)
(depot / "version").write_text(build + " x\n")
self.assertEqual(str(self.pc / "steamapps/common/Proton Experimental (ARM64)"), COMPAT["find_source"](str(self.steam)))
def test_missing_list_still_reads_the_client_library(self):
(self.steam / "steamapps/libraryfolders.vdf").unlink()
self.assertEqual(str(self.steam), COMPAT["libraries"](str(self.steam))[0])
class DesktopGamesTest(unittest.TestCase):
def test_games_in_registered_libraries_get_entries(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
steam, pc = root / "Steam", root / "Games/PC"
manifest(steam / "steamapps", 40, name="Internal")
manifest(pc / "steamapps", 50, name="Outside")
(steam / "steamapps/libraryfolders.vdf").write_text('"libraryfolders"\n{\n' + entry(0, steam) + entry(1, pc) + "}\n")
with patch.object(desktop, "STEAM_ROOT", str(steam)), patch.object(desktop, "APPS_DIR", str(root / "apps")), \
patch.object(desktop, "LIBRARIES", ((str(steam), "Steam Games"), (str(root / "card"), "SD Games"))):
self.assertEqual({40: "Internal", 50: "Outside"}, desktop.write_entries())
if __name__ == "__main__":
unittest.main()
-169
View File
@@ -1,169 +0,0 @@
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
def load(name):
loader = importlib.machinery.SourceFileLoader(name, str(BIN / name))
spec = importlib.util.spec_from_loader(name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
shortcuts = load('droiddeck-steam-shortcuts')
APPID = 0x87654321
GUEST = '/root/Games/PC/Example'
class ShortcutsTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.steam = self.root / 'Steam'
self.config = self.steam / 'userdata/123/config'
self.config.mkdir(parents=True)
self.listing = self.root / 'added-games.json'
def game(self, exe='Example.exe', seen=0, appid=APPID, name='Example'):
path = GUEST + '/' + exe
return dict(name=name, exe=path, folder=GUEST, dir=path.rsplit('/', 1)[0], appid=appid, seen=seen)
def run_writer(self, *games):
self.listing.write_text(json.dumps(list(games)))
subprocess.run(['python3', str(BIN / 'droiddeck-steam-shortcuts'), str(self.steam), str(self.listing)],
check=True, capture_output=True)
return self.entries()
def entries(self):
data = shortcuts.parse((self.config / 'shortcuts.vdf').read_bytes())['shortcuts']
return {value['appid'] & 0xFFFFFFFF: value for value in data.values()}
def steam_edits(self, appid=APPID, **fields):
path = self.config / 'shortcuts.vdf'
data = shortcuts.parse(path.read_bytes())['shortcuts']
for value in data.values():
if value['appid'] & 0xFFFFFFFF == appid:
value.update(fields)
path.write_bytes(shortcuts.write({'shortcuts': data}))
def record(self):
return json.loads((self.config / shortcuts.RECORD).read_text())
def test_settings_changed_in_steam_survive_its_restart(self):
self.run_writer(self.game())
edits = dict(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s"' % GUEST, LaunchOptions='DXVK_HUD=1 %command%',
AppName='Example GOTY', icon='/root/custom.png', IsHidden=1, AllowOverlay=0, LastPlayTime=1791372037,
sortas='example', tags={'0': shortcuts.TAG, '1': 'Favorites'})
self.steam_edits(**edits)
entry = self.run_writer(self.game())[APPID]
for field, value in edits.items():
self.assertEqual(value, entry[field], field)
entry = self.run_writer(self.game())[APPID]
for field, value in edits.items():
self.assertEqual(value, entry[field], field)
def test_steam_edit_is_recorded_for_the_app(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST)
self.run_writer(self.game())
state = self.record()['games'][str(APPID)]
self.assertEqual('"%s/Example.exe"' % GUEST, state['app']['Exe'])
self.assertEqual('"%s/bin/Other.exe"' % GUEST, state['steam']['Exe'])
self.assertEqual(1, state['rev'])
self.run_writer(self.game())
self.assertEqual(1, self.record()['games'][str(APPID)]['rev'])
def test_the_app_taking_steams_target_keeps_steams_start_in(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, StartDir='"%s/data"' % GUEST)
self.run_writer(self.game())
entry = self.run_writer(self.game('bin/Other.exe', seen=1))[APPID]
self.assertEqual('"%s/bin/Other.exe"' % GUEST, entry['Exe'])
self.assertEqual('"%s/data"' % GUEST, entry['StartDir'])
def test_an_exe_chosen_in_the_app_replaces_steams_target(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, LaunchOptions='-windowed')
self.run_writer(self.game())
entry = self.run_writer(self.game('tools/Launcher.exe'))[APPID]
self.assertEqual('"%s/tools/Launcher.exe"' % GUEST, entry['Exe'])
self.assertEqual('"%s/tools"' % GUEST, entry['StartDir'])
self.assertEqual('-windowed', entry['LaunchOptions'])
def test_going_back_to_the_apps_exe_after_taking_steams_wins(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST)
self.run_writer(self.game())
entry = self.run_writer(self.game(seen=1))[APPID]
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
self.assertEqual('"%s"' % GUEST, entry['StartDir'])
def test_a_later_steam_edit_is_kept_until_the_app_takes_it(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST)
self.run_writer(self.game())
self.run_writer(self.game(seen=1))
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST)
entry = self.run_writer(self.game(seen=1))[APPID]
self.assertEqual('"%s/bin/Other.exe"' % GUEST, entry['Exe'])
self.assertEqual(2, self.record()['games'][str(APPID)]['rev'])
def test_a_game_that_goes_away_comes_back_with_its_settings(self):
self.run_writer(self.game())
self.steam_edits(Exe='"%s/bin/Other.exe"' % GUEST, LaunchOptions='-dx11', LastPlayTime=1791372037)
self.assertEqual({}, self.run_writer())
self.assertIn(str(APPID), self.record()['away'])
entry = self.run_writer(self.game())[APPID]
self.assertEqual('"%s/bin/Other.exe"' % GUEST, entry['Exe'])
self.assertEqual('-dx11', entry['LaunchOptions'])
self.assertEqual(1791372037, entry['LastPlayTime'])
self.assertEqual({}, self.record()['away'])
def test_first_run_keeps_steams_own_fields_and_writes_the_apps_paths(self):
old = dict(shortcuts.shortcut(self.game('Old.exe')), LaunchOptions='-novid', LastPlayTime=5, sortas='x')
mine = dict(shortcuts.shortcut(dict(self.game(appid=0x81111111), name='Mine')), tags={'0': 'Personal'})
(self.config / 'shortcuts.vdf').write_bytes(shortcuts.write({'shortcuts': {'0': mine, '1': old}}))
entries = self.run_writer(self.game())
entry = entries[APPID]
self.assertEqual('"%s/Example.exe"' % GUEST, entry['Exe'])
self.assertEqual('-novid', entry['LaunchOptions'])
self.assertEqual(5, entry['LastPlayTime'])
self.assertEqual('x', entry['sortas'])
self.assertEqual(mine, entries[0x81111111])
def test_a_missing_tag_is_put_back_without_losing_steams(self):
self.run_writer(self.game())
self.steam_edits(tags={'1': 'Favorites', '0': shortcuts.TAG})
entry = self.run_writer(self.game())[APPID]
self.assertEqual({'1': 'Favorites', '0': shortcuts.TAG}, entry['tags'])
self.assertEqual({'0': shortcuts.TAG}, shortcuts.merge(shortcuts.shortcut(self.game()), dict(shortcuts.shortcut(self.game()), tags={}), None, 0)[0]['tags'])
def test_a_damaged_record_is_started_over(self):
self.run_writer(self.game())
(self.config / shortcuts.RECORD).write_text('{not json')
self.steam_edits(LaunchOptions='-safe')
entry = self.run_writer(self.game())[APPID]
self.assertEqual('-safe', entry['LaunchOptions'])
self.assertIn(str(APPID), self.record()['games'])
def test_games_set_aside_are_bounded(self):
many = [self.game(appid=0x80000000 + n, name='Game %d' % n) for n in range(shortcuts.AWAY_LIMIT + 4)]
self.run_writer(*many)
self.run_writer()
away = self.record()['away']
self.assertEqual(shortcuts.AWAY_LIMIT, len(away))
self.assertNotIn(str(0x80000000), away)
self.assertIn(str(0x80000000 + shortcuts.AWAY_LIMIT + 3), away)
if __name__ == '__main__':
unittest.main()
-55
View File
@@ -11,9 +11,6 @@ seed_text = MODULE['seed_text']
parse = MODULE['parse']
initial_scale = MODULE['initial_scale']
DISPLAY = MODULE['DISPLAY']
seed_native_resolution = MODULE['seed_native_resolution']
initialize_native_resolution = MODULE['initialize_native_resolution']
NATIVE_RESOLUTION = MODULE['NATIVE_RESOLUTION']
class SteamUiScaleTest(unittest.TestCase):
@@ -99,55 +96,3 @@ class SteamUiScaleTest(unittest.TestCase):
initialize(self.root, 0, 720)
self.assertFalse(self.config.exists())
self.assertFalse(self.marker.exists())
class SteamNativeResolutionTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.config = self.root / 'config/config.vdf'
self.config.parent.mkdir()
self.marker = self.config.with_name('droiddeck-native-resolution-initialized')
def native(self, text):
return parse(text).get('InstallConfigStore').get('Gamescope').get(NATIVE_RESOLUTION)
def test_fresh_client_renders_at_the_session_size(self):
self.assertTrue(initialize_native_resolution(self.root))
self.assertEqual('1', self.native(self.config.read_text()))
self.assertTrue(self.marker.exists())
def test_existing_client_gets_it_once_beside_its_settings(self):
text = '"InstallConfigStore"\n{\n\t"Gamescope"\n\t{\n\t\t"HDREnabled"\t\t"1"\n\t}\n}\n'
self.config.write_text(text)
self.assertTrue(initialize_native_resolution(self.root))
updated = self.config.read_text()
self.assertEqual('1', self.native(updated))
self.assertEqual('1', parse(updated).get('InstallConfigStore').get('Gamescope').get('HDREnabled'))
def test_users_choice_is_kept(self):
text = f'"InstallConfigStore" {{ "Gamescope" {{ "{NATIVE_RESOLUTION}" "0" }} }}'
self.assertEqual((text, False), seed_native_resolution(text))
def test_turning_it_off_after_initialization_survives_restart(self):
initialize_native_resolution(self.root)
text = self.config.read_text().replace('"1"', '"0"')
self.config.write_text(text)
self.assertFalse(initialize_native_resolution(self.root))
self.assertEqual(text, self.config.read_text())
def test_ui_scale_and_native_resolution_seed_the_same_config(self):
initialize(self.root, 2340, 1080)
initialize_native_resolution(self.root)
text = self.config.read_text()
self.assertEqual('1', self.native(text))
self.assertIsNotNone(parse(text).get('InstallConfigStore').get('UI').get('display').get(DISPLAY))
def test_invalid_config_is_never_rewritten_or_marked_initialized(self):
for text in ('"InstallConfigStore" {', '"InstallConfigStore" { "Gamescope" "bad" }'):
self.config.write_text(text)
with self.assertRaises(ValueError):
initialize_native_resolution(self.root)
self.assertEqual(text, self.config.read_text())
self.assertFalse(self.marker.exists())
-149
View File
@@ -1,149 +0,0 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
FAKE = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <unistd.h>
static void path_of(int fd, char *out, size_t size) {
char link[32];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
long n = syscall(SYS_readlinkat, AT_FDCWD, link, out, size - 1);
out[n > 0 ? n : 0] = '\0';
}
int fallocate(int fd, int mode, off_t offset, off_t length) {
(void)fd; (void)mode; (void)offset; (void)length;
errno = EOPNOTSUPP;
return -1;
}
int ftruncate(int fd, off_t length) {
char path[4096];
path_of(fd, path, sizeof(path));
FILE *log = fopen(getenv("FAKE_LOG"), "a");
if (log) { fprintf(log, "%s %lld\n", strrchr(path, '/') + 1, (long long)length); fclose(log); }
if (strstr(path, "ntfs")) { errno = EPERM; return -1; }
return (int)syscall(SYS_ftruncate, fd, length);
}
"""
PROGRAM = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
for (int i = 1; i + 2 < argc; i += 3) {
int fd = open(argv[i + 1], O_RDWR | O_CREAT, 0644);
if (fd < 0) return 2;
long long length = atoll(argv[i + 2]);
int result;
errno = 0;
if (strcmp(argv[i], "fallocate") == 0) result = fallocate(fd, 0, 0, length);
else result = ftruncate(fd, length);
int error = result == 0 ? 0 : errno;
struct stat st;
fstat(fd, &st);
printf("%s %d %s %lld\n", argv[i], result, error ? strerrorname_np(error) : "-", (long long)st.st_size);
close(fd);
}
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc"), "needs a C compiler")
class StoragePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
(build / "fake.c").write_text(FAKE)
(build / "program.c").write_text(PROGRAM)
cls.storage = build / "storage.so"
cls.fake = build / "fake.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.storage), str(PRELOAD / "storage.c"), "-ldl"], check=True)
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.fake), str(build / "fake.c")], check=True)
cls.steam = cls.dir / "steamrtarm64/steam"
cls.steam.parent.mkdir()
subprocess.run(["cc", "-O2", "-o", str(cls.steam), str(build / "program.c")], check=True)
cls.other = build / "steamwebhelper"
shutil.copy(cls.steam, cls.other)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def setUp(self):
self.lib = Path(tempfile.mkdtemp(dir=self.dir))
self.staging = self.lib / "steamapps/downloading/252410"
self.staging.mkdir(parents=True)
self.log = self.lib / "ftruncate.log"
def run_program(self, *steps, program=None):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.storage, self.fake), FAKE_LOG=str(self.log))
env.pop("BL_STORAGE_DIAGNOSTICS", None)
args = [str(program or self.steam)]
for call, path, length in steps:
args += [call, str(path), str(length)]
result = subprocess.run(args, env=env, capture_output=True, text=True, check=True)
return result.stdout.splitlines()
def reached(self):
return self.log.read_text().splitlines() if self.log.exists() else []
def test_reservation_after_failed_fallocate_is_not_zero_filled(self):
data = self.staging / "data.pak"
out = self.run_program(("fallocate", data, 1 << 20), ("ftruncate", data, 1 << 20), ("ftruncate", data, 0))
self.assertEqual(["fallocate -1 EOPNOTSUPP 0", "ftruncate 0 - 0", "ftruncate 0 - 0"], out)
self.assertEqual(["data.pak 0"], self.reached())
def test_reservation_is_real_until_the_device_has_refused_one(self):
data = self.staging / "data.pak"
self.assertEqual(["ftruncate 0 - 4096"], self.run_program(("ftruncate", data, 4096)))
self.assertEqual(["data.pak 4096"], self.reached())
def test_refused_extension_is_reported_as_done_and_remembered(self):
first, second = self.staging / "ntfs-one", self.staging / "two"
out = self.run_program(("ftruncate", first, 8192), ("ftruncate", second, 8192))
self.assertEqual(["ftruncate 0 - 0", "ftruncate 0 - 0"], out)
self.assertEqual(["ntfs-one 8192"], self.reached())
def test_refused_shrink_keeps_its_error(self):
data = self.staging / "ntfs-data"
data.write_bytes(b"x" * 100)
self.assertEqual(["ftruncate -1 EPERM 100"], self.run_program(("ftruncate", data, 10)))
def test_files_outside_staging_are_untouched(self):
manifest = self.lib / "steamapps/ntfs-appmanifest.acf"
out = self.run_program(("fallocate", self.staging / "a", 4096), ("ftruncate", manifest, 4096))
self.assertEqual(["fallocate -1 EOPNOTSUPP 0", "ftruncate -1 EPERM 0"], out)
self.assertEqual(["ntfs-appmanifest.acf 4096"], self.reached())
def test_other_programs_are_untouched(self):
data = self.staging / "ntfs-data"
out = self.run_program(("fallocate", data, 4096), ("ftruncate", data, 4096), program=self.other)
self.assertEqual(["fallocate -1 EOPNOTSUPP 0", "ftruncate -1 EPERM 0"], out)
if __name__ == "__main__":
unittest.main()