feat: connect remote controller skin sources

This commit is contained in:
Kurt Himebauch committed 2026-11-08 01:15:25 -05:00
1 parent 8276b29b7d
commit e5824dabab
12 files changed
+493 -56

No files matched your search

@@ -0,0 +1,115 @@
package com.droiddeck.launcher.input
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.ZipInputStream
internal object ArmsControlSkins {
private val buttons = mapOf(
InputControl.A to "cross", InputControl.B to "circle", InputControl.X to "square", InputControl.Y to "triangle",
InputControl.LB to "l1", InputControl.RB to "r1", InputControl.LT to "l2", InputControl.RT to "r2",
InputControl.L3 to "l3", InputControl.R3 to "r3", InputControl.SELECT to "select", InputControl.START to "start",
InputControl.UP to "up", InputControl.DOWN to "down", InputControl.LEFT to "left", InputControl.RIGHT to "right")
private val keys = buttons.values.toSet() + setOf("analog_base", "analog_stick", "analog_base_left", "analog_base_right",
"analog_stick_left", "analog_stick_right")
fun parse(context: android.content.Context, bytes: ByteArray, original: SavedInputLayout, actions: SavedInputBindings, name: String): CommunityControls.Pack {
require(bytes.size <= 32 * 1024 * 1024 && original.editable && actions.compatible(original))
val art = linkedMapOf<String, ByteArray>()
var total = 0
var entries = 0
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
require(++entries <= 256 && ControlSources.validPath(entry.name.trimEnd('/'))) { "Invalid skin archive path or file count." }
if (entry.isDirectory) continue
val data = CommunityControls.readLimited(zip, minOf(8 * 1024 * 1024, 64 * 1024 * 1024 - total))
total += data.size
require(entry.name != "controls.json") { "Import this file as a DroidDeck controls pack." }
val file = entry.name.substringAfterLast('/').lowercase()
if (file.startsWith("._") || !file.endsWith(".png")) continue
val key = file.removeSuffix(".png").removePrefix("ic_controller_").removeSuffix("_button")
if (key !in keys) continue
require(key !in art) { "Duplicate skin button artwork." }
art[key] = normalize(data)
}
}
require(art.isNotEmpty()) { "No supported controller PNGs found in this skin." }
val used = linkedMapOf<String, ByteArray>()
fun image(key: String): String? = art[key]?.let { data ->
val file = "skin_$key.png"
used[file] = data
file
}
var matched = 0
val elements = original.elements.map { e ->
val action = actions.action(e) as? InputAction.Native ?: return@map e
val control = action.target ?: e.control
if (e.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
val side = if (control == InputControl.LS) "left" else "right"
val base = image("analog_base_$side") ?: image("analog_base")
val stick = image("analog_stick_$side") ?: image("analog_stick")
if (base == null && stick == null) e else {
matched++
e.copy(image = base ?: "", stickImage = stick ?: "", showLabel = false)
}
} else if (e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER) {
val file = buttons[control]?.let(::image)
if (file == null) e else { matched++; e.copy(image = file, icon = 0, showLabel = false) }
} else e
}
require(matched > 0) { "This layout has no matching gamepad controls. Choose a gamepad profile and screen." }
val id = newInputId()
val label = name.trim().take(80).ifBlank { "Imported controller skin" }
val layout = original.copy(id = id, name = label, origin = null, elements = elements)
for (file in elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
if (file !in used) used[file] = requireNotNull(InputButtonImages.file(context, file)).inputStream().use {
CommunityControls.readLimited(it, 1024 * 1024)
}
}
return CommunityControls.Pack(layout, actions.copy(id = newInputId(), name = label, layoutId = id), used)
}
fun export(context: android.content.Context, layout: SavedInputLayout, actions: SavedInputBindings): ByteArray {
val images = linkedMapOf<String, String>()
for (element in layout.elements) {
val action = actions.action(element) as? InputAction.Native ?: continue
val control = action.target ?: element.control
if (element.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
val side = if (control == InputControl.LS) "left" else "right"
if (element.image.isNotEmpty()) images["ic_controller_analog_base_$side.png"] = element.image
if (element.stickImage.isNotEmpty()) images["ic_controller_analog_stick_$side.png"] = element.stickImage
} else if (element.image.isNotEmpty()) {
buttons[control]?.let { images["ic_controller_${it}_button.png"] = element.image }
}
}
require(images.isNotEmpty()) { "This layout has no controller skin artwork to export." }
val output = ByteArrayOutputStream()
java.util.zip.ZipOutputStream(output).use { zip ->
for ((name, local) in images) {
val bytes = requireNotNull(InputButtonImages.file(context, local)).inputStream().use {
CommunityControls.readLimited(it, 1024 * 1024)
}
zip.putNextEntry(java.util.zip.ZipEntry(name)); zip.write(bytes); zip.closeEntry()
}
}
return output.toByteArray().also { require(it.size <= 32 * 1024 * 1024) }
}
private fun normalize(data: ByteArray): ByteArray {
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10)) { "Invalid skin PNG." }
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
require(bounds.outWidth in 1..8192 && bounds.outHeight in 1..8192) { "Invalid skin image dimensions." }
val options = BitmapFactory.Options().apply {
inSampleSize = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 512) inSampleSize *= 2
}
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size, options)) { "Unreadable skin image." }
return try {
ByteArrayOutputStream().also { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) }.toByteArray()
} finally { bitmap.recycle() }
}
}
@@ -19,7 +19,10 @@ internal object CommunityControls {
const val SUBMIT = "https://github.com/Droid-Deck/DroidDeck/issues/new?template=community-controls.yml"
data class Pack(val layout: SavedInputLayout, val bindings: SavedInputBindings, val images: Map<String, ByteArray>)
data class Entry(val name: String, val author: String, val game: String, val license: String,
val path: String, val sha256: String, val screen: InputLayoutScreen, val preview: String? = null, val bundled: Boolean = false)
val path: String, val sha256: String, val screen: InputLayoutScreen, val preview: String? = null, val bundled: Boolean = false,
val source: ControlSources.Source = ControlSources.DROIDDECK, val skin: Boolean = false) {
val key get() = source.id + "/" + path
}
fun readLimited(input: InputStream, limit: Int = MAX_BYTES): ByteArray {
val output = ByteArrayOutputStream()
@@ -49,7 +52,7 @@ internal object CommunityControls {
zip.putNextEntry(ZipEntry(name)); zip.write(bytes); zip.closeEntry()
}
add("controls.json", manifest.toString().toByteArray(Charsets.UTF_8))
for (name in layout.elements.map { it.image }.filter { it.isNotEmpty() }.distinct()) {
for (name in layout.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
val file = requireNotNull(InputButtonImages.file(context, name))
add("images/$name", file.inputStream().use { readLimited(it, 1024 * 1024) })
}
@@ -86,7 +89,7 @@ internal object CommunityControls {
doc.getJSONArray("bindings").put(bindings)
val decoded = requireNotNull(InputLibraries.decode(doc.toString())) { "Invalid controls or bindings." }
val saved = decoded.layouts.first { it.id == layoutId }
val names = saved.elements.map { it.image }.filter { it.isNotEmpty() }.toSet()
val names = saved.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.toSet()
require(files.keys == names.map { "images/$it" }.toSet()) { "Missing or unexpected button images." }
var pixels = 0L
val images = names.associateWith { name ->
@@ -96,7 +99,7 @@ internal object CommunityControls {
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
require(bounds.outWidth in 1..1024 && bounds.outHeight in 1..1024)
pixels += bounds.outWidth.toLong() * bounds.outHeight
require(pixels <= 4_194_304)
require(pixels <= 16_777_216)
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size))
bitmap.recycle()
data
@@ -116,7 +119,7 @@ internal object CommunityControls {
file.writeBytes(bytes)
name
}
val layout = pack.layout.copy(elements = pack.layout.elements.map { e -> e.copy(image = names[e.image] ?: "") })
val layout = pack.layout.copy(elements = pack.layout.elements.map { e -> e.copy(image = names[e.image] ?: "", stickImage = names[e.stickImage] ?: "") })
return InputLibraries.update(context) {
it.withLayout(layout).withPreset(pack.bindings).chooseLayout(profile, role, layout.id)
}
@@ -126,22 +129,23 @@ internal object CommunityControls {
}
}
fun catalog(raw: String): List<Entry> {
fun catalog(raw: String, source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> {
require(raw.length <= 1_000_000)
val doc = JSONObject(raw)
require(doc.getInt("version") == 1)
val list = doc.getJSONArray("controls")
val skin = doc.has("skins") && !doc.has("controls")
require(skin || doc.getInt("version") == 1)
val list = doc.getJSONArray(if (skin) "skins" else "controls")
require(list.length() <= 256)
return (0 until list.length()).map { index ->
val e = list.getJSONObject(index)
fun text(key: String) = e.getString(key).also { require(it.isNotBlank() && it.length <= 160) }
val path = text("file")
require(path.matches(Regex("packs/[a-z0-9_-]+[.]ddcontrols[.]zip")))
val sha = text("sha256").also { require(it.matches(Regex("[a-f0-9]{64}"))) }
Entry(text("name"), text("author"), e.optString("game").take(160), text("license"), path, sha,
InputLayoutScreen.valueOf(e.getString("screen")), e.optString("preview").takeIf { it.isNotEmpty() }?.also {
require(it.matches(Regex("previews/[a-z0-9_-]+[.]png")))
})
require(ControlSources.validPath(path) && path.endsWith(".zip", ignoreCase = true))
val sha = e.optString("sha256").also { require(if (skin) it.isEmpty() || it.matches(Regex("[a-f0-9]{64}")) else it.matches(Regex("[a-f0-9]{64}"))) }
Entry(text("name"), e.optString("author").take(160), e.optString("game").take(160), e.optString("license").take(160), path, sha,
if (skin) InputLayoutScreen.BOTH else InputLayoutScreen.valueOf(e.getString("screen")), e.optString("preview").takeIf { it.isNotEmpty() }?.also {
require(ControlSources.validPath(it) && it.endsWith(".png", ignoreCase = true))
}, source = source, skin = skin)
}.also { require(it.map { e -> e.path }.distinct().size == it.size) }
}
@@ -149,23 +153,29 @@ internal object CommunityControls {
catalog(readLimited(it, 1_000_000).toString(Charsets.UTF_8)).map { e -> e.copy(bundled = true) }
}
fun fetchCatalog(): List<Entry> = catalog(get(BASE + "catalog.json", 1_000_000).toString(Charsets.UTF_8))
fun fetchCatalog(source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> =
catalog(get(source.manifest, 1_000_000).toString(Charsets.UTF_8), source)
fun preview(context: Context, entry: Entry): android.graphics.Bitmap? {
val path = entry.preview ?: return null
val bytes = if (entry.bundled) context.assets.open("community-controls/$path").use { readLimited(it, 512 * 1024) }
else get(BASE + path, 512 * 1024)
else get(entry.source.url(path), 2 * 1024 * 1024)
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
require(bounds.outWidth in 1..1024 && bounds.outHeight in 1..1024)
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
require(bounds.outWidth in 1..4096 && bounds.outHeight in 1..4096)
val options = BitmapFactory.Options().apply {
inSampleSize = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 512) inSampleSize *= 2
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
}
fun download(context: Context, entry: Entry): Pack {
fun download(context: Context, entry: Entry, layout: SavedInputLayout? = null, bindings: SavedInputBindings? = null): Pack {
val bytes = if (entry.bundled) context.assets.open("community-controls/${entry.path}").use { readLimited(it) }
else get(BASE + entry.path, MAX_BYTES)
else get(entry.source.url(entry.path), if (entry.skin) 32 * 1024 * 1024 else MAX_BYTES)
val sha = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
require(sha == entry.sha256) { "Controls download failed verification." }
return parse(context, bytes).also { require(it.layout.screen == entry.screen) }
require(entry.sha256.isEmpty() && entry.skin || sha == entry.sha256) { "Controls download failed verification." }
return if (entry.skin) ArmsControlSkins.parse(context, bytes, requireNotNull(layout), requireNotNull(bindings), entry.name)
else parse(context, bytes).also { require(it.layout.screen == entry.screen) }
}
private fun get(url: String, limit: Int): ByteArray {
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONArray
import java.net.URI
import java.net.URLEncoder
internal object ControlSources {
data class Source(val name: String, val manifest: String, val submit: String? = null, val builtIn: Boolean = false) {
val id get() = manifest
fun url(path: String): String {
require(validPath(path)) { "Invalid controls source path." }
return manifest.substringBeforeLast('/') + "/" + path.split('/').joinToString("/") {
URLEncoder.encode(it, "UTF-8").replace("+", "%20")
}
}
}
val DROIDDECK = Source("DroidDeck", CommunityControls.BASE + "catalog.json", CommunityControls.SUBMIT, true)
val ARMSX2 = Source("ARMSX2 community", "https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/manifest.json",
"https://github.com/bagasromadon/ARMSX2-CustomControllerSkins/issues/new", true)
private fun prefs(context: Context) = context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE)
fun validPath(path: String) = path.length in 1..512 && path.split('/').all { it.isNotBlank() && it != "." && it != ".." } &&
path.none { it.isISOControl() || it in "\\:%?#" } && !path.startsWith('/')
private fun https(raw: String): URI {
require(raw.length <= 2048)
val uri = URI(raw.trim())
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null && uri.query == null && !uri.path.isNullOrBlank() && !uri.path.endsWith('/')) {
"Enter an HTTPS catalog URL or a GitHub repository URL."
}
return uri
}
fun candidates(raw: String): List<Source> {
val uri = https(raw)
val parts = uri.path.trim('/').split('/')
if (uri.host.equals("github.com", true)) {
require(parts.size == 2 || parts.size >= 5 && parts[2] == "blob") { "Use a GitHub repository or manifest file URL." }
require(parts.take(2).all { it.matches(Regex("[A-Za-z0-9_.-]+")) && it != "." && it != ".." })
val repo = parts.take(2).joinToString("/")
val submit = "https://github.com/$repo/issues/new"
val base = "https://raw.githubusercontent.com/$repo/"
return if (parts.size == 2) listOf("catalog.json", "manifest.json").map { Source(repo, base + "main/" + it, submit) }
else listOf(Source(repo, base + parts.drop(3).joinToString("/"), submit))
}
val submit = if (uri.host.equals("raw.githubusercontent.com", true) && parts.size >= 4)
"https://github.com/${parts[0]}/${parts[1]}/issues/new" else null
return listOf(Source(if (submit != null) parts.take(2).joinToString("/") else uri.host, uri.toASCIIString(), submit))
}
fun read(context: Context): List<Source> {
val custom = runCatching {
val raw = prefs(context).getString("sources", "[]")!!
require(raw.length <= 32_000)
val array = JSONArray(raw)
require(array.length() <= 16)
(0 until array.length()).map { candidates(array.getString(it)).single() }
}.getOrDefault(emptyList())
return (listOf(DROIDDECK, ARMSX2) + custom).distinctBy { it.id }
}
fun add(context: Context, source: Source) {
val list = read(context)
require(list.none { it.id == source.id }) { "This source is already connected." }
require(list.size < 18) { "Remove a source before adding another." }
save(context, list + source)
}
fun remove(context: Context, source: Source) {
require(!source.builtIn)
save(context, read(context).filterNot { it.id == source.id })
}
private fun save(context: Context, sources: List<Source>) {
check(prefs(context).edit().putString("sources", JSONArray(sources.filterNot { it.builtIn }.map { it.manifest }).toString()).commit()) {
"Could not save controls sources."
}
}
}
@@ -10,7 +10,7 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 14
private const val VERSION = 15
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -304,7 +304,7 @@ object InputLibraries {
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown).put("stickImage", e.stickImage))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
@@ -345,7 +345,7 @@ object InputLibraries {
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false), e.optString("stickImage", ""))
}
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
@@ -244,7 +244,8 @@ data class InputLibrary(
for (e in layout.elements) {
inputName(e.name)
require(e.icon == 0 || InputButtonIcons.has(e.icon))
require(e.image.isEmpty() || e.image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && e.image != "." && e.image != "..")
for (image in listOf(e.image, e.stickImage))
require(image.isEmpty() || image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && image != "." && image != "..")
require(e.opacity.isFinite() && e.opacity in 0.01f..1f)
require(!e.toggle || e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER)
require(listOf(e.x, e.y, e.width, e.height).all { it.isFinite() })
@@ -35,6 +35,7 @@ data class InputSurfaceElement(
val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
val showLabel: Boolean = true,
val alwaysShown: Boolean = false,
val stickImage: String = "",
) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
@@ -29,6 +29,10 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
val scope = rememberCoroutineScope()
val host = rememberMenuHost()
var role by remember { mutableStateOf(initialRole.takeUnless { it == InputRole.PHYSICAL } ?: InputRole.PRIMARY) }
var sources by remember { mutableStateOf(ControlSources.read(context)) }
var selectedSource by remember { mutableStateOf(sources.first()) }
var addingSource by remember { mutableStateOf(false) }
var sourceUrl by remember { mutableStateOf("") }
var entries by remember { mutableStateOf(CommunityControls.bundled(context)) }
var busy by remember { mutableStateOf(false) }
var status by remember { mutableStateOf<String?>(null) }
@@ -39,9 +43,9 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
DisposableEffect(Unit) { onDispose { previews.values.forEach { it.recycle() } } }
LaunchedEffect(entries) {
for (entry in entries) {
if (entry.preview == null || entry.path in previews) continue
if (entry.preview == null || entry.key in previews) continue
val bitmap = withContext(Dispatchers.IO) { runCatching { CommunityControls.preview(context, entry) }.getOrNull() }
if (bitmap != null) previews[entry.path] = bitmap
if (bitmap != null) previews[entry.key] = bitmap
}
}
fun task(action: suspend () -> Unit) {
@@ -54,11 +58,22 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
finally { busy = false }
}
}
fun load(source: ControlSources.Source) {
task {
val remote = withContext(Dispatchers.IO) { CommunityControls.fetchCatalog(source) }
val bundled = if (source.id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
entries = (remote + bundled).distinctBy { it.path }
status = context.getString(R.string.community_refreshed)
}
}
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) task {
pending = withContext(Dispatchers.IO) {
val bytes = requireNotNull(context.contentResolver.openInputStream(uri)).use { CommunityControls.readLimited(it) }
CommunityControls.parse(context, bytes)
val bytes = requireNotNull(context.contentResolver.openInputStream(uri)).use { CommunityControls.readLimited(it, 32 * 1024 * 1024) }
runCatching { CommunityControls.parse(context, bytes) }.getOrElse {
ArmsControlSkins.parse(context, bytes, requireNotNull(library.layout(targetProfile, role)),
library.preset(library.profile(targetProfile).binding(role)), "Imported skin")
}
}
}
}
@@ -73,10 +88,29 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
}
}
InputHint(stringResource(R.string.community_description))
SettingsGroup(stringResource(R.string.community_sources)) {
ChoiceRow(host, "community-source", stringResource(R.string.community_source), null,
sources.map { it.id to it.name }, selectedSource.id) { id ->
if (!busy) {
selectedSource = sources.first { it.id == id }
entries = if (id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
load(selectedSource)
}
}
PadTextButton(enabled = !busy, onClick = { sourceUrl = ""; addingSource = true }, modifier = Modifier.padding(8.dp).testTag("community-add-source")) {
Text(stringResource(R.string.community_add_source))
}
if (!selectedSource.builtIn) PadTextButton(enabled = !busy, onClick = { task {
ControlSources.remove(context, selectedSource)
sources = ControlSources.read(context)
selectedSource = sources.first()
entries = CommunityControls.bundled(context)
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_remove_source)) }
}
SettingsGroup(stringResource(R.string.community_target)) {
ChoiceRow(host, "community-profile", stringResource(R.string.input_profile), null,
library.profiles.map { it.id to it.name }, targetProfile) { if (!busy) targetProfile = it }
ChoiceRow(host, "community-screen", stringResource(R.string.ctrl_layout), null,
ChoiceRow(host, "community-screen", stringResource(R.string.community_screen), null,
listOf(InputRole.PRIMARY, InputRole.SECONDARY).map { it to roleLabel(it) }, role) { if (!busy) role = it }
}
SettingsGroup(stringResource(R.string.community_title)) {
@@ -86,18 +120,15 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
(search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, ignoreCase = true)) }) {
InputNavigationRow(entry.name, listOf(entry.author, entry.game, entry.license).filter { it.isNotEmpty() }.joinToString(" · "),
Modifier.testTag("community-pack-${entry.path}"), leading = {
previews[entry.path]?.let { Image(it.asImageBitmap(), null, Modifier.width(112.dp).height(76.dp).testTag("community-preview-${entry.path}"), contentScale = ContentScale.Fit) }
previews[entry.key]?.let { Image(it.asImageBitmap(), null, Modifier.width(112.dp).height(76.dp).testTag("community-preview-${entry.path}"), contentScale = ContentScale.Fit) }
}) {
task { pending = withContext(Dispatchers.IO) { CommunityControls.download(context, entry) } }
task { pending = withContext(Dispatchers.IO) { CommunityControls.download(context, entry, library.layout(targetProfile, role),
library.preset(library.profile(targetProfile).binding(role))) } }
}
}
if (entries.none { it.screen.supports(role) && (search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, true)) })
InputHint(stringResource(R.string.community_empty))
PadTextButton(enabled = !busy, onClick = { task {
val remote = withContext(Dispatchers.IO) { CommunityControls.fetchCatalog() }
entries = (remote + CommunityControls.bundled(context)).distinctBy { it.path }
status = context.getString(R.string.community_refreshed)
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_refresh)) }
PadTextButton(enabled = !busy, onClick = { load(selectedSource) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_refresh)) }
PadTextButton(enabled = !busy, onClick = { importer.launch(arrayOf("application/zip", "application/octet-stream", "application/x-zip-compressed")) },
modifier = Modifier.padding(8.dp).testTag("community-import")) { Text(stringResource(R.string.community_import)) }
}
@@ -108,13 +139,43 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
exporting = withContext(Dispatchers.IO) { CommunityControls.export(context, layout, library.preset(library.profile(targetProfile).binding(role))) }
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".ddcontrols.zip")
} }, modifier = Modifier.padding(8.dp).testTag("community-export")) { Text(stringResource(R.string.community_export)) }
if (layout?.editable == true && layout.elements.any { it.image.isNotEmpty() || it.stickImage.isNotEmpty() })
PadTextButton(enabled = !busy, onClick = { task {
exporting = withContext(Dispatchers.IO) { ArmsControlSkins.export(context, layout,
library.preset(library.profile(targetProfile).binding(role))) }
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".skin.zip")
} }, modifier = Modifier.padding(8.dp).testTag("community-export-skin")) { Text(stringResource(R.string.community_export_skin)) }
PadTextButton(onClick = {
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(CommunityControls.SUBMIT))) }
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(selectedSource.submit ?: selectedSource.manifest))) }
.onFailure { status = context.getString(R.string.community_failed) }
}, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_submit)) }
}
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth().padding(12.dp))
status?.let { InputHint(it) }
if (addingSource) AlertDialog(onDismissRequest = { if (!busy) addingSource = false },
title = { Text(stringResource(R.string.community_add_source)) }, text = { Column {
Text(stringResource(R.string.community_source_hint))
OutlinedTextField(sourceUrl, { sourceUrl = it.take(2048) }, singleLine = true,
label = { Text(stringResource(R.string.community_source_url)) }, modifier = Modifier.testTag("community-source-url"))
status?.let { Text(it) }
} }, confirmButton = {
PadTextButton(enabled = !busy && sourceUrl.isNotBlank(), onClick = { task {
val (source, remote) = withContext(Dispatchers.IO) {
var failure: Exception? = null
var found: Pair<ControlSources.Source, List<CommunityControls.Entry>>? = null
for (candidate in ControlSources.candidates(sourceUrl)) {
try { found = candidate to CommunityControls.fetchCatalog(candidate); break }
catch (e: Exception) { failure = e }
}
found ?: throw (failure ?: IllegalArgumentException(context.getString(R.string.community_failed)))
}
ControlSources.add(context, source)
sources = ControlSources.read(context)
selectedSource = sources.first { it.id == source.id }
entries = remote
addingSource = false
} }) { Text(stringResource(R.string.community_connect)) }
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { addingSource = false }) { Text(stringResource(R.string.common_cancel)) } })
pending?.let { pack ->
AlertDialog(onDismissRequest = { if (!busy) pending = null }, title = { Text(pack.layout.name) },
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
@@ -327,13 +327,7 @@ class InputSurfaceView(
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
}
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private var down = false
private val pointers = HashSet<Int>()
val round get() = element.buttonShape == InputButtonShape.CIRCLE
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
private val symbol = InputButtonIcons.drawable(context, element.icon)
private val bitmap = previewImages[element.image] ?: InputButtonImages.file(context, element.image)?.let { file ->
private fun imageBitmap(name: String): android.graphics.Bitmap? = previewImages[name] ?: InputButtonImages.file(context, name)?.let { file ->
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.path, size)
val options = BitmapFactory.Options().apply {
@@ -342,6 +336,14 @@ class InputSurfaceView(
}
if (file.isFile) BitmapFactory.decodeFile(file.path, options) else null
}
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private var down = false
private val pointers = HashSet<Int>()
val round get() = element.buttonShape == InputButtonShape.CIRCLE
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
private val symbol = InputButtonIcons.drawable(context, element.icon)
private val bitmap = imageBitmap(element.image)
private val imageRect = RectF()
override fun onDraw(canvas: Canvas) {
@@ -512,6 +514,17 @@ class InputSurfaceView(
private var knobY = 0f
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
private val baseImage = imageBitmap(element.image)
private val stickImage = imageBitmap(element.stickImage)
private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
private val imageBounds = RectF()
private fun drawImage(canvas: Canvas, image: android.graphics.Bitmap, x: Float, y: Float, radius: Float) {
val scale = min(radius * 2 / image.width, radius * 2 / image.height)
imageBounds.set(x - image.width * scale / 2, y - image.height * scale / 2,
x + image.width * scale / 2, y + image.height * scale / 2)
canvas.drawBitmap(image, null, imageBounds, imagePaint)
}
val adaptive get() = adaptive(element)
@@ -535,6 +548,14 @@ class InputSurfaceView(
val cx = if (touching) originX else centreX()
val cy = if (touching) originY else height / 2f
val color = tint
if (baseImage != null || stickImage != null) {
val radius = min(width, height) / 2f - .75f * density
if (baseImage != null) drawImage(canvas, baseImage, cx, cy, radius)
else { ring.color = LINE; ring.strokeWidth = 2 * density; canvas.drawCircle(cx, cy, radius, ring) }
if (stickImage != null) drawImage(canvas, stickImage, cx + knobX, cy + knobY, radius * .46f)
else { knob.color = if (touching) ACCENT else KNOB; canvas.drawCircle(cx + knobX, cy + knobY, radius * .46f, knob) }
return
}
if (classic(element) && color != null) {
val radius = min(width, height) / 2f - 0.75f * density
drawCircle(canvas, cx, cy, radius,
+12 -3
View File
@@ -7,11 +7,11 @@
<string name="community_empty">No controls match this screen and search.</string>
<string name="community_refresh">Check for community packs</string>
<string name="community_refreshed">Community catalog updated.</string>
<string name="community_import">Import controls pack (.zip)</string>
<string name="community_import">Import controls or skin (.zip)</string>
<string name="community_export">Export this layout and actions</string>
<string name="community_share">Share your controls</string>
<string name="community_submit_hint">Export the selected profile’s layout, then attach the ZIP and a screenshot to a community submission. Reviewed packs appear in the catalog. A GitHub account is required to submit.</string>
<string name="community_submit">Submit a community pack</string>
<string name="community_submit_hint">Export your controls and share the ZIP directly, or submit it through the selected source’s website. Each source manages its own uploads and catalog. GitHub sources require a GitHub account.</string>
<string name="community_submit">Open source submissions</string>
<string name="community_exported">Pack exported. You can share the ZIP directly or attach it to a community submission.</string>
<string name="community_apply_hint">%1$d controls. Apply layout and actions to %2$s · %3$s? This selects a new local copy. Other profiles keep their controls.</string>
<string name="community_apply">Apply controls</string>
@@ -19,4 +19,13 @@
<string name="community_failed">Could not load or save community controls.</string>
<string name="community_game_controls">On-screen controls profile</string>
<string name="community_game_controls_hint">Use this profile’s screen layouts and actions. Physical controls follow your general settings.</string>
<string name="community_sources">Sources</string>
<string name="community_source">Source</string>
<string name="community_screen">Screen</string>
<string name="community_add_source">Connect another source</string>
<string name="community_remove_source">Remove source</string>
<string name="community_source_url">Repository or catalog URL</string>
<string name="community_source_hint">Enter a public GitHub repository or an HTTPS catalog.json or manifest.json URL. Supports DroidDeck controls packs and ARMSX2 controller skins. Downloads come directly from the source.</string>
<string name="community_connect">Connect</string>
<string name="community_export_skin">Export skin artwork (.zip)</string>
</resources>
@@ -0,0 +1,80 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import org.junit.Assert.*
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
import org.robolectric.annotation.GraphicsMode
import java.io.ByteArrayOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class ArmsControlSkinsTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun reset() { context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit() }
private fun base() = CommunityControls.parse(context, context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() })
private fun png(color: Int, size: Int = 16): ByteArray {
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }
return ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it); bitmap.recycle() }.toByteArray()
}
private fun zip(vararg files: Pair<String, ByteArray>): ByteArray {
val bytes = ByteArrayOutputStream()
ZipOutputStream(bytes).use { z -> files.forEach { (name, data) -> z.putNextEntry(ZipEntry(name)); z.write(data); z.closeEntry() } }
return bytes.toByteArray()
}
@Test fun skinAppliesToNativeTargetsAndPreservesBindingsAndGeometry() {
val old = base()
val skin = ArmsControlSkins.parse(context, zip("folder/ic_controller_cross_button.png" to png(Color.RED),
"square.png" to png(Color.BLUE)), old.layout, old.bindings, "Community skin")
assertEquals(old.bindings.elements, skin.bindings.elements)
assertEquals(old.layout.elements.map { it.x to it.y }, skin.layout.elements.map { it.x to it.y })
assertEquals("skin_cross.png", skin.layout.elements.first { it.id == "a" }.image)
assertEquals("skin_square.png", skin.layout.elements.first { it.id == "x" }.image)
assertEquals("", skin.layout.elements.first { it.id == "b" }.image)
assertNotEquals(old.layout.id, skin.layout.id)
}
@Test fun separateStickArtworkSurvivesInstallExportAndReimport() {
val old = base()
val skin = ArmsControlSkins.parse(context, zip("analog_base.png" to png(Color.RED),
"analog_stick_left.png" to png(Color.GREEN), "analog_stick_right.png" to png(Color.BLUE)), old.layout, old.bindings, "Stick skin")
val left = skin.layout.elements.first { it.id == "left-stick" }
val right = skin.layout.elements.first { it.id == "right-stick" }
assertEquals(left.image, right.image)
assertNotEquals(left.stickImage, right.stickImage)
val installed = CommunityControls.install(context, skin, InputProfile.GAME, InputRole.PRIMARY)
val layout = installed.layout(InputProfile.GAME, InputRole.PRIMARY)!!
val bindings = installed.preset(installed.profile(InputProfile.GAME).binding(InputRole.PRIMARY))
val pack = CommunityControls.parse(context, CommunityControls.export(context, layout, bindings))
assertEquals(3, pack.images.size)
assertNotEquals("", pack.layout.elements.first { it.id == "left-stick" }.stickImage)
val artwork = ArmsControlSkins.export(context, layout, bindings)
val imported = ArmsControlSkins.parse(context, artwork, old.layout, old.bindings, "Shared skin")
assertEquals(4, imported.images.size)
assertEquals(old.bindings.elements, imported.bindings.elements)
}
@Test fun downsamplesLargeImagesBeforeStoringThem() {
val old = base()
val skin = ArmsControlSkins.parse(context, zip("cross.png" to png(Color.RED, 2048)), old.layout, old.bindings, "Large skin")
val bytes = skin.images.values.single()
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
assertTrue(bitmap.width <= 512 && bitmap.height <= 512)
bitmap.recycle()
}
@Test fun rejectsTraversalDuplicateButtonsAndArchivesWithoutMatchingImages() {
val old = base()
for (files in listOf(arrayOf("../cross.png" to png(Color.RED)),
arrayOf("cross.png" to png(Color.RED), "ic_controller_cross_button.png" to png(Color.RED)),
arrayOf("readme.txt" to byteArrayOf()), arrayOf("cross.png" to byteArrayOf(1, 2))))
assertThrows(IllegalArgumentException::class.java) { ArmsControlSkins.parse(context, zip(*files), old.layout, old.bindings, "Invalid") }
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class ControlSourcesTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun reset() { context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE).edit().clear().commit() }
@Test fun hasRemoteArmsSourceWithoutBundlingItsArtwork() {
assertEquals(listOf(ControlSources.DROIDDECK, ControlSources.ARMSX2), ControlSources.read(context))
assertTrue(ControlSources.ARMSX2.manifest.contains("bagasromadon/ARMSX2-CustomControllerSkins"))
}
@Test fun githubRepositoriesAndFileLinksResolveToManifests() {
val repo = ControlSources.candidates("https://github.com/example/controls")
assertEquals(listOf("https://raw.githubusercontent.com/example/controls/main/catalog.json",
"https://raw.githubusercontent.com/example/controls/main/manifest.json"), repo.map { it.manifest })
assertEquals("https://raw.githubusercontent.com/example/controls/dev/skins/manifest.json",
ControlSources.candidates("https://github.com/example/controls/blob/dev/skins/manifest.json").single().manifest)
}
@Test fun customSourcesPersistAndCanBeRemovedWithoutLosingDefaults() {
val source = ControlSources.candidates("https://example.com/controls/catalog.json").single()
ControlSources.add(context, source)
assertEquals(source, ControlSources.read(context).last())
assertThrows(IllegalArgumentException::class.java) { ControlSources.add(context, source) }
ControlSources.remove(context, source)
assertEquals(2, ControlSources.read(context).size)
}
@Test fun pathsStayWithinSourceAndEncodeSpaces() {
assertEquals("https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/Skins/Black%20Gold.zip",
ControlSources.ARMSX2.url("Skins/Black Gold.zip"))
for (path in listOf("../other.zip", "packs/../x.zip", "https://other.com/x", "/x", "x%2f..zip", "x?bad", "x\\bad"))
assertThrows(IllegalArgumentException::class.java) { ControlSources.ARMSX2.url(path) }
for (url in listOf("http://example.com/catalog.json", "https://user:secret@example.com/catalog.json", "file:///tmp/catalog.json", "https://example.com"))
assertThrows(IllegalArgumentException::class.java) { ControlSources.candidates(url) }
}
@Test fun parsesArmsCatalogAndKeepsSourceAndOptionalLicenseSeparate() {
val raw = """{"skins":[{"name":"Black Gold", "author":"maker", "file":"Skins/Black Gold.zip", "preview":"Previews/Black_Gold.png"}]}"""
val entry = CommunityControls.catalog(raw, ControlSources.ARMSX2).single()
assertTrue(entry.skin)
assertEquals("", entry.license)
assertEquals("", entry.sha256)
assertEquals(ControlSources.ARMSX2, entry.source)
assertNotEquals(entry.key, entry.copy(source = ControlSources.DROIDDECK).key)
}
}