fix: bound previews and preserve skin artwork

This commit is contained in:
Kurt Himebauch committed 2026-11-08 01:36:08 -05:00
1 parent 0ff1bebdf6
commit 97c6229e85
8 files changed
+92 -21

No files matched your search

@@ -15,7 +15,7 @@ internal object ArmsControlSkins {
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 {
fun parse(context: android.content.Context, bytes: ByteArray, original: SavedInputLayout, actions: SavedInputBindings, name: String, nativeFailure: Exception? = null): CommunityControls.Pack {
require(bytes.size <= 32 * 1024 * 1024 && original.editable && actions.compatible(original))
val art = linkedMapOf<String, ByteArray>()
var total = 0
@@ -27,7 +27,7 @@ internal object ArmsControlSkins {
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." }
if (entry.name == "controls.json") throw (nativeFailure ?: IllegalArgumentException("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")
@@ -53,7 +53,7 @@ internal object ArmsControlSkins {
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)
e.copy(image = base ?: e.image, stickImage = stick ?: e.stickImage, showLabel = false)
}
} else if (e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER) {
val file = buttons[control]?.let(::image)
@@ -107,6 +107,11 @@ internal object CommunityControls {
return Pack(saved, decoded.preset(bindingId), images)
}
fun importFile(context: Context, bytes: ByteArray, layout: SavedInputLayout, bindings: SavedInputBindings): Pack =
try { parse(context, bytes) } catch (nativeFailure: Exception) {
ArmsControlSkins.parse(context, bytes, layout, bindings, "Imported skin", nativeFailure)
}
fun install(context: Context, pack: Pack, profile: String, role: InputRole): InputLibrary {
require(pack.layout.supports(role))
val written = mutableListOf<java.io.File>()
@@ -164,7 +169,7 @@ internal object CommunityControls {
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
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 256) inSampleSize *= 2
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
}
@@ -22,7 +22,7 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun InputCommunityPage(library: InputLibrary, profile: String, initialRole: InputRole,
internal fun InputCommunityPage(library: InputLibrary, profile: String, initialRole: InputRole, initialEntries: List<CommunityControls.Entry>? = null,
onInstalled: (InputLibrary) -> Unit) {
val context = LocalContext.current
var targetProfile by remember { mutableStateOf(profile) }
@@ -33,19 +33,27 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
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 entries by remember { mutableStateOf(initialEntries ?: CommunityControls.bundled(context)) }
var busy by remember { mutableStateOf(false) }
var status by remember { mutableStateOf<String?>(null) }
var pending by remember { mutableStateOf<CommunityControls.Pack?>(null) }
var exporting by remember { mutableStateOf<ByteArray?>(null) }
var search by remember { mutableStateOf("") }
val previews = remember { mutableStateMapOf<String, android.graphics.Bitmap>() }
DisposableEffect(Unit) { onDispose { previews.values.forEach { it.recycle() } } }
LaunchedEffect(entries) {
for (entry in entries) {
val filtered = remember(entries, search, role) { entries.filter { it.screen.supports(role) &&
(search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, ignoreCase = true)) } }
var page by remember(selectedSource.id, entries, search, role) { mutableIntStateOf(0) }
val pageCount = ((filtered.size + 11) / 12).coerceAtLeast(1)
val pageEntries = filtered.drop(page * 12).take(12)
val previews = remember(selectedSource.id, pageEntries) { mutableStateMapOf<String, android.graphics.Bitmap>() }
DisposableEffect(previews, selectedSource.id, pageEntries) { onDispose { previews.values.forEach { it.recycle() } } }
LaunchedEffect(previews, pageEntries) {
for (entry in pageEntries) {
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.key] = bitmap
var decoded: android.graphics.Bitmap? = null
try {
withContext(Dispatchers.IO) { decoded = runCatching { CommunityControls.preview(context, entry) }.getOrNull() }
decoded?.let { previews[entry.key] = it; decoded = null }
} finally { decoded?.recycle() }
}
}
fun task(action: suspend () -> Unit) {
@@ -70,10 +78,8 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
if (uri != null) task {
pending = withContext(Dispatchers.IO) {
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")
}
CommunityControls.importFile(context, bytes, requireNotNull(library.layout(targetProfile, role)),
library.preset(library.profile(targetProfile).binding(role)))
}
}
}
@@ -116,8 +122,7 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
SettingsGroup(stringResource(R.string.community_title)) {
OutlinedTextField(search, { search = it.take(160) }, singleLine = true,
label = { Text(stringResource(R.string.community_search)) }, modifier = Modifier.fillMaxWidth().padding(12.dp))
for (entry in entries.filter { it.screen.supports(role) &&
(search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, ignoreCase = true)) }) {
for (entry in pageEntries) {
InputNavigationRow(entry.name, listOf(entry.author, entry.game, entry.license).filter { it.isNotEmpty() }.joinToString(" · "),
Modifier.testTag("community-pack-${entry.path}"), leading = {
previews[entry.key]?.let { Image(it.asImageBitmap(), null, Modifier.width(112.dp).height(76.dp).testTag("community-preview-${entry.path}"), contentScale = ContentScale.Fit) }
@@ -126,7 +131,12 @@ internal fun InputCommunityPage(library: InputLibrary, profile: String, initialR
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)) })
if (pageCount > 1) Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween) {
PadTextButton(enabled = page > 0 && !busy, onClick = { page-- }, modifier = Modifier.testTag("community-previous")) { Text(stringResource(R.string.community_previous)) }
Text(stringResource(R.string.community_page, page + 1, pageCount), Modifier.align(androidx.compose.ui.Alignment.CenterVertically))
PadTextButton(enabled = page + 1 < pageCount && !busy, onClick = { page++ }, modifier = Modifier.testTag("community-next")) { Text(stringResource(R.string.community_next)) }
}
if (filtered.isEmpty())
InputHint(stringResource(R.string.community_empty))
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")) },
@@ -28,4 +28,7 @@
<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>
<string name="community_previous">Previous</string>
<string name="community_next">Next</string>
<string name="community_page">Page %1$d of %2$d</string>
</resources>
@@ -62,6 +62,25 @@ class ArmsControlSkinsTest {
assertEquals(4, imported.images.size)
assertEquals(old.bindings.elements, imported.bindings.elements)
}
@Test fun partialStickSkinsKeepExistingBaseOrThumbArtwork() {
val old = base()
val full = ArmsControlSkins.parse(context, zip("analog_base.png" to png(Color.RED),
"analog_stick.png" to png(Color.GREEN)), old.layout, old.bindings, "Full skin")
val library = CommunityControls.install(context, full, InputProfile.GAME, InputRole.PRIMARY)
val layout = library.layout(InputProfile.GAME, InputRole.PRIMARY)!!
val bindings = library.preset(library.profile(InputProfile.GAME).binding(InputRole.PRIMARY))
val original = layout.elements.first { it.id == "left-stick" }
for (thumbOnly in listOf(true, false)) {
val key = if (thumbOnly) "analog_stick.png" else "analog_base.png"
val partial = ArmsControlSkins.parse(context, zip(key to png(Color.BLUE)), layout, bindings, "Partial skin")
val element = partial.layout.elements.first { it.id == "left-stick" }
val retained = if (thumbOnly) original.image else original.stickImage
assertEquals(retained, if (thumbOnly) element.image else element.stickImage)
assertArrayEquals(InputButtonImages.file(context, retained)!!.readBytes(), partial.images.getValue(retained))
assertEquals(bindings.elements, partial.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")
@@ -99,6 +99,16 @@ class CommunityControlsTest {
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
}
@Test fun importingInvalidNativePackPreservesItsOriginalError() {
val doc = manifest()
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "missing.png")
val old = CommunityControls.parse(context, starter())
val error = assertThrows(IllegalArgumentException::class.java) {
CommunityControls.importFile(context, archive("controls.json" to doc.toString().toByteArray()), old.layout, old.bindings)
}
assertEquals("Missing or unexpected button images.", error.message)
}
@Test fun rejectsCorruptImages() {
val doc = manifest()
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "invalid.png")
@@ -116,7 +126,9 @@ class CommunityControlsTest {
assertTrue(entries.isNotEmpty())
entries.forEach {
assertEquals(it.name, CommunityControls.download(context, it).layout.name)
assertNotNull(CommunityControls.preview(context, it))
val preview = requireNotNull(CommunityControls.preview(context, it))
assertTrue(maxOf(preview.width, preview.height) <= 256)
preview.recycle()
}
rejects { CommunityControls.download(context, entries.first().copy(sha256 = "0".repeat(64))) }
val doc = JSONObject(context.assets.open("community-controls/catalog.json").bufferedReader().use { it.readText() })
@@ -5,6 +5,10 @@ import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.Modifier
import androidx.compose.material3.Surface
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalView
@@ -63,6 +67,24 @@ class InputCommunityPageTest {
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
compose.onNodeWithText(context.getString(R.string.community_submit)).performScrollTo().assertIsDisplayed()
}
@Test fun largeCatalogIsPagedAndSearchResetsToMatchingResults() {
val library = InputLibraries.read(context)
val starter = CommunityControls.bundled(context).first()
val entries = (1..25).map { starter.copy(name = "Pack $it", path = "packs/pack-$it.ddcontrols.zip", preview = null) }
compose.setContent { DroidDeckTheme { Column(Modifier.verticalScroll(rememberScrollState())) {
InputCommunityPage(library, InputProfile.GAME, InputRole.PRIMARY, initialEntries = entries, onInstalled = {})
} } }
compose.onNodeWithText("Pack 1").assertExists()
compose.onNodeWithText("Pack 13").assertDoesNotExist()
compose.onNodeWithTag("community-next").performScrollTo().performClick()
compose.onNodeWithText("Pack 13").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Pack 1").assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.community_search)).performScrollTo().performTextInput("Pack 25")
compose.onNodeWithTag("community-pack-packs/pack-25.ddcontrols.zip").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("community-next").assertDoesNotExist()
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
}
@Test fun starterPreviewUsesTheSameRendererAsInstalledControls() {
val bytes = context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() }
val pack = CommunityControls.parse(context, bytes)
+1 -1
View File
@@ -4,7 +4,7 @@ Controller settings → Community controls browses source catalogs and imports o
## Sources and sharing
The Source selector includes DroidDeck and [bagasromadon/ARMSX2-CustomControllerSkins](https://github.com/bagasromadon/ARMSX2-CustomControllerSkins). **Connect another source** accepts a public GitHub repository URL, a GitHub manifest file link, or a direct HTTPS catalog URL. Repository URLs try `main/catalog.json`, then `main/manifest.json`; use a file URL for another branch or a catalog in a subdirectory. Connected sources persist locally and can be removed. Native manifests use `controls`; ARMSX2 manifests use `skins`. Relative paths stay within the manifest directory, with spaces encoded when downloading. No account credentials are stored in DroidDeck.
The Source selector includes DroidDeck and [bagasromadon/ARMSX2-CustomControllerSkins](https://github.com/bagasromadon/ARMSX2-CustomControllerSkins). **Connect another source** accepts a public GitHub repository URL, a GitHub manifest file link, or a direct HTTPS catalog URL. Repository URLs try `main/catalog.json`, then `main/manifest.json`; use a file URL for another branch or a catalog in a subdirectory. Connected sources persist locally and can be removed. Results are filtered before pagination, with at most 12 entries and their previews loaded per page. Previews are sampled to at most 256 pixels and released when changing page, filters, or source. Native manifests use `controls`; ARMSX2 manifests use `skins`. Relative paths stay within the manifest directory, with spaces encoded when downloading. No account credentials are stored in DroidDeck.
**Export this layout and actions** creates a portable DroidDeck pack. **Export skin artwork** creates an ARMSX2-compatible PNG-only ZIP when the selected layout has suitable artwork. Share either ZIP directly, or use **Open source submissions** to visit the selected source's issue page and attach it there. GitHub requires an account. Source owners manage submissions and publication; the app does not automatically publish uploads. For other HTTPS hosts, the button opens the catalog URL; use that host's own upload process. A native controls pack includes layouts and bindings, while an artwork ZIP includes only controller images.