mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 13:26:02 +00:00
feat: add community on-screen controls
This commit is contained in:
1 parent
15baa296bb
commit
8276b29b7d
23 files changed
+790
-17
No files matched your search
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"controls": [
|
||||
{
|
||||
"name": "Compact gamepad",
|
||||
"author": "DroidDeck",
|
||||
"game": "",
|
||||
"license": "GPL-3.0",
|
||||
"file": "packs/compact-gamepad.ddcontrols.zip",
|
||||
"sha256": "8b747e86268a1f607e312f2c39dd67402658bd5cf9e4e4ff524a4640417c9f3e",
|
||||
"screen": "BOTH",
|
||||
"preview": "previews/compact-gamepad.png"
|
||||
}
|
||||
]
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
@@ -278,7 +278,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
|
||||
private lateinit var touchscreenGestures: TouchscreenGestures
|
||||
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
|
||||
private var gestureGame: String? = null
|
||||
private var gestureGame by mutableStateOf<String?>(null)
|
||||
private var gameStarts by mutableIntStateOf(0)
|
||||
private var gestureSettingsOpen by mutableStateOf(false)
|
||||
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
|
||||
@@ -1038,8 +1038,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
}
|
||||
if (nextGame != gestureGame) {
|
||||
if (nextGame != null) gameStarts++
|
||||
val previousControls = com.droiddeck.launcher.input.GameInputControls.profile(this@SessionActivity, inputGameScope())
|
||||
gestureGame = nextGame
|
||||
refreshGestureConfig()
|
||||
if (previousControls != com.droiddeck.launcher.input.GameInputControls.profile(this@SessionActivity, inputGameScope())) {
|
||||
releasePads()
|
||||
refreshInputProfile()
|
||||
}
|
||||
}
|
||||
if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
|
||||
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
|
||||
@@ -3542,9 +3547,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
if (started && displayId !in inputWindowDisplays && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
|
||||
}
|
||||
|
||||
fun inputGameScope(): String? =
|
||||
if (SessionState.mode == SessionService.MODE_RUN) SessionState.gameId ?: gestureGame else gestureGame
|
||||
|
||||
private fun refreshInputProfile() {
|
||||
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
|
||||
val desktop = loadingMode() == SessionService.MODE_DESKTOP
|
||||
val game = inputGameScope()
|
||||
val library = com.droiddeck.launcher.input.GameInputControls.resolve(this,
|
||||
com.droiddeck.launcher.input.InputLibraries.read(this), desktop, game)
|
||||
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
|
||||
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
|
||||
adaptiveSticks = primaryInputLayout?.adaptiveSticks
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipInputStream
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
internal object CommunityControls {
|
||||
const val MAX_BYTES = 16 * 1024 * 1024
|
||||
const val BASE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/community/controls/"
|
||||
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)
|
||||
|
||||
fun readLimited(input: InputStream, limit: Int = MAX_BYTES): ByteArray {
|
||||
val output = ByteArrayOutputStream()
|
||||
val buffer = ByteArray(8192)
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
require(output.size() + count <= limit) { "Controls file is too large." }
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
fun export(context: Context, layout: SavedInputLayout, bindings: SavedInputBindings): ByteArray {
|
||||
require(layout.editable && bindings.compatible(layout))
|
||||
val library = InputLibraries.read(context).withLayout(layout).withPreset(bindings)
|
||||
val doc = JSONObject(InputLibraries.encode(library))
|
||||
fun item(key: String, id: String): JSONObject {
|
||||
val array = doc.getJSONArray(key)
|
||||
return (0 until array.length()).map { array.getJSONObject(it) }.first { it.getString("id") == id }
|
||||
}
|
||||
val manifest = JSONObject().put("format", "droiddeck-controls").put("version", 1)
|
||||
.put("layout", item("layouts", layout.id)).put("bindings", item("bindings", bindings.id))
|
||||
val output = ByteArrayOutputStream()
|
||||
ZipOutputStream(output).use { zip ->
|
||||
fun add(name: String, bytes: ByteArray) {
|
||||
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()) {
|
||||
val file = requireNotNull(InputButtonImages.file(context, name))
|
||||
add("images/$name", file.inputStream().use { readLimited(it, 1024 * 1024) })
|
||||
}
|
||||
}
|
||||
return output.toByteArray().also { parse(context, it) }
|
||||
}
|
||||
|
||||
fun parse(context: Context, bytes: ByteArray): Pack {
|
||||
require(bytes.size <= MAX_BYTES)
|
||||
val files = linkedMapOf<String, ByteArray>()
|
||||
var total = 0
|
||||
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
|
||||
while (true) {
|
||||
val entry = zip.nextEntry ?: break
|
||||
require(!entry.isDirectory && files.size < 65 && entry.name !in files)
|
||||
require(entry.name == "controls.json" || entry.name.matches(Regex("images/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}")))
|
||||
val data = readLimited(zip, minOf(if (entry.name == "controls.json") 2_000_000 else 1024 * 1024, MAX_BYTES - total))
|
||||
total += data.size
|
||||
files[entry.name] = data
|
||||
}
|
||||
}
|
||||
val manifest = JSONObject(requireNotNull(files.remove("controls.json")).toString(Charsets.UTF_8))
|
||||
require(manifest.getString("format") == "droiddeck-controls" && manifest.getInt("version") == 1)
|
||||
val layout = manifest.getJSONObject("layout")
|
||||
val bindings = manifest.getJSONObject("bindings")
|
||||
val layoutId = newInputId()
|
||||
val bindingId = newInputId()
|
||||
layout.put("id", layoutId).remove("origin")
|
||||
require(layout.getString("template") == InputLayoutTemplate.CUSTOM.name)
|
||||
bindings.put("id", bindingId).put("layout", layoutId)
|
||||
require(!bindings.getBoolean("physical") && bindings.getJSONArray("keys").length() == 0)
|
||||
val doc = JSONObject(InputLibraries.encode(InputLibraries.read(context)))
|
||||
doc.getJSONArray("layouts").put(layout)
|
||||
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()
|
||||
require(files.keys == names.map { "images/$it" }.toSet()) { "Missing or unexpected button images." }
|
||||
var pixels = 0L
|
||||
val images = names.associateWith { name ->
|
||||
val data = files.getValue("images/$name")
|
||||
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10))
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
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)
|
||||
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size))
|
||||
bitmap.recycle()
|
||||
data
|
||||
}
|
||||
return Pack(saved, decoded.preset(bindingId), images)
|
||||
}
|
||||
|
||||
fun install(context: Context, pack: Pack, profile: String, role: InputRole): InputLibrary {
|
||||
require(pack.layout.supports(role))
|
||||
val written = mutableListOf<java.io.File>()
|
||||
try {
|
||||
val names = pack.images.mapValues { (_, bytes) ->
|
||||
val name = "key_${newInputId()}.png"
|
||||
val file = requireNotNull(InputButtonImages.file(context, name))
|
||||
file.parentFile!!.mkdirs()
|
||||
written += file
|
||||
file.writeBytes(bytes)
|
||||
name
|
||||
}
|
||||
val layout = pack.layout.copy(elements = pack.layout.elements.map { e -> e.copy(image = names[e.image] ?: "") })
|
||||
return InputLibraries.update(context) {
|
||||
it.withLayout(layout).withPreset(pack.bindings).chooseLayout(profile, role, layout.id)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
written.forEach { it.delete() }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun catalog(raw: String): List<Entry> {
|
||||
require(raw.length <= 1_000_000)
|
||||
val doc = JSONObject(raw)
|
||||
require(doc.getInt("version") == 1)
|
||||
val list = doc.getJSONArray("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")))
|
||||
})
|
||||
}.also { require(it.map { e -> e.path }.distinct().size == it.size) }
|
||||
}
|
||||
|
||||
fun bundled(context: Context): List<Entry> = context.assets.open("community-controls/catalog.json").use {
|
||||
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 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)
|
||||
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)
|
||||
}
|
||||
|
||||
fun download(context: Context, entry: Entry): Pack {
|
||||
val bytes = if (entry.bundled) context.assets.open("community-controls/${entry.path}").use { readLimited(it) }
|
||||
else get(BASE + entry.path, 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) }
|
||||
}
|
||||
|
||||
private fun get(url: String, limit: Int): ByteArray {
|
||||
val connection = URL(url).openConnection() as HttpURLConnection
|
||||
connection.connectTimeout = 15_000
|
||||
connection.readTimeout = 30_000
|
||||
connection.instanceFollowRedirects = false
|
||||
return try {
|
||||
require(connection.responseCode == 200) { "Could not download community controls (${connection.responseCode})." }
|
||||
require(connection.contentLengthLong <= limit)
|
||||
connection.inputStream.use { readLimited(it, limit) }
|
||||
} finally { connection.disconnect() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
|
||||
object GameInputControls {
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("input-game-controls", Context.MODE_PRIVATE)
|
||||
fun profile(context: Context, game: String?): String? = game?.let { prefs(context).getString(it, null) }
|
||||
fun set(context: Context, game: String, profile: String?) {
|
||||
require(game.isNotBlank() && game.length <= 512)
|
||||
require(profile == null || InputLibraries.read(context).profiles.any { it.id == profile })
|
||||
val edit = prefs(context).edit()
|
||||
if (profile == null) edit.remove(game) else edit.putString(game, profile)
|
||||
check(edit.commit()) { "Could not save game controls." }
|
||||
}
|
||||
fun resolve(context: Context, library: InputLibrary, desktop: Boolean, game: String?): InputLibrary {
|
||||
val selection = library.selection(desktop)
|
||||
if (game == null || selection.profile != InputProfiles.AUTO) return library
|
||||
val target = profile(context, game)?.let { id -> library.profiles.firstOrNull { it.id == id } } ?: return library
|
||||
var result = library
|
||||
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) {
|
||||
if (role !in selection.parts) result = result.selectPart(desktop, role, target.binding(role))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ object GameProfileManager {
|
||||
}
|
||||
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
|
||||
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
|
||||
clear("on-screen controls") { com.droiddeck.launcher.input.GameInputControls.set(context, scope, null) }
|
||||
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
|
||||
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
|
||||
|
||||
|
||||
@@ -840,6 +840,9 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
val ready = current != null && !state.saving
|
||||
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
|
||||
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) = state.save(change)
|
||||
val inputLibrary = remember(host.open) { com.droiddeck.launcher.input.InputLibraries.read(appContext) }
|
||||
var controlsProfile by remember(scope) { mutableStateOf(com.droiddeck.launcher.input.GameInputControls.profile(appContext, scope)) }
|
||||
val controlsKey = "game-settings-controls"
|
||||
val key = GAME_SETTINGS_MENU
|
||||
val fexKey = "game-settings-fex"
|
||||
val syncKey = "game-settings-sync"
|
||||
@@ -882,10 +885,13 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
|
||||
) { host.open = syncKey }
|
||||
}
|
||||
MenuItem(stringResource(R.string.community_game_controls), checked = false,
|
||||
detail = inputLibrary.profiles.firstOrNull { it.id == controlsProfile }?.name ?: useDefault) { host.open = controlsKey }
|
||||
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
|
||||
detail = stringResource(R.string.game_settings_default_detail)) {
|
||||
save {
|
||||
val failure = runCatching { com.droiddeck.launcher.session.GameProfileManager.reset(it, scope) }.exceptionOrNull()
|
||||
if (failure == null) controlsProfile = null
|
||||
com.droiddeck.launcher.stores.StoresState.post {
|
||||
android.widget.Toast.makeText(
|
||||
it,
|
||||
@@ -897,6 +903,20 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
}
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == controlsKey, onDismiss = { if (host.open == controlsKey) host.open = null },
|
||||
title = stringResource(R.string.community_game_controls)) { first ->
|
||||
MenuItem(useDefault, checked = controlsProfile == null, focusRequester = first) {
|
||||
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, null) }
|
||||
.onSuccess { controlsProfile = null; host.open = key }
|
||||
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}
|
||||
for (profile in inputLibrary.profiles) MenuItem(profile.name, checked = profile.id == controlsProfile,
|
||||
detail = stringResource(R.string.community_game_controls_hint)) {
|
||||
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, profile.id) }
|
||||
.onSuccess { controlsProfile = profile.id; host.open = key }
|
||||
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
|
||||
}
|
||||
}
|
||||
AnchoredMenu(host.open == fexKey, onDismiss = { if (host.open == fexKey) host.open = null }, title = stringResource(R.string.fex_preset_title)) { first ->
|
||||
MenuItem(useDefault, checked = fex == null, enabled = ready, detail = stringResource(generalFex.label), focusRequester = first) {
|
||||
host.open = key
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@Composable
|
||||
internal fun InputCommunityPage(library: InputLibrary, profile: String, initialRole: InputRole,
|
||||
onInstalled: (InputLibrary) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var targetProfile by remember { mutableStateOf(profile) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val host = rememberMenuHost()
|
||||
var role by remember { mutableStateOf(initialRole.takeUnless { it == InputRole.PHYSICAL } ?: InputRole.PRIMARY) }
|
||||
var entries by remember { mutableStateOf(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) {
|
||||
if (entry.preview == null || entry.path in previews) continue
|
||||
val bitmap = withContext(Dispatchers.IO) { runCatching { CommunityControls.preview(context, entry) }.getOrNull() }
|
||||
if (bitmap != null) previews[entry.path] = bitmap
|
||||
}
|
||||
}
|
||||
fun task(action: suspend () -> Unit) {
|
||||
if (busy) return
|
||||
busy = true
|
||||
status = null
|
||||
scope.launch {
|
||||
try { action() } catch (e: kotlinx.coroutines.CancellationException) { throw e }
|
||||
catch (e: Exception) { status = e.message ?: context.getString(R.string.community_failed) }
|
||||
finally { busy = false }
|
||||
}
|
||||
}
|
||||
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 exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
|
||||
val bytes = exporting
|
||||
exporting = null
|
||||
if (uri != null && bytes != null) task {
|
||||
withContext(Dispatchers.IO) {
|
||||
requireNotNull(context.contentResolver.openOutputStream(uri, "wt")).use { it.write(bytes) }
|
||||
}
|
||||
status = context.getString(R.string.community_exported)
|
||||
}
|
||||
}
|
||||
InputHint(stringResource(R.string.community_description))
|
||||
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,
|
||||
listOf(InputRole.PRIMARY, InputRole.SECONDARY).map { it to roleLabel(it) }, role) { if (!busy) role = it }
|
||||
}
|
||||
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)) }) {
|
||||
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) }
|
||||
}) {
|
||||
task { pending = withContext(Dispatchers.IO) { CommunityControls.download(context, entry) } }
|
||||
}
|
||||
}
|
||||
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 = { 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)) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.community_share)) {
|
||||
InputHint(stringResource(R.string.community_submit_hint))
|
||||
val layout = library.layout(targetProfile, role)
|
||||
if (layout?.editable == true) PadTextButton(enabled = !busy, onClick = { task {
|
||||
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)) }
|
||||
PadTextButton(onClick = {
|
||||
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(CommunityControls.SUBMIT))) }
|
||||
.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) }
|
||||
pending?.let { pack ->
|
||||
AlertDialog(onDismissRequest = { if (!busy) pending = null }, title = { Text(pack.layout.name) },
|
||||
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
InputLayoutThumbnail(pack.layout, role, pack.images, Modifier.fillMaxWidth().height(180.dp))
|
||||
Text(stringResource(R.string.community_apply_hint, pack.layout.elements.size, library.profile(targetProfile).name, roleLabel(role)))
|
||||
} }, confirmButton = {
|
||||
PadTextButton(enabled = !busy && pack.layout.supports(role), onClick = { task {
|
||||
val installed = withContext(Dispatchers.IO) { CommunityControls.install(context, pack, targetProfile, role) }
|
||||
onInstalled(installed)
|
||||
pending = null
|
||||
status = context.getString(R.string.community_installed)
|
||||
} }) { Text(stringResource(R.string.community_apply)) }
|
||||
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { pending = null }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
}
|
||||
@@ -36,13 +36,18 @@ internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: S
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
|
||||
update = { it.update(layout, role) })
|
||||
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole, images: Map<String, ByteArray> = emptyMap(),
|
||||
modifier: Modifier = Modifier.width(112.dp).height(76.dp)) {
|
||||
val bitmaps = remember(images) { images.mapValues { (_, bytes) -> android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } }
|
||||
DisposableEffect(bitmaps) { onDispose { bitmaps.values.forEach { it?.recycle() } } }
|
||||
key(bitmaps) {
|
||||
AndroidView(factory = { InputLayoutPreviewView(it, bitmaps.filterValues { it != null }.mapValues { it.value!! }) },
|
||||
modifier = modifier.testTag("layout-preview-${layout.id}"), update = { it.update(layout, role) })
|
||||
}
|
||||
}
|
||||
|
||||
internal class InputLayoutPreviewView(context: Context) : View(context) {
|
||||
private val renderer = InputSurfaceView(context)
|
||||
internal class InputLayoutPreviewView(context: Context, images: Map<String, android.graphics.Bitmap> = emptyMap()) : View(context) {
|
||||
private val renderer = InputSurfaceView(context, previewImages = images)
|
||||
private var sourceHeight = 563
|
||||
fun update(layout: SavedInputLayout, role: InputRole) {
|
||||
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
|
||||
|
||||
@@ -33,7 +33,10 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) }
|
||||
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
|
||||
}
|
||||
val selection = library.selection(desktop)
|
||||
val game = (context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputGameScope()
|
||||
fun effective(value: InputLibrary) = GameInputControls.resolve(context, value, desktop, game)
|
||||
val resolved = effective(library)
|
||||
val selection = resolved.selection(desktop)
|
||||
val mixed = selection.parts.isNotEmpty()
|
||||
val active = library.profile(library.activeId(desktop))
|
||||
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) +
|
||||
@@ -61,7 +64,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
if (role == InputRole.PHYSICAL) binding.physical
|
||||
else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) }
|
||||
}.map { it.id to it.name }
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings,
|
||||
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, resolved.activePart(desktop, role).bindings,
|
||||
chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } }
|
||||
}
|
||||
if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true }
|
||||
@@ -73,7 +76,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
|
||||
var name by remember { mutableStateOf("") }
|
||||
AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) },
|
||||
text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) },
|
||||
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { effective(it).saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
|
||||
dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } })
|
||||
}
|
||||
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
|
||||
|
||||
@@ -65,7 +65,7 @@ private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE }
|
||||
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE, COMMUNITY }
|
||||
private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false)
|
||||
private data class InputNameRequest(val title: Int, val initial: String, val sources: List<Pair<String, String>> = emptyList(),
|
||||
val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit)
|
||||
@@ -85,6 +85,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
val host = rememberMenuHost()
|
||||
var library by remember { mutableStateOf(InputLibraries.read(context)) }
|
||||
var page by remember { mutableStateOf(InputPage.HOME) }
|
||||
var communityBack by remember { mutableStateOf(InputPage.HOME) }
|
||||
var bindingsTab by remember { mutableIntStateOf(0) }
|
||||
var profileId by remember { mutableStateOf(InputProfile.GAME) }
|
||||
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
|
||||
@@ -104,12 +105,13 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
|
||||
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
|
||||
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
|
||||
fun go(next: InputPage) { page = next; host.open = null }
|
||||
fun go(next: InputPage) { if (next == InputPage.COMMUNITY) communityBack = page; page = next; host.open = null }
|
||||
fun back() {
|
||||
when {
|
||||
edit != null -> edit = null
|
||||
page == InputPage.HOME -> onBack()
|
||||
page == InputPage.PROFILE -> go(InputPage.HOME)
|
||||
page == InputPage.COMMUNITY -> go(communityBack)
|
||||
page == InputPage.SOURCE -> go(InputPage.PROFILE)
|
||||
else -> go(InputPage.SOURCE)
|
||||
}
|
||||
@@ -191,6 +193,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
InputPage.SOURCE -> roleLabel(role)
|
||||
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
|
||||
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
|
||||
InputPage.COMMUNITY -> stringResource(R.string.community_title)
|
||||
}, eyebrow = when (page) {
|
||||
InputPage.SOURCE -> profile.name
|
||||
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
|
||||
@@ -198,7 +201,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
},
|
||||
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
|
||||
when (page) {
|
||||
InputPage.COMMUNITY -> InputCommunityPage(library, profileId, role) { installed -> library = installed; onChanged() }
|
||||
InputPage.HOME -> {
|
||||
SettingsGroup(stringResource(R.string.community_title)) {
|
||||
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint),
|
||||
Modifier.testTag("input-community")) { go(InputPage.COMMUNITY) }
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_default_profiles)) {
|
||||
ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null,
|
||||
library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } }
|
||||
@@ -284,6 +292,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
|
||||
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
|
||||
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
|
||||
}
|
||||
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint)) { go(InputPage.COMMUNITY) }
|
||||
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.input_assign_actions)) {
|
||||
@@ -449,7 +458,7 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List<InputCo
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
internal fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
|
||||
Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
leading?.invoke()
|
||||
@@ -499,6 +508,6 @@ internal fun roleLabel(role: InputRole) = stringResource(when (role) {
|
||||
})
|
||||
|
||||
@Composable
|
||||
private fun InputHint(text: String) {
|
||||
internal fun InputHint(text: String) {
|
||||
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
@@ -51,6 +51,7 @@ class InputSurfaceView(
|
||||
private val inputRole: InputRole = InputRole.SECONDARY,
|
||||
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
|
||||
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
|
||||
private val previewImages: Map<String, android.graphics.Bitmap> = emptyMap(),
|
||||
) : FrameLayout(context) {
|
||||
private val content = FrameLayout(context)
|
||||
private val elementSources = ArrayList<InputSurfaceSource>()
|
||||
@@ -332,7 +333,7 @@ class InputSurfaceView(
|
||||
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 = InputButtonImages.file(context, element.image)?.let { file ->
|
||||
private val bitmap = previewImages[element.image] ?: InputButtonImages.file(context, element.image)?.let { file ->
|
||||
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, size)
|
||||
val options = BitmapFactory.Options().apply {
|
||||
|
||||
@@ -306,8 +306,12 @@ class SecondScreenPresentation(
|
||||
}
|
||||
}
|
||||
|
||||
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
|
||||
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
|
||||
private fun panelLayout(mode: SecondScreenMode): com.droiddeck.launcher.input.SavedInputLayout? {
|
||||
val desktop = SessionState.mode == SessionService.MODE_DESKTOP
|
||||
return com.droiddeck.launcher.input.GameInputControls.resolve(context,
|
||||
com.droiddeck.launcher.input.InputLibraries.read(context), desktop, sessionActivity.inputGameScope())
|
||||
.panelLayout(desktop, mode.panel(context))
|
||||
}
|
||||
|
||||
private fun bar(mode: SecondScreenMode) {
|
||||
val first = barModel(mode) ?: return
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<resources>
|
||||
<string name="community_title">Community controls</string>
|
||||
<string name="community_home_hint">Browse, import, and share on-screen controls</string>
|
||||
<string name="community_description">Discover controls made by the community. Packs include button artwork, layout, and actions. Review a pack before applying it to a profile.</string>
|
||||
<string name="community_target">Apply to</string>
|
||||
<string name="community_search">Search name, author, or game</string>
|
||||
<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_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_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>
|
||||
<string name="community_installed">Controls installed and selected for this profile.</string>
|
||||
<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>
|
||||
</resources>
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import org.json.JSONObject
|
||||
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 java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipInputStream
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class CommunityControlsTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private fun starter() = context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() }
|
||||
@Before fun reset() {
|
||||
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
private fun archive(vararg entries: Pair<String, ByteArray>): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
ZipOutputStream(out).use { zip -> entries.forEach { (name, data) ->
|
||||
zip.putNextEntry(ZipEntry(name)); zip.write(data); zip.closeEntry()
|
||||
} }
|
||||
return out.toByteArray()
|
||||
}
|
||||
private fun manifest(): JSONObject = ZipInputStream(ByteArrayInputStream(starter())).use {
|
||||
it.nextEntry; JSONObject(it.readBytes().toString(Charsets.UTF_8))
|
||||
}
|
||||
private fun rejects(action: () -> Unit) {
|
||||
try { action(); fail("Expected rejected controls") } catch (_: IllegalArgumentException) { }
|
||||
}
|
||||
|
||||
@Test fun starterInstallsIndependentNativeGamepadWithoutChangingOtherParts() {
|
||||
val original = InputLibraries.read(context)
|
||||
val pack = CommunityControls.parse(context, starter())
|
||||
val second = CommunityControls.parse(context, starter())
|
||||
assertNotEquals(pack.layout.id, second.layout.id)
|
||||
assertNotEquals(pack.bindings.id, second.bindings.id)
|
||||
val changed = CommunityControls.install(context, pack, InputProfile.GAME, InputRole.PRIMARY)
|
||||
assertEquals(pack.layout, changed.layout(InputProfile.GAME, InputRole.PRIMARY))
|
||||
assertEquals(InputAction.Native(InputControl.A), changed.preset(changed.profile(InputProfile.GAME).binding(InputRole.PRIMARY)).elements["a"])
|
||||
assertEquals(original.profile(InputProfile.DESKTOP), changed.profile(InputProfile.DESKTOP))
|
||||
assertEquals(original.profile(InputProfile.GAME).parts[InputRole.PHYSICAL], changed.profile(InputProfile.GAME).parts[InputRole.PHYSICAL])
|
||||
assertEquals(original.profile(InputProfile.GAME).parts[InputRole.SECONDARY], changed.profile(InputProfile.GAME).parts[InputRole.SECONDARY])
|
||||
assertEquals(changed, InputLibraries.read(context))
|
||||
}
|
||||
|
||||
@Test fun packRoundTripPreservesImagesStyleActionsAndClicks() {
|
||||
val base = CommunityControls.parse(context, starter())
|
||||
val imageName = "roundtrip.png"
|
||||
val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)
|
||||
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()
|
||||
bitmap.recycle()
|
||||
val layout = base.layout.copy(elements = base.layout.elements.map { if (it.id == "a") it.copy(image = imageName, showLabel = false, toggle = true) else it })
|
||||
val bindings = base.bindings.copy(elements = base.bindings.elements + ("a" to InputAction.Keys(listOf(29, 30))),
|
||||
clicks = mapOf("left-stick" to InputAction.MouseButton(272)))
|
||||
val installed = CommunityControls.install(context, CommunityControls.Pack(layout, bindings, mapOf(imageName to png)), InputProfile.GAME, InputRole.PRIMARY)
|
||||
val saved = installed.layout(InputProfile.GAME, InputRole.PRIMARY)!!
|
||||
val exported = CommunityControls.export(context, saved, installed.preset(installed.profile(InputProfile.GAME).binding(InputRole.PRIMARY)))
|
||||
val imported = CommunityControls.parse(context, exported)
|
||||
assertEquals(saved.copy(id = imported.layout.id), imported.layout)
|
||||
assertEquals(bindings.elements, imported.bindings.elements)
|
||||
assertEquals(bindings.clicks, imported.bindings.clicks)
|
||||
assertArrayEquals(png, imported.images.values.single())
|
||||
assertNotEquals(imageName, saved.elements.first { it.id == "a" }.image)
|
||||
}
|
||||
|
||||
@Test fun parserDoesNotChangePreferences() {
|
||||
val before = InputLibraries.read(context)
|
||||
CommunityControls.parse(context, starter())
|
||||
assertEquals(before, InputLibraries.read(context))
|
||||
}
|
||||
|
||||
@Test fun rejectsTraversalAndUnexpectedEntries() {
|
||||
rejects { CommunityControls.parse(context, archive("../controls.json" to byteArrayOf())) }
|
||||
rejects { CommunityControls.parse(context, archive("images/../x.png" to byteArrayOf())) }
|
||||
rejects { CommunityControls.parse(context, archive("unrelated" to byteArrayOf())) }
|
||||
}
|
||||
|
||||
@Test fun rejectsMissingAndUnreferencedImages() {
|
||||
val doc = manifest()
|
||||
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "missing.png")
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to manifest().toString().toByteArray(), "images/unused.png" to byteArrayOf())) }
|
||||
}
|
||||
|
||||
@Test fun rejectsFutureFormatsAndInvalidActions() {
|
||||
val doc = manifest().put("version", 99)
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
|
||||
doc.put("version", 1).getJSONObject("bindings").getJSONObject("elements").put("a", JSONObject().put("type", "shell").put("command", "bad"))
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
|
||||
}
|
||||
|
||||
@Test fun rejectsCorruptImages() {
|
||||
val doc = manifest()
|
||||
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "invalid.png")
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray(), "images/invalid.png" to byteArrayOf(0, 1, 2))) }
|
||||
}
|
||||
|
||||
@Test fun boundedReaderRejectsOversizeBeforeBufferingAllInput() {
|
||||
rejects { CommunityControls.readLimited(ByteArrayInputStream(ByteArray(8192)), 16) }
|
||||
assertEquals(16, CommunityControls.readLimited(ByteArrayInputStream(ByteArray(16)), 16).size)
|
||||
rejects { CommunityControls.parse(context, archive("controls.json" to ByteArray(2_000_001))) }
|
||||
}
|
||||
|
||||
@Test fun bundledCatalogMatchesPackAndRejectsExternalPaths() {
|
||||
val entries = CommunityControls.bundled(context)
|
||||
assertTrue(entries.isNotEmpty())
|
||||
entries.forEach {
|
||||
assertEquals(it.name, CommunityControls.download(context, it).layout.name)
|
||||
assertNotNull(CommunityControls.preview(context, it))
|
||||
}
|
||||
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() })
|
||||
doc.getJSONArray("controls").getJSONObject(0).put("file", "https://example.com/pack.zip")
|
||||
rejects { CommunityControls.catalog(doc.toString()) }
|
||||
doc.getJSONArray("controls").getJSONObject(0).put("file", "packs/../../other.ddcontrols.zip")
|
||||
rejects { CommunityControls.catalog(doc.toString()) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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 GameInputControlsTest {
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
@Before fun reset() {
|
||||
for (name in listOf("input-profiles", "input-game-controls"))
|
||||
context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
private fun library(): InputLibrary {
|
||||
val result = InputLibraries.update(context) { it.duplicateProfile(InputProfile.GAME, "My game", "my-game") }
|
||||
GameInputControls.set(context, "42", "my-game")
|
||||
return result
|
||||
}
|
||||
@Test fun gameOverridesOnlyScreenPartsAndRestoresGeneralControlsOnExit() {
|
||||
val original = library()
|
||||
val game = GameInputControls.resolve(context, original, false, "42")
|
||||
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY))
|
||||
assertEquals(original.profile("my-game").binding(role), game.activePart(false, role).bindings)
|
||||
assertEquals(original.activePart(false, InputRole.PHYSICAL), game.activePart(false, InputRole.PHYSICAL))
|
||||
assertEquals(original, GameInputControls.resolve(context, original, false, null))
|
||||
assertEquals(original, GameInputControls.resolve(context, original, false, "43"))
|
||||
assertEquals(original, InputLibraries.read(context))
|
||||
}
|
||||
@Test fun manualProfileAndScreenChoicesTakePriority() {
|
||||
val original = library()
|
||||
val manual = original.selectProfile(false, InputProfile.DESKTOP)
|
||||
assertEquals(manual, GameInputControls.resolve(context, manual, false, "42"))
|
||||
val role = InputRole.PRIMARY
|
||||
val chosen = original.profile(InputProfile.DESKTOP).binding(role)
|
||||
val mixed = original.selectPart(false, role, chosen)
|
||||
val effective = GameInputControls.resolve(context, mixed, false, "42")
|
||||
assertEquals(chosen, effective.activePart(false, role).bindings)
|
||||
assertEquals(original.profile("my-game").binding(InputRole.SECONDARY), effective.activePart(false, InputRole.SECONDARY).bindings)
|
||||
}
|
||||
@Test fun gameResetClearsOnlyTheSelectedControlsMapping() {
|
||||
library()
|
||||
GameInputControls.set(context, "43", InputProfile.DESKTOP)
|
||||
com.droiddeck.launcher.session.GameProfileManager.reset(context, "42")
|
||||
assertNull(GameInputControls.profile(context, "42"))
|
||||
assertEquals(InputProfile.DESKTOP, GameInputControls.profile(context, "43"))
|
||||
}
|
||||
@Test fun deletedProfileAndClearedOverridesFallBackToGeneral() {
|
||||
val original = library()
|
||||
val removed = original.removeProfile("my-game")
|
||||
assertEquals(removed, GameInputControls.resolve(context, removed, false, "42"))
|
||||
GameInputControls.set(context, "42", null)
|
||||
assertNull(GameInputControls.profile(context, "42"))
|
||||
assertEquals(original, GameInputControls.resolve(context, original, false, "42"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.view.View
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.input.*
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
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.File
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28], qualifiers = "w1000dp-h900dp")
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
class InputCommunityPageTest {
|
||||
@get:Rule val compose = createRobolectricComposeRule()
|
||||
private val context get() = RuntimeEnvironment.getApplication()
|
||||
private lateinit var root: View
|
||||
@Before fun reset() {
|
||||
for (name in listOf("input-profiles", "input-surfaces", "controller", "input-game-controls"))
|
||||
context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
|
||||
}
|
||||
private fun open() {
|
||||
compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { BoxWithConstraints {
|
||||
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < 600.dp)) { InputSettingsPage({}) }
|
||||
} } } }
|
||||
compose.onNodeWithTag("input-community").performScrollTo().performClick()
|
||||
}
|
||||
@Test fun communityRequiresReviewBeforeApplyingAndPreservesOtherProfiles() {
|
||||
val before = InputLibraries.read(context)
|
||||
open()
|
||||
compose.onNodeWithText("Compact gamepad").performScrollTo().performClick()
|
||||
compose.waitUntil(10_000) { compose.onAllNodesWithText(context.getString(R.string.community_apply)).fetchSemanticsNodes().isNotEmpty() }
|
||||
assertEquals(before, InputLibraries.read(context))
|
||||
screenshot("community-review", org.robolectric.shadows.ShadowDialog.getLatestDialog().window!!.decorView)
|
||||
compose.onNodeWithText(context.getString(R.string.community_apply)).performClick()
|
||||
compose.waitUntil(10_000) { InputLibraries.read(context).layout(InputProfile.GAME, InputRole.PRIMARY)?.name == "Compact gamepad" }
|
||||
val after = InputLibraries.read(context)
|
||||
assertEquals(before.profile(InputProfile.DESKTOP), after.profile(InputProfile.DESKTOP))
|
||||
compose.onNodeWithText(context.getString(R.string.community_export)).performScrollTo().assertIsDisplayed()
|
||||
}
|
||||
@Test @Config(qualifiers = "w360dp-h800dp")
|
||||
fun phoneCanBrowseSearchAndReachImportAndSubmission() {
|
||||
open()
|
||||
compose.waitUntil(10_000) { compose.onAllNodesWithTag("community-preview-packs/compact-gamepad.ddcontrols.zip", useUnmergedTree = true).fetchSemanticsNodes().isNotEmpty() }
|
||||
screenshot("community-phone")
|
||||
compose.onNodeWithText(context.getString(R.string.community_search)).performTextInput("absent-game")
|
||||
compose.onNodeWithText(context.getString(R.string.community_empty)).performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
|
||||
compose.onNodeWithText(context.getString(R.string.community_submit)).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)
|
||||
val view = InputLayoutPreviewView(context)
|
||||
view.update(pack.layout, InputRole.PRIMARY)
|
||||
view.measure(View.MeasureSpec.makeMeasureSpec(640, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY))
|
||||
view.layout(0, 0, 640, 360)
|
||||
screenshot("compact-gamepad", view)
|
||||
}
|
||||
private fun screenshot(name: String, view: View = root) {
|
||||
compose.runOnIdle {
|
||||
val image = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
|
||||
view.draw(Canvas(image))
|
||||
val file = File("build/reports/community-controls/$name.png").apply { parentFile?.mkdirs() }
|
||||
file.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
image.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user