Compare commits

...
2 changed files with 166 additions and 23 deletions

No files matched your search

@@ -166,14 +166,21 @@ object SteamTouchConfig {
fun steamRoot(context: Context) = com.droiddeck.launcher.session.SessionPrefs.activeSteamRoot(context)
private fun controllerConfigs(context: Context) = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
fun configDir(context: Context): File? {
val base = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
val base = controllerConfigs(context)
val account = accountId(context)
if (account != null) File(base, "$account/config").takeIf { it.isDirectory }?.let { return it }
return base.listFiles()?.filter { it.name.all(Char::isDigit) && File(it, "config").isDirectory }
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
}
private fun writableConfigDir(context: Context): File? {
val account = accountId(context) ?: return configDir(context)
return File(controllerConfigs(context), "$account/config").apply { mkdirs() }.takeIf { it.isDirectory }
}
private fun accountId(context: Context): Long? = try {
val users = KeyValues.parse(File(steamRoot(context), "config/loginusers.vdf").readText())
val node = users.child("users")
@@ -197,7 +204,7 @@ object SteamTouchConfig {
}
return try {
val text = file.readText()
val kv = KeyValues.parse(text.removePrefix(""))
val kv = KeyValues.parse(text)
val mappings = kv.child("controller_mappings") ?: kv
val layouts = mappings.string("touch_layout")?.let { hex -> decodeLayouts(hexToBytes(hex)) }
Log.i(TAG, "steam touch: app $appId uses ${file.path} (${layouts?.layouts?.size ?: 0} layouts)")
@@ -389,8 +396,9 @@ object SteamTouchConfig {
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
options: Options? = null,
): File? {
val dir = configDir(context) ?: return null
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
val dir = writableConfigDir(context) ?: return null.also { Log.w(TAG, "steam touch: no controller config folder to save app $appId in") }
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n"
else return null.also { Log.w(TAG, "steam touch: ${config.file?.path ?: "default layout"} has no readable text to save into") }
val source = bindings.entries.fold(base) { text, (ref, change) ->
SteamTouchBindings.rewrite(text, ref, change) ?: text
}
@@ -408,11 +416,11 @@ object SteamTouchConfig {
val existing = Regex("""\n\s*"touch_layout"\s+"[0-9a-fA-F]*"""")
val text = if (existing.containsMatchIn(source)) source.replace(existing, "\n$line")
else source.replaceFirst(Regex("""("controller_type"\s+"controller_mobile_touch"[^\n]*)"""), "$1\n$line")
if (!text.contains("touch_layout")) return null
if (!text.contains("touch_layout")) return null.also { Log.w(TAG, "steam touch: ${config.file?.path} is no controller_mobile_touch config") }
target.parentFile?.mkdirs()
val tmp = File(target.path + ".tmp")
tmp.writeText(text)
if (!tmp.renameTo(target)) return null
if (!tmp.renameTo(target)) return null.also { Log.w(TAG, "steam touch: could not replace ${target.path}") }
selectAutosave(dir, key)
dropDeviceEntry(dir, key)
Log.i(TAG, "steam touch: saved layouts ${sets.keys} for app $appId to ${target.path}")
@@ -430,12 +438,13 @@ object SteamTouchConfig {
private fun selectAutosave(dir: File, key: String) {
val file = File(dir, CONFIGSET)
val text = if (file.isFile) file.readText() else "\"controller_config\"\n{\n}\n"
val entry = "\t\"$key\"\n\t{\n\t\t\"autosave\"\t\t\"1\"\n\t}"
val block = Regex("""\n\s*"${Regex.escape(key)}"\s*\{[^}]*\}""", RegexOption.IGNORE_CASE)
val next = if (block.containsMatchIn(text)) text.replace(block) { "\n$entry" }
else text.substring(0, text.lastIndexOf('}')).trimEnd() + "\n$entry\n}\n"
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
val root = file.takeIf { it.isFile }?.readText()?.let(KeyValues::parse)?.takeIf { it.child("controller_config") != null }
?: KeyValues.Node(mutableListOf("controller_config" to KeyValues.Node()))
val config = root.child("controller_config") ?: return
val entry = key to KeyValues.Node(mutableListOf("autosave" to "1"))
val at = config.entries.indexOfFirst { it.first.equals(key, true) && it.second is KeyValues.Node }
if (at >= 0) config.entries[at] = entry else config.entries += entry
File(file.path + ".tmp").apply { writeText(KeyValues.write(root)) }.renameTo(file)
}
@@ -593,34 +602,48 @@ class KeyValues private constructor() {
fun string(key: String): String? = entries.firstOrNull { it.first.equals(key, true) && it.second is String }?.second as String?
}
private class Token(val text: String, val quoted: Boolean) {
val opens get() = !quoted && text == "{"
val closes get() = !quoted && text == "}"
}
companion object {
fun write(node: Node): String = write(node, "")
private fun write(node: Node, indent: String): String = node.entries.joinToString("") { (key, value) ->
if (value is Node) "$indent\"${escape(key)}\"\n$indent{\n${write(value, "$indent\t")}$indent}\n"
else "$indent\"${escape(key)}\"\t\t\"${escape(value.toString())}\"\n"
}
private fun escape(text: String) = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\t", "\\t")
fun parse(text: String): Node {
val tokens = tokenize(text)
val tokens = tokenize(text.removePrefix("\uFEFF"))
var i = 0
fun node(): Node {
val n = Node()
while (i < tokens.size) {
val t = tokens[i++]
if (t == "}" ) return n
if (t == "{") continue
if (t.closes) return n
if (t.opens) continue
if (i >= tokens.size) break
val next = tokens[i]
if (next == "{") { i++; n.entries += t to node() } else { i++; n.entries += t to next }
if (next.opens) { i++; n.entries += t.text to node() } else { i++; n.entries += t.text to next.text }
}
return n
}
return node()
}
private fun tokenize(text: String): List<String> {
val out = mutableListOf<String>()
private fun tokenize(text: String): List<Token> {
val out = mutableListOf<Token>()
var i = 0
while (i < text.length) {
val c = text[i]
when {
c.isWhitespace() -> i++
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
c == '{' || c == '}' -> { out += c.toString(); i++ }
c == '{' || c == '}' -> { out += Token(c.toString(), false); i++ }
c == '"' -> {
val sb = StringBuilder()
i++
@@ -632,13 +655,13 @@ class KeyValues private constructor() {
i++
}
i++
out += sb.toString()
out += Token(sb.toString(), true)
}
c == '[' -> { while (i < text.length && text[i] != ']') i++; i++ }
else -> {
val start = i
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
out += text.substring(start, i)
out += Token(text.substring(start, i), false)
}
}
}
@@ -60,6 +60,117 @@ class SteamTouchConfigFilesTest {
private val template get() = File(steam, "controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf")
private fun login() = File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
private fun saveDefault(app: Int): File? {
val elements = listOf(SteamTouchConfig.Element(SteamTouchConfig.A, true, 0.5f, 0.6f))
return SteamTouchConfig.saveLayouts(context, app, SteamTouchConfig.load(context, app), mapOf(1 to elements))
}
private fun assertSavedA(app: Int, saved: File?) {
val loaded = SteamTouchConfig.load(context, app)
assertEquals(saved, loaded.file)
val a = SteamTouchConfig.elementsFor(loaded, 1, emptyList()).first { it.type == SteamTouchConfig.A }
assertEquals(0.5f, a.x, 0.002f)
assertEquals(0.6f, a.y, 0.002f)
}
@Test fun savesWhenSteamHasNotCreatedTheAccountsControllerFolder() {
File(steam, "steamapps/common/Steam Controller Configs").deleteRecursively()
login()
val saved = saveDefault(413150)
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
assertSavedA(413150, saved)
}
@Test fun savesIntoTheSignedInAccountNotAnotherAccountsFolder() {
dir.parentFile!!.deleteRecursively()
val other = File(steam, "steamapps/common/Steam Controller Configs/456/config").apply { mkdirs() }
login()
val saved = saveDefault(413150)
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
assertFalse(File(other, "413150").exists())
assertSavedA(413150, saved)
}
@Test fun withoutAnAccountOrControllerFolderNothingIsWritten() {
File(steam, "steamapps/common/Steam Controller Configs").deleteRecursively()
assertEquals(null, saveDefault(413150))
assertFalse(File(steam, "steamapps/common/Steam Controller Configs").exists())
}
@Test fun anEmptyConfigsetIsRebuiltInsteadOfFailingTheSave() {
File(dir, "configset_controller_mobile_touch.vdf").writeText("")
val saved = saveDefault(413150)
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
assertTrue(File(dir, "configset_controller_mobile_touch.vdf").readText().contains("\"413150\""))
assertSavedA(413150, saved)
}
@Test fun aConfigsetWithOnlyAQuotedBraceIsRebuilt() {
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\" \"{\"\n")
val saved = saveDefault(413150)
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
assertEquals("1", root?.child("413150")?.string("autosave"))
assertSavedA(413150, saved)
}
@Test fun anExistingConfigsetKeepsItsOtherEntries() {
configset("configset_controller_mobile_touch.vdf", "8400" to "\"workshop\"\t\t\"7\"")
saveDefault(413150)
val text = File(dir, "configset_controller_mobile_touch.vdf").readText()
assertTrue(text.contains("\"8400\""))
assertTrue(text.contains("\"413150\""))
}
private fun withBom(name: String) = File(dir, name).apply { writeText("\uFEFF" + readText()) }
@Test fun aConfigsetWithAByteOrderMarkKeepsItsOtherEntries() {
configset("configset_controller_mobile_touch.vdf", "8400" to "\"workshop\"\t\t\"7\"")
withBom("configset_controller_mobile_touch.vdf")
val saved = saveDefault(413150)
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
assertEquals("1", root?.child("413150")?.string("autosave"))
assertEquals("7", root?.child("8400")?.string("workshop"))
assertSavedA(413150, saved)
}
@Test fun aWorkshopPickInAConfigsetWithAByteOrderMarkIsRead() {
val picked = workshop("42", "community")
configset("configset_controller_mobile_touch.vdf", "413150" to "\"workshop\"\t\t\"42\"")
withBom("configset_controller_mobile_touch.vdf")
assertEquals(picked, SteamTouchConfig.load(context, 413150).file)
}
@Test fun aConfigsetMissingItsRootBraceGetsTheEntryAtTheRoot() {
File(dir, "configset_controller_mobile_touch.vdf")
.writeText("\"controller_config\"\n{\n\t\"8400\"\n\t{\n\t\t\"workshop\"\t\t\"7\"\n\t}\n")
val saved = saveDefault(413150)
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
assertEquals("1", root?.child("413150")?.string("autosave"))
assertEquals("7", root?.child("8400")?.string("workshop"))
assertEquals(null, root?.child("8400")?.child("413150"))
assertSavedA(413150, saved)
}
@Test fun aConfigsetCutOffAfterAKeyGetsTheEntryAtTheRoot() {
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\"\n{\n\t\"8400\"\n\t{\n\t\t\"workshop\"")
val saved = saveDefault(413150)
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
assertEquals("1", root?.child("413150")?.string("autosave"))
assertEquals(null, root?.child("8400")?.child("413150"))
assertSavedA(413150, saved)
}
@Test fun aConfigsetWhoseRootIsAQuotedValueIsRebuilt() {
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\" \"{}\"\n")
val saved = saveDefault(413150)
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
assertEquals("1", root?.child("413150")?.string("autosave"))
assertSavedA(413150, saved)
}
private fun shortcut(name: String): Int {
val shortcut = 2702387189L.toInt()
template.apply { parentFile!!.mkdirs(); writeText(touch("Gamepad with Joystick")) }
@@ -67,8 +178,7 @@ class SteamTouchConfigFilesTest {
"!! Controller 0 attributes:\n Type: 43\n" +
"Loaded Config for Last Resort Path for App ID 2702387189, Controller 0: /root/.local/share/Steam//controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf\n",
)
File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
login()
val vdf = java.io.ByteArrayOutputStream().apply {
write("\u0000shortcuts\u0000\u00000\u0000\u0002appid\u0000".toByteArray())
write(java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.LITTLE_ENDIAN).putInt(shortcut).array())
@@ -89,6 +199,16 @@ class SteamTouchConfigFilesTest {
assertEquals(saved, SteamTouchConfig.load(context, shortcut).file)
}
@Test fun aSavedShortcutNameWithBracesDoesNotHideTheNextAppsEntry() {
val shortcut = shortcut("Game {")
SteamTouchConfig.saveLayouts(context, shortcut, SteamTouchConfig.load(context, shortcut), mapOf(1 to emptyList()))
val saved = saveDefault(413150)
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
assertEquals("1", root?.child("game {")?.string("autosave"))
assertEquals("1", root?.child("413150")?.string("autosave"))
assertSavedA(413150, saved)
}
@Test fun aShortcutNameThatIsNoPlainFolderNameUsesTheAppId() {
for (name in listOf("../escape", "a/b", "..", "Tab\tName")) {
assertEquals(name, "2702387189", SteamTouchConfig.steamKey(context, shortcut(name)))