Compare commits

...
Author SHA1 Message Date
The412Banner 6c75e17870 fix(prefs): a setting stored with the wrong type no longer stops DroidDeck from opening 2026-11-27 17:22:48 +00:00
MaxsTechReview cc63b40387 fix(input): a direct touch reaches the game when the finger lands (#3339)
A direct touch is forwarded on touch-down by default instead of on release; the saved long-press right click behaviour is unchanged for users who chose it. Short taps keep a 50 ms minimum press.
2026-11-27 12:07:10 -05:00
The412Banner 89ef2f1e90 fix(session): Steam starts without waiting for the added-games scan (#2734) 2026-11-27 10:30:41 -05:00
24 changed files with 587 additions and 50 deletions

No files matched your search

@@ -349,7 +349,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var gestureSettingsOpen by mutableStateOf(false)
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
private var steamImportAnswered: String? = null
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_NONE)
private var relativeMouseMode by mutableIntStateOf(0)
@Volatile private var appliedRelativeMouseMode: Int? = null
private val agentReadyListener: () -> Unit = {
@@ -235,6 +235,10 @@ object AgentPrefs {
if (e is AgentException) throw e
throw AgentException("INVALID_PREF", "The value is not a $type")
}
val stored = previous?.let(::typeOf)
if (type != "remove" && stored != null && stored != type) {
throw AgentException("INVALID_PREF", "$file/$key is stored as $stored; set it with type $stored, or remove it first")
}
if (!editor.commit()) throw AgentException("PREF_WRITE_FAILED", "Could not write $file/$key")
return JSONObject().put("file", file).put("key", key).put("type", type)
.put("previous", previous ?: JSONObject.NULL).put("value", prefs.all[key] ?: JSONObject.NULL)
@@ -247,6 +251,15 @@ object AgentPrefs {
return JSONObject().put("file", file).put("values", JSONObject(all.mapValues { it.value ?: JSONObject.NULL }))
}
private fun typeOf(value: Any): String = when (value) {
is Boolean -> "bool"
is Int -> "int"
is Long -> "long"
is Float -> "float"
is String -> "string"
else -> "string set"
}
private fun validateFile(file: String) {
if (!Regex("[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}").matches(file)) {
throw AgentException("INVALID_PREF", "Preference files must be simple names")
@@ -233,14 +233,14 @@ object AddedGames {
if (folder.name.lowercase() in steamInstalls || isSteamLibraryFolder(folder.name)) continue
if (folder.path in removed) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true)
timed(folder) { for (game in expand(folder, entries, reuse = true)) if (game.path !in removed) scanGame(context, game, out, reuse = true) }
}
}
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
scanGame(context, folder, out, single = entry, reuse = true)
timed(folder) { scanGame(context, folder, out, single = entry, reuse = true) }
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out, reuse = true)
@@ -250,6 +250,15 @@ object AddedGames {
return out.distinctBy { it.folder.canonicalPath }
}
private const val SLOW_FOLDER_MS = 1_000L
private inline fun timed(folder: File, block: () -> Unit) {
val began = android.os.SystemClock.elapsedRealtime()
block()
val took = android.os.SystemClock.elapsedRealtime() - began
if (took >= SLOW_FOLDER_MS) Log.i(TAG, "games: scanning ${folder.path} took ${took}ms")
}
fun single(context: Context, folderPath: String, reuse: Boolean = false): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
@@ -564,8 +573,10 @@ object AddedGames {
class Listed(val appId: Long, val name: String, val launchOptions: String)
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
fun listed(context: Context): List<Listed>? = runCatching {
val file = File(context.filesDir, "session/added-games.json")
val file = listingFile(context)
if (!file.isFile) return null
val entries = org.json.JSONArray(file.readText())
(0 until entries.length()).mapNotNull { i ->
@@ -575,7 +586,7 @@ object AddedGames {
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
val file = listingFile(context).apply { parentFile?.mkdirs() }
val json = StringBuilder("[")
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
@@ -596,10 +607,24 @@ object AddedGames {
if (games.isNotEmpty() || i > 0) json.append(',')
json.append(entry.toString())
}
file.writeText(json.append(']').toString())
val text = json.append(']').toString()
synchronized(listing) {
val partial = File(file.parentFile, file.name + ".part")
try {
partial.writeText(text)
java.nio.file.Files.move(partial.toPath(), file.toPath(),
java.nio.file.StandardCopyOption.ATOMIC_MOVE, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.io.IOException) {
Log.w(TAG, "games: listing not replaced: ${e.message}")
partial.delete()
if (!file.isFile) file.writeText(text)
}
}
return file
}
private val listing = Any()
private fun artGuestPath(context: Context, file: File): String? {
val files = context.filesDir.absolutePath
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
@@ -1,17 +1,31 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.os.SystemClock
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.concurrent.Callable
import java.util.concurrent.Executors
object AddedGamesPublisher {
private const val TAG = "AddedGamesPublisher"
private const val CLIENT_WAIT_MS = 600_000L
private const val POLL_MS = 1_000L
private const val RETRY_MS = 5_000L
@VisibleForTesting
@Volatile
internal var now = false
@VisibleForTesting
@Volatile
internal var live: (Context, List<AddedGames.Game>, (AddedGames.Game) -> Boolean) -> Boolean = SteamLiveShortcuts::sync
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
fun later(context: Context, live: () -> Unit = {}) {
@@ -23,10 +37,56 @@ object AddedGamesPublisher {
if (now) work.run() else worker.execute(work)
}
fun republish(context: Context) {
fun republish(context: Context): List<AddedGames.Game> {
val games = AddedGames.scan(context)
AddedGames.writeListing(context, games)
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(context)
val arch = SessionPrefs.activeSteamClientArch(context)
LibraryCache.save(context, Library.launchableGames(context, added = games, arch = arch), arch == "x86_64")
return games
}
fun sessionListing(context: Context): File {
val app = context.applicationContext
val started = AddedGames.listed(app)?.map { it.appId }?.toSet()
?: return AddedGames.writeListing(app, AddedGames.scan(app).also { log(it) })
val session = SessionState.sessionId
val work = Runnable {
try {
val began = SystemClock.elapsedRealtime()
val games = serial { republish(app) }
Log.i(TAG, "session refresh: ${games.size} game(s) in ${SystemClock.elapsedRealtime() - began} ms")
log(games)
val fresh = games.filter { (it.appId and 0xFFFFFFFFL) !in started }
if (fresh.isNotEmpty()) deliver(app, session, fresh)
} catch (e: Exception) {
Log.w(TAG, "session refresh: ${e.message}")
}
}
if (now) work.run() else Thread(work, "added-games-refresh").apply { priority = Thread.MIN_PRIORITY }.start()
return AddedGames.listingFile(app)
}
internal fun log(games: List<AddedGames.Game>) {
if (games.isNotEmpty()) Log.i(TAG, "added games: " + games.joinToString { "${it.name} (${it.exe.name})" })
}
private fun deliver(app: Context, session: String?, games: List<AddedGames.Game>) {
val until = SystemClock.uptimeMillis() + CLIENT_WAIT_MS
while (current(session)) {
val ready = SessionState.phase == SessionPhase.READY
if (ready && serial { !current(session) || (SessionState.phase == SessionPhase.READY && syncUnremoved(app, games)) }) return
if (now || SystemClock.uptimeMillis() >= until) return
Thread.sleep(if (ready) RETRY_MS else POLL_MS)
}
}
private fun current(session: String?): Boolean =
SessionState.running && !SessionState.stopRequested && SessionState.sessionId == session
private fun syncUnremoved(app: Context, games: List<AddedGames.Game>): Boolean {
val removed = SessionPrefs.removedAddedGames(app).toSet()
return live(app, games) { it.folder.path !in removed }
}
private fun <T> serial(block: () -> T): T = if (now) block() else worker.submit(Callable { block() }).get()
}
@@ -51,11 +51,12 @@ object GameExePicker {
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
for (f in entries) {
if (visited >= WALK_BUDGET) break@walk
if (isLink(f)) continue
if (f.isDirectory) {
val attrs = attributes(f) ?: continue
if (attrs.isSymbolicLink) continue
if (attrs.isDirectory) {
visited++
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
} else if (attrs.isRegularFile && f.name.endsWith(".exe", ignoreCase = true)) {
visited++
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
}
@@ -98,7 +99,9 @@ object GameExePicker {
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
}
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
private fun attributes(f: File): java.nio.file.attribute.BasicFileAttributes? = runCatching {
java.nio.file.Files.readAttributes(f.toPath(), java.nio.file.attribute.BasicFileAttributes::class.java, java.nio.file.LinkOption.NOFOLLOW_LINKS)
}.getOrNull()
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.MotionEvent
import kotlin.math.abs
@@ -22,8 +23,9 @@ class DirectTouchHold(
private var downY = 0f
private var downId = 0
private var delayMs = 0L
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK
private var holdBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_NONE
private var forwarded = false
private var forwardedAt = 0L
private var held = false
private var pressing = false
private var upX = 0f
@@ -125,8 +127,11 @@ class DirectTouchHold(
upX = event.x
upY = event.y
liftId = event.getPointerId(event.actionIndex)
liftPending = true
handler.postDelayed(lift, LIFT_MS)
val wait = MIN_PRESS_MS - (SystemClock.uptimeMillis() - forwardedAt)
if (wait > 0L) {
liftPending = true
handler.postDelayed(lift, wait)
} else lift.run()
}
MotionEvent.ACTION_CANCEL -> cancel()
}
@@ -136,9 +141,10 @@ class DirectTouchHold(
private fun forwardDown() {
touch.down(downId, downX, downY)
forwarded = true
forwardedAt = SystemClock.uptimeMillis()
}
private companion object {
const val LIFT_MS = 50L
const val MIN_PRESS_MS = 50L
}
}
@@ -15,7 +15,7 @@ data class TouchGestureConfig(
val longPressAction: String = ACTION_RIGHT_CLICK,
val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD,
val longPressDelay: Int = DEFAULT_DELAY_MS,
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val directHoldBehavior: String = MOUSE_BEHAVIOR_NONE,
val doubleTapEnabled: Boolean = true,
val doubleTapDelay: Int = DEFAULT_DELAY_MS,
val twoFingerDragEnabled: Boolean = true,
@@ -167,7 +167,7 @@ data class TouchGestureConfig(
),
longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS),
directHoldBehavior = normalizeDirectHoldBehavior(
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_CLICK)
obj.optString(KEY_DIRECT_HOLD_BEHAVIOR, MOUSE_BEHAVIOR_NONE)
),
doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true),
doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS),
@@ -24,7 +24,7 @@ internal object BuildWatermarkSetting {
file(context).readFully().decodeToString() != "off"
}
} catch (_: java.io.IOException) {
context.getSharedPreferences("session", Context.MODE_PRIVATE).getBoolean("buildWatermark", true)
TolerantPrefs.session(context).getBoolean("buildWatermark", true)
}
fun setEnabled(context: Context, on: Boolean) {
@@ -11,16 +11,15 @@ object EnhancedDiagnostics {
const val MANIFEST_FILE = "enhanced-diagnostics.json"
private const val TAG = "EnhancedDiagnostics"
private const val PREFS = "session"
private const val ARMED = "enhancedDiagnosticsNext"
private const val ACTIVE_RECORDS = "enhancedDiagnosticsActiveSessions"
private const val SCHEMA = 1
fun isArmed(context: Context): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ARMED, false)
TolerantPrefs.session(context).getBoolean(ARMED, false)
fun setArmed(context: Context, armed: Boolean): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(ARMED, armed).commit()
TolerantPrefs.session(context).edit().putBoolean(ARMED, armed).commit()
fun isActive(context: Context, folder: File?): Boolean = activeAt(context, folder) != null
@@ -84,7 +83,7 @@ object EnhancedDiagnostics {
if (!File(known).isDirectory) records.remove(known)
}
records.put(path, activatedAt)
return context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
return TolerantPrefs.session(context).edit()
.putString(ACTIVE_RECORDS, records.toString())
.putBoolean(ARMED, false)
.commit()
@@ -108,11 +107,11 @@ object EnhancedDiagnostics {
}
private fun records(context: Context): JSONObject {
val text = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(ACTIVE_RECORDS, null)
val text = TolerantPrefs.session(context).getString(ACTIVE_RECORDS, null)
return runCatching { JSONObject(text ?: "{}") }.getOrDefault(JSONObject())
}
private fun saveRecords(context: Context, records: JSONObject): Boolean =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
TolerantPrefs.session(context).edit()
.putString(ACTIVE_RECORDS, records.toString()).commit()
}
@@ -17,7 +17,7 @@ object OfflineMode {
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
private const val EVAL_TIMEOUT_MS = 10_000L
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
private fun prefs(context: Context) = TolerantPrefs.session(context)
private fun loginUsers(root: File) = File(root, "root/.local/share/Steam/config/loginusers.vdf")
@@ -42,7 +42,7 @@ object QuestExperimental {
fun initialize(context: Context) {
if (!isSupported()) return
val prefs = context.getSharedPreferences("session", Context.MODE_PRIVATE)
val prefs = TolerantPrefs.session(context)
val defaultsKey = if (isQuest2()) "quest2DefaultsV1" else "questDefaultsV1"
if (!prefs.getBoolean(defaultsKey, false)) {
prefs.edit()
@@ -48,7 +48,7 @@ object SessionPrefs {
fun backActionsOrder(inverted: Boolean): Int =
if (inverted) BACK_QAM_THEN_MENU else BACK_MENU_THEN_QAM
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
private fun prefs(context: Context) = TolerantPrefs.session(context)
val orientationOptions = listOf(
ActivityInfo.SCREEN_ORIENTATION_USER to R.string.setup_launcher_orientation_auto,
@@ -693,12 +693,14 @@ class SessionService : Service() {
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
}
if (steamHere || noSteamGame) {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
val listing = if (steamHere) SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGamesPublisher.sessionListing(this) } else {
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
com.droiddeck.launcher.frontend.AddedGamesPublisher.log(added)
SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
}
guest.add("DD_ADDED_GAMES=" + listing.path)
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
}
guest.add("DD_LAUNCH_DIR=" + sessionRoot.path)
// Proton builds up to 11.12 report X11 text fields under this name.
@@ -0,0 +1,36 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.content.SharedPreferences
internal class TolerantPrefs(private val base: SharedPreferences) : SharedPreferences by base {
override fun getString(key: String?, defValue: String?): String? =
read(key, defValue, { base.getString(key, defValue) }) { it }
override fun getStringSet(key: String?, defValues: MutableSet<String>?): MutableSet<String>? =
try { base.getStringSet(key, defValues) } catch (_: ClassCastException) { defValues }
override fun getInt(key: String?, defValue: Int): Int =
read(key, defValue, { base.getInt(key, defValue) }) { it.toIntOrNull() }
override fun getLong(key: String?, defValue: Long): Long =
read(key, defValue, { base.getLong(key, defValue) }) { it.toLongOrNull() }
override fun getFloat(key: String?, defValue: Float): Float =
read(key, defValue, { base.getFloat(key, defValue) }) { it.toFloatOrNull() }
override fun getBoolean(key: String?, defValue: Boolean): Boolean =
read(key, defValue, { base.getBoolean(key, defValue) }) { it.toBooleanStrictOrNull() }
private inline fun <T> read(key: String?, defValue: T, typed: () -> T, parse: (String) -> T?): T =
try {
typed()
} catch (_: ClassCastException) {
base.all[key]?.toString()?.let(parse) ?: defValue
}
companion object {
fun session(context: Context): SharedPreferences =
TolerantPrefs(context.getSharedPreferences("session", Context.MODE_PRIVATE))
}
}
@@ -19,25 +19,33 @@ object SteamLiveShortcuts {
private const val EVAL_TIMEOUT_MS = 20_000L
private const val THAW_WAIT_MS = 15_000L
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
if (wanted.isEmpty()) return true
if (!clientRunning()) return false
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL).put("launch", g.launchOptions))
val js = """
(async () => {
const want = ${list};
let added = 0;
let added = 0, missed = 0;
for (const w of want) {
if (await ${KNOWN}(w.appid, w.name, w.exe)) continue;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++;
if (await ${ADD}(w.name, w.exe, w.dir, true, ${JSONObject.quote(compatTool(context))}, w.launch)) added++; else missed++;
}
return added;
return JSON.stringify({ added, missed });
})()
""".trimIndent()
val result = evaluate(context, js) ?: return
Log.i(TAG, "live shortcuts: $result added")
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
return synced(evaluate(context, js))
}
internal fun synced(result: String?): Boolean {
val counts = result?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return false
val added = counts.optInt("added")
val missed = counts.optInt("missed")
Log.i(TAG, "live shortcuts: $added added" + if (missed > 0) ", $missed not added" else "")
if (added > 0) StoresState.logLine("Steam: $added shortcut(s) added to the running client")
return missed == 0
}
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
@@ -333,7 +333,7 @@ class DrawerActions(
val onInputSelection: (com.droiddeck.launcher.input.InputRole?) -> Unit = {},
val onGestureSettings: () -> Unit = {},
val touchActive: String = "",
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
val directHoldBehavior: String = MOUSE_BEHAVIOR_NONE,
val onDirectHoldBehavior: (String) -> Unit = {},
val onFexPreset: (String) -> Unit,
val onUpscaler: (Int) -> Unit = {},
@@ -333,6 +333,28 @@ class AgentSecurityTest {
assertFalse(error.message!!.contains("synthetic-private-value"))
}
@Test fun preferencesKeepTheTypeAStoredKeyHas() {
AgentAccess.setCommandsEnabled(context, true)
val session = context.getSharedPreferences("session", Context.MODE_PRIVATE)
session.edit().clear().putBoolean("gameDebugLogsEnabled", false).putString("testText", "first").commit()
val error = refused("INVALID_PREF") { AgentPrefs.set(context, "session", "gameDebugLogsEnabled", "string", "true") }
assertTrue(error.message!!.contains("bool"))
assertEquals(false, session.all["gameDebugLogsEnabled"])
refused("INVALID_PREF") { AgentPrefs.set(context, "session", "testText", "bool", "true") }
assertEquals("first", session.all["testText"])
assertEquals(true, AgentPrefs.set(context, "session", "gameDebugLogsEnabled", "bool", "true").get("value"))
assertEquals("second", AgentPrefs.set(context, "session", "testText", "string", "second").get("value"))
assertEquals("fresh", AgentPrefs.set(context, "session", "unsetKey", "string", "fresh").get("value"))
session.edit().putString("gameDebugLogsEnabled", "true").commit()
AgentPrefs.set(context, "session", "gameDebugLogsEnabled", "remove", null)
assertEquals(false, AgentPrefs.set(context, "session", "gameDebugLogsEnabled", "bool", "false").get("value"))
assertEquals(false, session.all["gameDebugLogsEnabled"])
session.edit().clear().commit()
}
@Test fun overrideRefusesLinksAndTraversalNames() {
AgentAccess.setCommandsEnabled(context, true)
for (name in listOf(".", "..", "../gamescope")) refused("INVALID_NAME") { AgentEnv.override(context, name) }
@@ -145,4 +145,15 @@ class AddedGamesCandidatesTest {
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
assertEquals("My Game [Repack]", AddedGames.scan(app).single().name)
}
@Test fun linksAndFoldersNamedLikeAnExeAreNotCandidates() {
val elsewhere = tmp.newFolder("Elsewhere")
exe(elsewhere, "Other.exe")
val game = tmp.newFolder("Linked")
exe(game, "bin/Linked.exe")
File(game, "Folder.exe").mkdirs()
java.nio.file.Files.createSymbolicLink(File(game, "other").toPath(), elsewhere.toPath())
java.nio.file.Files.createSymbolicLink(File(game, "Alias.exe").toPath(), File(elsewhere, "Other.exe").toPath())
assertEquals(listOf("bin/Linked.exe"), names(game))
}
}
@@ -0,0 +1,213 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.After
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
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 AddedGamesSessionListingTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@After fun restore() {
AddedGamesPublisher.now = false
AddedGamesPublisher.live = SteamLiveShortcuts::sync
SessionState.running = false
SessionState.stopRequested = false
SessionState.sessionId = null
SessionState.phase = SessionPhase.IDLE
}
private val stale = """[{"name":"Old","exe":"/root/Games/Old/Old.exe","folder":"/root/Games/Old","dir":"/root/Games/Old","appid":2147483649,"seen":0}]"""
private fun gamesFolder(vararg names: String): File {
val games = tmp.newFolder("PC")
for (n in names) File(games, "$n/$n.exe").apply { parentFile!!.mkdirs() }.writeText("game")
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, listOf(games.path))
return games
}
private fun session(phase: SessionPhase) {
SessionState.sessionId = "session-test"
SessionState.stopRequested = false
SessionState.phase = phase
SessionState.running = true
}
private fun until(what: String, check: () -> Boolean) {
val end = System.currentTimeMillis() + 30_000
while (!check()) {
assertTrue(what, System.currentTimeMillis() < end)
Thread.sleep(20)
}
}
private fun scanLock(): Any =
AddedGames::class.java.getDeclaredField("scanning").apply { isAccessible = true }.get(null)!!
private fun refreshes() = Thread.getAllStackTraces().keys.filter { it.name == "added-games-refresh" }
@Test fun aSessionStartsFromTheLastListingWhileTheLibraryScanHoldsTheLock() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val done = CountDownLatch(1)
var returned: File? = null
var seen = ""
synchronized(scanLock()) {
Thread {
returned = AddedGamesPublisher.sessionListing(app)
seen = listing.readText()
done.countDown()
}.start()
assertTrue("the session start waited for the library scan", done.await(5, TimeUnit.SECONDS))
}
assertEquals(listing.path, returned!!.path)
assertEquals(stale, seen)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
val fresh = listing.readText()
assertTrue(fresh.contains("\"Alpha\""))
assertFalse(fresh.contains("\"Old\""))
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aFirstSessionScansBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app)
listing.delete()
assertEquals(listing.path, AddedGamesPublisher.sessionListing(app).path)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
assertFalse(File(listing.parentFile, listing.name + ".part").exists())
}
@Test fun aListingThatCannotBeReplacedKeepsTheOldOne() {
val listing = AddedGames.listingFile(app).apply { parentFile?.mkdirs() }
listing.writeText("[]")
val blocked = File(listing.parentFile, listing.name + ".part").apply { mkdirs() }
gamesFolder("Alpha")
AddedGames.writeListing(app, AddedGames.scan(app))
assertEquals("[]", listing.readText())
assertFalse(blocked.exists())
}
@Test fun anUnreadableListingIsRescannedBeforeStarting() {
gamesFolder("Alpha")
AddedGamesPublisher.now = false
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText("[{\"name\":") }
AddedGamesPublisher.sessionListing(app)
assertTrue(listing.readText().contains("\"Alpha\""))
assertTrue(refreshes().isEmpty())
}
@Test fun aGameRemovedWhileTheClientStartsIsNotAddedToIt() {
val games = gamesFolder("Alpha", "Beta")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.STARTING_STEAM)
AddedGamesPublisher.sessionListing(app)
until("the refresh did not write the listing") { listing.readText().contains("\"Beta\"") }
SessionPrefs.setAddedGameRemoved(app, File(games, "Beta").path, true)
SessionState.phase = SessionPhase.READY
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), delivered.toList())
}
@Test fun aDeliveryTheClientRefusesIsRetriedUntilItIsTaken() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<List<String>>())
AddedGamesPublisher.live = { _, found, include -> attempts.add(found.filter(include).map { it.name }); attempts.size > 1 }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf(listOf("Alpha"), listOf("Alpha")), attempts.toList())
}
@Test fun anEndedSessionStopsTheRetries() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val attempts = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, _ -> attempts.addAll(found.map { it.name }); SessionState.running = false; false }
session(SessionPhase.READY)
AddedGamesPublisher.sessionListing(app)
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertEquals(listOf("Alpha"), attempts.toList())
}
@Test fun aDeliveryQueuedForAnEndedSessionIsNotSentToTheNextOne() {
gamesFolder("Alpha")
AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val delivered = Collections.synchronizedList(ArrayList<String>())
AddedGamesPublisher.live = { _, found, include -> delivered.addAll(found.filter(include).map { it.name }); true }
session(SessionPhase.READY)
val first = CountDownLatch(1)
val firstHeld = CountDownLatch(1)
val second = CountDownLatch(1)
val secondHeld = CountDownLatch(1)
AddedGamesPublisher.later(app) { firstHeld.countDown(); first.await() }
try {
assertTrue(firstHeld.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh did not wait for its scan") { refresh.state == Thread.State.WAITING }
AddedGamesPublisher.later(app) { secondHeld.countDown(); second.await() }
first.countDown()
assertTrue(secondHeld.await(30, TimeUnit.SECONDS))
until("the refresh did not queue its delivery") {
refresh.state == Thread.State.WAITING && refresh.stackTrace.any { it.methodName == "deliver" }
}
SessionState.sessionId = "session-next"
} finally {
first.countDown()
second.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(delivered.isEmpty())
}
@Test fun theRefreshWaitsForEarlierPublicationsBeforeWriting() {
gamesFolder("Alpha")
val listing = AddedGames.listingFile(app).apply { parentFile!!.mkdirs(); writeText(stale) }
val hold = CountDownLatch(1)
val holding = CountDownLatch(1)
AddedGamesPublisher.later(app) { holding.countDown(); hold.await() }
try {
assertTrue(holding.await(30, TimeUnit.SECONDS))
AddedGamesPublisher.sessionListing(app)
val refresh = refreshes().single()
until("the refresh neither finished nor waited") { refresh.state == Thread.State.WAITING || !refresh.isAlive }
assertTrue("the refresh wrote while an earlier publication was running", refresh.isAlive)
assertEquals(stale, listing.readText())
} finally {
hold.countDown()
}
refreshes().forEach { it.join(30_000) }
assertTrue(refreshes().isEmpty())
assertTrue(listing.readText().contains("\"Alpha\""))
}
}
@@ -29,7 +29,7 @@ class DirectTouchHoldTest {
override fun move(pointerId: Int, x: Float, y: Float) { touches += "move $pointerId at $x,$y" }
override fun up(pointerId: Int, x: Float, y: Float) { touches += "up $pointerId at $x,$y" }
override fun cancel() { touches += "cancel" }
}).also { it.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 500)) }
}).also { it.configure(TouchGestureConfig(longPressDelay = 500, directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)) }
@Test fun holdClicksRightWithoutTouchingTheGame() {
touch(MotionEvent.ACTION_DOWN)
@@ -87,18 +87,49 @@ class DirectTouchHoldTest {
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 44.0,30.0"), touches)
}
@Test fun stillHoldClicksRightWithTheDefaultConfig() {
@Test fun stillHoldStaysHeldWithTheDefaultConfig() {
hold.configure(TouchGestureConfig())
touch(MotionEvent.ACTION_DOWN)
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
advance(2000)
touch(MotionEvent.ACTION_MOVE)
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
assertTrue(buttons.isEmpty())
}
@Test fun aSavedRightClickChoiceIsKept() {
val saved = TouchGestureConfig.fromJson(
TouchGestureConfig(directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK).toJson())
assertEquals(TouchGestureConfig.MOUSE_BEHAVIOR_CLICK, saved.directHoldBehavior)
hold.configure(saved)
touch(MotionEvent.ACTION_DOWN)
advance(2000)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("true at 40.0,30.0", "false at 40.0,30.0"), buttons)
assertTrue(touches.isEmpty())
}
@Test fun aHeldTouchLiftsAtOnce() {
hold.configure(TouchGestureConfig())
touch(MotionEvent.ACTION_DOWN)
advance(80)
touch(MotionEvent.ACTION_UP)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
}
@Test fun aShortTapStaysPressedLongEnoughToBeSeen() {
hold.configure(TouchGestureConfig())
touch(MotionEvent.ACTION_DOWN)
advance(10)
touch(MotionEvent.ACTION_UP)
advance(39)
assertEquals(listOf("down 0 at 40.0,30.0"), touches)
advance(1)
assertEquals(listOf("down 0 at 40.0,30.0", "up 0 at 40.0,30.0"), touches)
}
@Test fun longPressFollowsTheConfiguredDelay() {
hold.configure(TouchGestureConfig(longPressEnabled = true, longPressDelay = 800))
hold.configure(TouchGestureConfig(longPressDelay = 800, directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
touch(MotionEvent.ACTION_DOWN)
advance(700)
assertTrue(buttons.isEmpty())
@@ -152,7 +152,8 @@ class SessionGestureRoutingTest {
@Test fun pausingCancelsPendingHoldsInBothTouchModes() {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E",
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
val now = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
@@ -167,7 +168,8 @@ class SessionGestureRoutingTest {
for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) {
keys.clear()
directButtons.clear()
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E"))
prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E",
directHoldBehavior = TouchGestureConfig.MOUSE_BEHAVIOR_CLICK))
val now = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0)
try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() }
@@ -0,0 +1,77 @@
package com.droiddeck.launcher.session
import android.app.Application
import android.content.Context
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, application = Application::class)
class TolerantPrefsTest {
private val context get() = RuntimeEnvironment.getApplication()
private val raw get() = context.getSharedPreferences("session", Context.MODE_PRIVATE)
@Before fun reset() {
raw.edit().clear().commit()
}
@After fun cleanup() {
raw.edit().clear().commit()
}
@Test fun aSwitchStoredAsTextReadsAsItsValue() {
raw.edit().putString("gameDebugLogsEnabled", "true").putString("logs", "false").commit()
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(SessionPrefs.logsEnabled(context))
}
@Test fun unreadableTextFallsBackToTheDefault() {
raw.edit().putString("gameDebugLogsEnabled", "yes").putString("logs", "").commit()
assertFalse(SessionPrefs.gameDebugLogsEnabled(context))
assertTrue(SessionPrefs.logsEnabled(context))
}
@Test fun everyTypedReadToleratesAnotherStoredType() {
raw.edit()
.putString("count", "7")
.putString("big", "8000000000")
.putString("ratio", "1.5")
.putBoolean("label", true)
.putInt("names", 3)
.commit()
val prefs = TolerantPrefs.session(context)
assertEquals(7, prefs.getInt("count", 0))
assertEquals(8_000_000_000L, prefs.getLong("big", 0L))
assertEquals(1.5f, prefs.getFloat("ratio", 0f), 0f)
assertEquals("true", prefs.getString("label", null))
assertEquals(setOf("x"), prefs.getStringSet("names", mutableSetOf("x")))
assertEquals(0, prefs.getInt("ratio", 0))
}
@Test fun correctlyTypedSettingsAreUnchanged() {
raw.edit().putBoolean("gameDebugLogsEnabled", true).putBoolean("logs", false).putString("theme", "paper").commit()
assertTrue(SessionPrefs.gameDebugLogsEnabled(context))
assertFalse(SessionPrefs.logsEnabled(context))
assertEquals("paper", SessionPrefs.theme(context))
}
@Test fun aSessionEndRepairsTheStoredType() {
raw.edit().putString("gameDebugLogsEnabled", "true").commit()
SessionPrefs.expireGameDebugLogs(context)
assertEquals(false, raw.all["gameDebugLogsEnabled"])
}
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.stores
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class SteamLiveShortcutsSyncTest {
@Test fun everyGameKnownOrAddedIsDelivered() {
assertTrue(SteamLiveShortcuts.synced("""{"added":2,"missed":0}"""))
assertTrue(SteamLiveShortcuts.synced("""{"added":0,"missed":0}"""))
}
@Test fun aGameTheClientRefusedIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced("""{"added":1,"missed":1}"""))
assertFalse(SteamLiveShortcuts.synced("""{"added":0,"missed":3}"""))
}
@Test fun noAnswerIsNotDelivered() {
assertFalse(SteamLiveShortcuts.synced(null))
assertFalse(SteamLiveShortcuts.synced("1"))
}
}
+5 -3
View File
@@ -43,9 +43,10 @@ Player controls and observations work over authorized ADB on any build: `state`,
**Setup > Developer > Debugging tools** is off by default in every build, including debug builds.
It enables `run`, `guest`, `cdp`, all `env` operations, `override`, `prefs`, and `glasses raw`. The
toggle switches directly without a confirmation dialog. The bridge refuses to change it through `ui`
or preference writes. The existing preference key, `setting-agent-commands` test tag, JSON command
names, and `AGENT_COMMANDS_DISABLED` error code are unchanged. Refusals exit 7; `droiddeckctl access`
reports whether commands are enabled.
or preference writes. `prefs set` refuses to change the type a key is stored as; remove the key
first. The existing preference key, `setting-agent-commands` test tag, JSON command names, and
`AGENT_COMMANDS_DISABLED` error code are unchanged. Refusals exit 7; `droiddeckctl access` reports
whether commands are enabled.
Disabling the toggle clears queued and persistent agent environment settings and installed binary
overrides. Disabled settings cannot apply at the next session start. Already running commands and
@@ -165,6 +166,7 @@ tools/droiddeckctl proot-profile disable
tools/droiddeckctl proot-profile report ./session.log --sort wall
tools/droiddeckctl prefs get session
tools/droiddeckctl prefs set session some_key true --type bool
tools/droiddeckctl prefs set session some_key --type remove
tools/droiddeckctl logs latest ./session-artifacts
tools/droiddeckctl screenshot ./screen.png --display 4