Preserve existing controller layout, import and role-mixing behavior

This commit is contained in:
Kurt Himebauch committed 2026-12-05 17:13:14 -05:00
1 parent 6a2ac13efe
commit cbf152bb3a
16 files changed
+358 -90

No files matched your search

@@ -4809,37 +4809,39 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun inputGameKey(): String? = bottomGameKey()
/** Opens the button binder or the on-screen layout editor on what this game uses, giving the game its own copy first when changes are for it. */
/** Opens the effective controls. Fork a per-game part only when the editor saves an actual change. */
private fun openInputEditor(role: InputRole) {
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val game = inputGameKey()?.takeUnless { SessionState.inputForAllGames }
val name = inputGameName()
val forked = game != null && runCatching { com.droiddeck.launcher.input.InputLibraries.read(this).games[game]?.parts?.containsKey(role) != true }.getOrDefault(false)
val opened = runCatching {
val library = if (game != null) com.droiddeck.launcher.input.InputLibraries.update(this) { it.withGamePart(desktop, game, name, role) }
else com.droiddeck.launcher.input.InputLibraries.read(this)
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val part = library.activePart(desktop, role, game)
val layout = part.layout?.let { id -> library.layouts.first { it.id == id } }
if (role != InputRole.PHYSICAL && layout?.editable != true) null
else com.droiddeck.launcher.ui.InputEditorTarget(role, library.activeId(desktop, game), part.bindings, part.layout,
scope = if (game != null) name else getString(R.string.flow_shared_defaults_of, com.droiddeck.launcher.ui.profileLabel(this, library.profile(library.activeId(desktop, game)))),
game = game?.takeIf { forked }, desktop = desktop)
else com.droiddeck.launcher.ui.InputEditorTarget(
role, library.activeId(desktop, game), part.bindings, part.layout,
scope = if (game != null) name else getString(R.string.flow_shared_defaults_of,
com.droiddeck.launcher.ui.profileLabel(this, library.profile(library.activeId(desktop, null)))),
gameEdit = game?.let { com.droiddeck.launcher.ui.GameInputEdit(desktop, it, name, role) },
wasInherited = game != null && library.games[game]?.parts?.containsKey(role) != true,
)
}.onFailure { Toast.makeText(this, it.message ?: getString(R.string.input_save_failed), Toast.LENGTH_LONG).show() }.getOrNull()
leaveImmersiveForDialog(); releasePads(); drawerOpen = false
inputEditor = opened
inputSettingsOpen = true
if (forked) refreshInputProfile()
}
private fun closeInputEditor() {
val target = inputEditor
inputSettingsOpen = false
inputEditor = null
val game = target?.game
if (game != null) runCatching {
val edit = target?.takeIf { it.wasInherited }?.gameEdit
if (edit != null) runCatching {
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
if (library.gameChanges(target.desktop, game, target.role) == 0)
com.droiddeck.launcher.input.InputLibraries.update(this) { it.resetGame(game, target.role) }
if (library.games[edit.game]?.parts?.containsKey(edit.role) == true &&
library.gameChanges(edit.desktop, edit.game, edit.role) == 0)
com.droiddeck.launcher.input.InputLibraries.update(this) { it.resetGame(edit.game, edit.role) }
}
releasePads()
refreshInputProfile()
@@ -113,20 +113,6 @@ object ControllerPrefs {
prefs(context).edit().putInt("onScreenOpacity", percent.coerceIn(onScreenOpacityRange)).apply()
}
fun opacityFolded(context: Context) = prefs(context).getBoolean("opacityFolded", false)
/** Multiplies the old per-layout opacity into the global one, once. False when it could not be saved. */
fun foldOpacity(context: Context, layoutPercent: Int): Boolean {
val p = prefs(context)
val before = onScreenOpacity(context)
val hadValue = p.contains("onScreenOpacity")
val folded = (before * layoutPercent / 100f).toInt().coerceIn(onScreenOpacityRange)
if (p.edit().putInt("onScreenOpacity", folded).putBoolean("opacityFolded", true).commit()) return true
// SharedPreferences keeps a failed commit's values in memory.
p.edit().apply { if (hadValue) putInt("onScreenOpacity", before) else remove("onScreenOpacity") }.remove("opacityFolded").apply()
return false
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
@@ -115,12 +115,12 @@ internal object InputLayoutFile {
else -> 4f * snap * scale
}
fun coordinate(name: String) = element.optDouble(name, .5).toFloat().takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: .5f
// A layout holds 64 controls; a file with more is refused rather than cut short.
if (keys.size == 64) return null
keys += LegacyScreenKey(codes, coordinate("x"), coordinate("y"), (sizePx / density).roundToInt().coerceIn(24, 140).toFloat(),
text = element.optString("text").trim().take(24),
opacity = element.optDouble("opacity", 1.0).toFloat().takeIf { it.isFinite() }?.coerceIn(.2f, 1f) ?: 1f,
shape = shape, toggle = element.optBoolean("toggleSwitch"))
// Preserve main's import behavior: accept the first 64 usable controls.
if (keys.size == 64) break
}
return keys
}
@@ -46,8 +46,6 @@ object InputLibraries {
if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library)
// Not tied to the version: a fold that could not be saved is tried again on the next read.
library = singleOpacity(context, library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -296,16 +294,6 @@ object InputLibraries {
return addStockLayouts(result)
}
/** Each layout used to carry its own opacity on top of the global one; the main-screen layout's share moves into the global value. */
internal fun singleOpacity(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.all { it.style.opacity == 100 }) return library
if (!ControllerPrefs.opacityFolded(context)) {
val main = runCatching { library.activeLayout(false, InputRole.PRIMARY) }.getOrNull()?.style?.opacity ?: 100
if (!ControllerPrefs.foldOpacity(context, main)) return library
}
return library.copy(layouts = library.layouts.map { it.copy(style = it.style.copy(opacity = 100)) })
}
private fun deckGamepadSurfaces(context: Context, library: InputLibrary): InputLibrary {
val leftPad = SessionPrefs.gamepadSurface(context, right = false) == SessionPrefs.SURFACE_TRACKPAD
val rightStick = SessionPrefs.gamepadSurface(context, right = true) == SessionPrefs.SURFACE_STICK
@@ -145,6 +145,14 @@ data class InputLibrary(
fun usersOfBindings(id: String) = profiles.filter { p -> p.parts.values.any { it.bindings == id } }
fun selectedBindings(id: String) = selections.values.any { id in it.parts.values } || games.values.any { g -> g.parts.values.any { it.bindings == id } }
fun usersOfLayout(id: String) = profiles.filter { p -> p.parts.values.any { it.layout == id } }
/** Game-owned editable copies are not reusable shared defaults; built-in layouts can still be used by both. */
fun isGameOwnedLayout(id: String) = layouts.any { it.id == id && it.editable } && gamesUsingLayout(id)
fun sharedLayouts(role: InputRole): List<SavedInputLayout> {
val gameLayouts = games.values.flatMap { it.parts.values }.mapNotNull { it.layout }.toSet()
return layouts.filter { it.supports(role) && !(it.editable && it.id in gameLayouts) }
}
private fun gamesUsingLayout(id: String) = games.values.any { g -> g.parts.values.any { it.layout == id } }
/** Gives [game] its own copy of the part it uses for [role], so edits made for it leave the profile alone. */
@@ -235,6 +243,7 @@ data class InputLibrary(
}
fun useLayout(profileId: String, role: InputRole, layoutId: String, shared: Boolean): InputLibrary {
require(!isGameOwnedLayout(layoutId)) { "A game-owned layout cannot be used as a shared layout" }
val source = layouts.first { it.id == layoutId }
require(source.supports(role))
val target = profile(profileId)
@@ -263,6 +272,7 @@ data class InputLibrary(
}
fun chooseLayout(profileId: String, role: InputRole, id: String): InputLibrary {
require(!isGameOwnedLayout(id)) { "A game-owned layout cannot be used as a shared layout" }
val layout = layouts.first { it.id == id }
require(layout.supports(role))
val profile = profile(profileId)
@@ -30,8 +30,9 @@ object WinlatorLayouts {
val bound = (0 until elements.length()).mapNotNull { i ->
elements.optJSONObject(i)?.let { e -> e.optString("type") to e.optJSONArray("bindings")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() }
}.filter { (type, bindings) -> type in setOf("TRACKPAD", "RANGE_BUTTON") || bindings.any { it.isNotBlank() && it != "NONE" } }
// Over 64 controls: the converter refuses the file, where the other importer would quietly keep the first 64.
bound.size > 64 || bound.any { (type, bindings) ->
// Keep existing key-only files on the compatible importer, including
// layouts exceeding the legacy 64-control cap.
bound.any { (type, bindings) ->
type in setOf("TRACKPAD", "RANGE_BUTTON") || bindings.any { it.isNotBlank() && it != "NONE" && !InputLayoutFile.knows(it) }
}
}.getOrDefault(false)
@@ -44,8 +44,8 @@ internal fun DrawerControlsGroup(host: MenuHost, a: DrawerActions, track: (Strin
var clearing by remember { mutableStateOf<Pair<String, String>?>(null) }
val game = a.inputGame
val gameScope = game != null && !forAll
fun update(change: (InputLibrary) -> InputLibrary) {
runCatching { InputLibraries.update(context, change) }.onSuccess { a.onInputSelection(null) }
fun update(role: InputRole? = null, change: (InputLibrary) -> InputLibrary) {
runCatching { InputLibraries.update(context, change) }.onSuccess { a.onInputSelection(role) }
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
val gameKey = game?.first
@@ -54,12 +54,18 @@ internal fun DrawerControlsGroup(host: MenuHost, a: DrawerActions, track: (Strin
val changes = scopeKey?.let { library.gameChanges(a.desktop, it) } ?: 0
val own = gameKey?.let { library.games[it] }
val named = library.profiles.map { it.id to profileLabel(context, it) }
// For one game the first choice follows whatever all games use; for all games the profile itself is the choice.
val profiles = if (gameScope) listOf(InputProfiles.AUTO to stringResource(R.string.flow_shared_defaults_of,
profileLabel(context, library.profile(library.activeId(a.desktop))))) + named
else listOf(InputProfiles.AUTO to stringResource(R.string.flow_default_profile, profileLabel(context, library.profile(library.defaultId(a.desktop))))) + named
val selected = if (gameScope) own?.profile ?: InputProfiles.AUTO else library.selection(a.desktop).profile
val detail = listOfNotNull(profileLabel(context, active), if (changes > 0 && game != null) stringResource(R.string.flow_game_changes, changes) else null).joinToString(" · ")
val mixedId = quickMixedChoiceId(library)
val sharedMixed = library.selection(a.desktop).parts.isNotEmpty()
val activeLabel = profileLabel(context, active)
val sharedLabel = profileLabel(context, library.profile(library.activeId(a.desktop)))
val sharedSummary = if (sharedMixed) stringResource(R.string.input_quick_mixed, sharedLabel) else sharedLabel
// The per-game choice follows or pins a whole profile; the live mix belongs to shared defaults.
val profiles = if (gameScope) listOf(InputProfiles.AUTO to stringResource(R.string.flow_shared_defaults_of, sharedSummary)) + named
else listOf(InputProfiles.AUTO to stringResource(R.string.flow_default_profile, profileLabel(context, library.profile(library.defaultId(a.desktop))))) +
named + if (sharedMixed) listOf(mixedId to sharedSummary) else emptyList()
val selected = if (gameScope) own?.profile ?: InputProfiles.AUTO else if (sharedMixed) mixedId else library.selection(a.desktop).profile
val detail = listOfNotNull(if (gameScope && own?.profile != null) activeLabel else sharedSummary,
if (changes > 0 && game != null) stringResource(R.string.flow_game_changes, changes) else null).joinToString(" · ")
SettingsGroup(stringResource(R.string.flow_controls), key = "controller-input", detail = detail) {
if (game != null) ChoiceRow(host, "input-scope", stringResource(R.string.flow_apply_to), null,
listOf(false to game.second, true to stringResource(R.string.flow_shared_defaults)), forAll, chipModifier = track("input-scope")) {
@@ -67,8 +73,9 @@ internal fun DrawerControlsGroup(host: MenuHost, a: DrawerActions, track: (Strin
}
ChoiceRow(host, "input-profile", stringResource(R.string.input_profile), null, profiles, selected, chipModifier = track("input-profile")) { id ->
if (gameScope && game != null) update { it.withGameProfile(game.first, game.second, id.takeUnless { it == InputProfiles.AUTO }) }
else update { it.selectProfile(a.desktop, id) }
else if (id != mixedId) update { it.selectProfile(a.desktop, id) }
}
if (!gameScope) SharedInputRoleMix(host, a.desktop, library, track, ::update)
val physical = if (gameScope && gameKey != null && own?.parts?.containsKey(InputRole.PHYSICAL) == true)
stringResource(R.string.flow_game_changes, library.gameChanges(a.desktop, gameKey, InputRole.PHYSICAL))
else profileLabel(context, active)
@@ -27,13 +27,19 @@ import androidx.compose.ui.window.DialogProperties
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
/**
* What an in-game editor works on: the bindings (and layout) one role uses now, already copied for the game when changes
* are for it alone. [scope] names whose controls these are; [game] is set when the copy was made just for this edit.
*/
/** A game edit reads its effective part until a real change needs a private copy. */
internal data class GameInputEdit(val desktop: Boolean, val game: String, val name: String, val role: InputRole) {
fun part(library: InputLibrary) = library.activePart(desktop, role, game)
fun apply(library: InputLibrary, change: (InputLibrary, InputPart) -> InputLibrary): InputLibrary {
val editable = library.withGamePart(desktop, game, name, role)
return change(editable, part(editable))
}
}
internal data class InputEditorTarget(
val role: InputRole, val profile: String, val bindings: String, val layout: String?,
val scope: String, val game: String? = null, val desktop: Boolean = false,
val scope: String, val gameEdit: GameInputEdit? = null, val wasInherited: Boolean = false,
)
@Composable
@@ -41,10 +47,12 @@ internal fun InputEditorWindow(target: InputEditorTarget, onDismiss: () -> Unit,
if (target.role == InputRole.PHYSICAL) Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
Surface(Modifier.fillMaxSize().systemBarsPadding().padding(8.dp), color = MaterialTheme.colorScheme.surface, shape = RoundedCornerShape(18.dp)) {
val library by rememberInputLibrary()
val base = library.profiles.firstOrNull { it.id == target.profile }?.binding(InputRole.PHYSICAL)?.takeIf { it != target.bindings }
InputButtonsPane(target.bindings, target.scope, base, onDismiss, onChanged)
val base = library.profiles.firstOrNull { it.id == target.profile }?.binding(InputRole.PHYSICAL)
?.takeIf { target.gameEdit != null || it != target.bindings }
InputButtonsPane(target.bindings, target.scope, base, onDismiss, onChanged, gameEdit = target.gameEdit)
}
} else InputSurfaceDialog(target.profile, onDismiss, onChanged, role = target.role, layoutId = target.layout, bindingsId = target.bindings, scope = target.scope)
} else InputSurfaceDialog(target.profile, onDismiss, onChanged, role = target.role, layoutId = target.layout,
bindingsId = target.bindings, scope = target.scope, gameEdit = target.gameEdit)
}
private val controllerKeys = mapOf(
@@ -68,11 +76,12 @@ internal fun controlForKey(keyCode: Int): InputControl? = controllerKeys[keyCode
*/
@Composable
internal fun InputButtonsPane(bindingsId: String, scope: String, baseId: String?, onBack: () -> Unit, onChanged: () -> Unit,
onMore: (() -> Unit)? = null) {
onMore: (() -> Unit)? = null, gameEdit: GameInputEdit? = null) {
val context = LocalContext.current
val host = rememberMenuHost()
val library by rememberInputLibrary()
val preset = library.bindings.firstOrNull { it.id == bindingsId } ?: return
val activeBindings = gameEdit?.part(library)?.bindings ?: bindingsId
val preset = library.bindings.firstOrNull { it.id == activeBindings } ?: return
val base = baseId?.let { id -> library.bindings.firstOrNull { it.id == id } }
var selected by remember { mutableStateOf(InputControl.A) }
var capturing by remember { mutableStateOf(false) }
@@ -81,7 +90,16 @@ internal fun InputButtonsPane(bindingsId: String, scope: String, baseId: String?
val current = preset.controls[selected] ?: InputAction.Native()
val draft = remember(selected) { InputActionDraft(current) }
fun save(action: InputAction) {
runCatching { InputLibraries.update(context) { l -> l.withPreset(l.preset(bindingsId).let { it.copy(controls = it.controls + (selected to action)) }) } }
fun change(library: InputLibrary, id: String): InputLibrary {
val current = library.preset(id)
return library.withPreset(current.copy(controls = current.controls + (selected to action)))
}
runCatching {
InputLibraries.update(context) { latest ->
if (gameEdit == null) change(latest, bindingsId)
else gameEdit.apply(latest) { editable, part -> change(editable, part.bindings) }
}
}
.onSuccess { onChanged() }.onFailure { draft.action = current; failure = it.message ?: context.getString(R.string.input_save_failed) }
}
// Every change applies as it is made, as in the layout editor, so leaving never loses an edit.
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.ui
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
@@ -16,15 +17,81 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
val library by rememberInputLibrary()
var failure by remember { mutableStateOf<String?>(null) }
val fallback = profileLabel(context, library.profile(library.defaultId(desktop)))
val selection = library.selection(desktop)
val mixedId = quickMixedChoiceId(library)
val isMixed = selection.parts.isNotEmpty()
val active = profileLabel(context, library.profile(library.activeId(desktop)))
val choices = listOf(InputProfiles.AUTO to stringResource(R.string.flow_default_profile, fallback)) +
library.profiles.map { it.id to profileLabel(context, it) }
ChoiceRow(host, "input-profile", stringResource(R.string.input_profile), null, choices,
library.selection(desktop).profile, chipModifier = track("input-profile")) { id ->
runCatching { InputLibraries.update(context) { it.selectProfile(desktop, id) } }.onSuccess { onChanged(null) }
library.profiles.map { it.id to profileLabel(context, it) } +
if (isMixed) listOf(mixedId to stringResource(R.string.input_quick_mixed, active)) else emptyList()
fun update(role: InputRole?, change: (InputLibrary) -> InputLibrary) {
runCatching { InputLibraries.update(context, change) }.onSuccess { onChanged(role) }
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
ChoiceRow(host, "input-profile", stringResource(R.string.input_profile), null, choices,
if (isMixed) mixedId else selection.profile, chipModifier = track("input-profile")) { id ->
if (id != mixedId) update(null) { it.selectProfile(desktop, id) }
}
SharedInputRoleMix(host, desktop, library, track, ::update)
ActionRow(stringResource(R.string.flow_all_settings), null, stringResource(R.string.ctrl_edit), onEdit,
modifier = track("input-settings").testTag("input-profile-edit"))
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
text = { Text(message) }, confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) }
}
// This summary is not a selectable profile, even if an imported library uses the nominal ID.
internal fun quickMixedChoiceId(library: InputLibrary): String =
generateSequence("mixed") { "_$it" }.first { candidate ->
candidate != InputProfiles.AUTO && library.profiles.none { it.id == candidate }
}
internal fun quickRoleChoices(library: InputLibrary, role: InputRole): List<Pair<String, String>> =
library.bindings.filter { binding ->
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 }
/** Mode-local combinations belong to shared defaults, not to a game's pinned profile. */
@Composable
internal fun SharedInputRoleMix(
host: MenuHost,
desktop: Boolean,
library: InputLibrary,
track: (String) -> Modifier,
update: (InputRole?, (InputLibrary) -> InputLibrary) -> Unit,
) {
var expanded by rememberSaveable(desktop) { mutableStateOf(false) }
var naming by rememberSaveable(desktop) { mutableStateOf(false) }
val mixed = library.selection(desktop).parts.isNotEmpty()
ActionRow(stringResource(R.string.input_quick_mix_parts), null,
stringResource(if (expanded) R.string.common_hide else R.string.common_show), { expanded = !expanded },
modifier = track("input-profile-expand").testTag("input-profile-expand"))
if (expanded) {
for (role in InputRole.entries) {
val tag = "input-part-${role.name}"
ChoiceRow(host, tag, roleLabel(role), null, quickRoleChoices(library, role),
library.activePart(desktop, role).bindings, chipModifier = track(tag)) { id ->
update(role) { it.selectPart(desktop, role, id) }
}
}
if (mixed) ActionRow(stringResource(R.string.input_save_combination), null,
stringResource(R.string.gesture_save_changes), { naming = true },
modifier = track("input-save-combination").testTag("input-save-combination"))
}
if (naming) {
var name by rememberSaveable { 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)) } },
dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } },
)
}
}
@@ -332,6 +332,16 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) {
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
}
if (!library.isGameOwnedLayout(layout.id)) {
SliderRow(stringResource(R.string.ctrl_opacity), layout.name, layout.style.opacity, 1..100,
format = { "$it%" }, modifier = Modifier.testTag("input-layout-opacity")) { opacity ->
update { current ->
val saved = current.layouts.firstOrNull { it.id == layout.id }
if (saved == null || current.isGameOwnedLayout(saved.id)) current
else current.withLayout(saved.copy(style = saved.style.copy(opacity = opacity)))
}
}
}
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.flow_second_screen_hint))
}
@@ -380,7 +390,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
else InputHint(stringResource(R.string.input_layout_geometry_hint))
if (!community) SettingsGroup(stringResource(R.string.input_saved_layouts)) {
var showOther by remember { mutableStateOf(false) }
val available = library.layouts.filter { it.supports(role) }
val available = library.sharedLayouts(role)
val other = available.filter { saved -> !saved.id.startsWith("builtin.") && saved.id != layout?.id &&
library.usersOfLayout(saved.id).isEmpty() && library.bindings.none { it.layoutId == saved.id && library.selectedBindings(it.id) } }
for (saved in available.filter { showOther || it !in other }) {
@@ -244,15 +244,16 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
}
@Composable
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, initialSelection: String? = null, scope: String? = null) {
internal fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, initialSelection: String? = null,
scope: String? = null, gameEdit: GameInputEdit? = null) {
val context = LocalContext.current
val host = LocalInputActivity.current ?: context.findActivity() as? ComponentActivity
val library = remember { InputLibraries.read(context) }
val savedLayout = remember { library.layouts.first { it.id == (layoutId ?: library.profile(profile).parts.getValue(role).layout) } }
val savedBindings = remember { library.preset(bindingsId ?: library.profile(profile).binding(role)) }
val layoutUsers = library.usersOfLayout(savedLayout.id).size
val bindingUsers = library.usersOfBindings(savedBindings.id).size
val layoutUsers = if (gameEdit == null) library.usersOfLayout(savedLayout.id).size else 1
val bindingUsers = if (gameEdit == null) library.usersOfBindings(savedBindings.id).size else 1
val draft = remember {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let {
@@ -278,13 +279,26 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val remote = target != null && target.displayId != host?.window?.decorView?.display?.displayId
fun leave() { if (draft.dirty) discard = true else onDismiss() }
fun save() {
if (!draft.dirty) {
onDismiss()
return
}
fun change(library: InputLibrary, layoutId: String, bindingsId: String): InputLibrary {
val layout = library.layouts.first { it.id == layoutId }
check(layout.editable)
val bindings = library.preset(bindingsId)
return library.withLayout(OnScreenLayout.withFrame(context, layout, draft.elements, draft.aspect, draft.layoutScale)
.let { it.copy(style = it.style.copy(hidden = draft.hidden)) }).withPreset(bindings.copy(
elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } },
))
}
runCatching {
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)
.let { it.copy(style = it.style.copy(hidden = draft.hidden)) }).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
if (gameEdit == null) change(latest, savedLayout.id, savedBindings.id)
else gameEdit.apply(latest) { editable, part ->
change(editable, requireNotNull(part.layout), part.bindings)
}
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="input_quick_mix_parts">Mix profile parts</string>
</resources>
@@ -1,7 +1,11 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.view.View
import android.widget.FrameLayout
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.InputSurfaceView
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -123,16 +127,68 @@ class InputLibraryGamesTest {
assertTrue(runCatching { forked.removeBindings(id) }.isFailure)
}
@Test fun theOldPerLayoutOpacityFoldsIntoTheGlobalOneOnce() {
val base = library()
val main = base.activeLayout(false, InputRole.PRIMARY)!!
val faded = base.copy(layouts = base.layouts.map { if (it.id == main.id) it.copy(style = it.style.copy(opacity = 50)) else it })
@Test fun v14PreservesCustomPortraitAndBottomScreenOpacitySeparatelyFromGlobalOpacity() {
val button = InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, opacity = .5f)
val portrait = SavedInputLayout("portrait", "Portrait custom", listOf(button), screen = InputLayoutScreen.MAIN,
style = InputSurfaceStyle(opacity = 50), rotated = listOf(button.copy(y = .6f)), rotatedAspect = .6f)
val bottom = SavedInputLayout("bottom", "Bottom custom", listOf(button), screen = InputLayoutScreen.SECONDARY,
style = InputSurfaceStyle(opacity = 75))
val customized = library().withLayout(portrait).withLayout(bottom)
.chooseLayout(InputProfile.GAME, InputRole.PRIMARY, portrait.id)
.chooseLayout(InputProfile.GAME, InputRole.SECONDARY, bottom.id)
val old = JSONObject(InputLibraries.encode(customized)).apply { put("version", 14); remove("games") }
val prefs = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
assertTrue(prefs.edit().putString("library", old.toString()).commit())
ControllerPrefs.setOnScreenOpacity(context, 80)
val folded = InputLibraries.singleOpacity(context, faded)
assertTrue(folded.layouts.all { it.style.opacity == 100 })
assertEquals(40, ControllerPrefs.onScreenOpacity(context))
InputLibraries.singleOpacity(context, faded)
assertEquals(40, ControllerPrefs.onScreenOpacity(context))
val migrated = library()
assertEquals(portrait, migrated.activeLayout(false, InputRole.PRIMARY))
assertEquals(bottom, migrated.activeLayout(false, InputRole.SECONDARY))
assertEquals(80, ControllerPrefs.onScreenOpacity(context))
assertEquals(17, JSONObject(prefs.getString("library", null)!!).getInt("version"))
ControllerPrefs.setOnScreenOpacity(context, 25)
assertEquals(portrait, library().activeLayout(false, InputRole.PRIMARY))
assertEquals(bottom, library().activeLayout(false, InputRole.SECONDARY))
assertEquals(25, ControllerPrefs.onScreenOpacity(context))
}
@Test fun aGameOwnedLayoutKeepsInheritedOpacityButStaysOutOfSharedChoices() {
val shared = SavedInputLayout("shared_custom", "Shared custom", style = InputSurfaceStyle(opacity = 50))
val base = library().withLayout(shared).chooseLayout(InputProfile.GAME, InputRole.PRIMARY, shared.id)
val forked = base.withGamePart(false, "620", "Portal 2", InputRole.PRIMARY)
val own = forked.activeLayout(false, InputRole.PRIMARY, "620")!!
assertEquals(50, own.style.opacity)
assertNotEquals(shared.id, own.id)
assertFalse(forked.sharedLayouts(InputRole.PRIMARY).any { it.id == own.id })
assertTrue(forked.sharedLayouts(InputRole.PRIMARY).any { it.id == shared.id })
assertTrue(runCatching { forked.useLayout(InputProfile.GAME, InputRole.PRIMARY, own.id, shared = true) }.isFailure)
assertTrue(runCatching { forked.chooseLayout(InputProfile.GAME, InputRole.PRIMARY, own.id) }.isFailure)
val changed = forked.withLayout(own.copy(style = own.style.copy(opacity = 65)))
InputLibraries.update(context) { changed }
assertEquals(65, library().activeLayout(false, InputRole.PRIMARY, "620")!!.style.opacity)
assertEquals(50, library().activeLayout(false, InputRole.PRIMARY)!!.style.opacity)
assertEquals(1, library().gameChanges(false, "620", InputRole.PRIMARY))
}
@Test fun renderedControlsMultiplyLayoutAndElementOpacityIndependentlyOfGlobalOpacity() {
val button = InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, opacity = .5f)
ControllerPrefs.setOnScreenOpacity(context, 80)
val content = InputSurfaceView(context, customLayout = listOf(button), surfaceStyle = InputSurfaceStyle(opacity = 75))
// The live session applies global opacity on the parent; hiding/previewing a layout doesn't change that preference.
val parent = FrameLayout(context).apply {
alpha = ControllerPrefs.onScreenOpacity(context) / 100f
addView(content)
}
val rendered = content.findViewWithTag<View>(button)
assertEquals(.375f, rendered.alpha, .001f)
assertEquals(.3f, parent.alpha * rendered.alpha, .001f)
content.updateStyle(InputSurfaceStyle(opacity = 40))
assertEquals(.2f, rendered.alpha, .001f)
assertEquals(.16f, parent.alpha * rendered.alpha, .001f)
assertEquals(80, ControllerPrefs.onScreenOpacity(context))
}
@Test fun steamTouchIsOptIn() {
@@ -160,11 +160,12 @@ class WinlatorLayoutsTest {
assertNull(WinlatorLayouts.import(raw, "x", InputLayoutScreen.MAIN, 1920, 1080))
}
@Test fun aKeyOnlyFileOver64ControlsGoesToTheConverterWhichRefusesIt() {
@Test fun keyOnlyFilesOver64ControlsKeepTheFirst64UsableControls() {
val buttons = (0 until 65).joinToString(",") { """{"type":"BUTTON","shape":"CIRCLE","bindings":["KEY_A"],"scale":0.5,"x":0.5,"y":0.5}""" }
val raw = """{"cursorSpeed":1,"elements":[$buttons]}"""
assertTrue(WinlatorLayouts.needsConversion(raw))
assertNull(WinlatorLayouts.import(raw, "x", InputLayoutScreen.MAIN, 1920, 1080))
assertFalse(WinlatorLayouts.needsConversion(raw))
assertEquals(64, InputLayoutFile.import(context, raw, "x", InputLayoutScreen.MAIN,
InputSurfaceStyle(), 1920, 1080, 2f)!!.first.elements.size)
}
@Test fun controlsAfterManyEmptyEntriesStillCount() {
@@ -186,11 +187,11 @@ class WinlatorLayoutsTest {
assertEquals(52, layout.elements.size)
}
@Test fun aFileWithoutCursorSpeedOver64ControlsIsRefusedByTheOtherImporter() {
@Test fun aFileWithoutCursorSpeedOver64ControlsAlsoKeepsTheFirst64() {
val buttons = (0 until 65).joinToString(",") { """{"type":"BUTTON","shape":"CIRCLE","bindings":["KEY_A"],"scale":0.5,"x":0.5,"y":0.5}""" }
val raw = """{"name":"Many","elements":[$buttons]}"""
assertFalse(WinlatorLayouts.isIcp(raw))
assertNull(InputLayoutFile.import(context, raw, "Many", InputLayoutScreen.MAIN, InputSurfaceStyle(), 1920, 1080, 2f))
assertEquals(64, InputLayoutFile.import(context, raw, "Many", InputLayoutScreen.MAIN, InputSurfaceStyle(), 1920, 1080, 2f)!!.first.elements.size)
val sixtyFour = """{"name":"Fits","elements":[${(0 until 64).joinToString(",") { """{"type":"BUTTON","bindings":["KEY_A"],"x":0.5,"y":0.5}""" }}]}"""
assertEquals(64, InputLayoutFile.import(context, sixtyFour, "Fits", InputLayoutScreen.MAIN, InputSurfaceStyle(), 1920, 1080, 2f)!!.first.elements.size)
}
@@ -0,0 +1,46 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.input.InputAction
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputRole
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class GameInputEditTest {
@Test
fun readingInheritedControlsDoesNotWriteAGameOverride() {
val library = InputLibraries.read(RuntimeEnvironment.getApplication())
val editor = GameInputEdit(false, "game:preview", "Preview", InputRole.PRIMARY)
assertEquals(library.activePart(false, InputRole.PRIMARY), editor.part(library))
assertFalse(library.games.containsKey("game:preview"))
assertFalse(InputLibraries.read(RuntimeEnvironment.getApplication()).games.containsKey("game:preview"))
}
@Test
fun firstRealEditForksOnlyItsGameAndRole() {
val library = InputLibraries.read(RuntimeEnvironment.getApplication())
val editor = GameInputEdit(false, "game:edit", "Edit", InputRole.PHYSICAL)
val original = library.activePart(false, InputRole.PHYSICAL)
val updated = editor.apply(library) { editable, part ->
val preset = editable.preset(part.bindings)
editable.withPreset(preset.copy(controls = preset.controls + (InputControl.A to InputAction.Native(InputControl.B))))
}
val gamePart = editor.part(updated)
assertNotEquals(original.bindings, gamePart.bindings)
assertEquals(InputAction.Native(InputControl.B), updated.preset(gamePart.bindings).controls[InputControl.A])
assertEquals(original, updated.activePart(false, InputRole.PHYSICAL, "game:other"))
assertEquals(library.activePart(false, InputRole.PRIMARY), updated.activePart(false, InputRole.PRIMARY, "game:edit"))
assertEquals(library.preset(original.bindings), updated.preset(original.bindings))
}
}
@@ -0,0 +1,58 @@
package com.droiddeck.launcher.ui
import android.content.Context
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputRole
import com.droiddeck.launcher.input.InputStockLayouts
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class SharedInputRoleMixTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Test fun rolePickerOffersOnlyBindingsAcceptedByTheLibrary() {
val library = InputLibraries.read(context)
for (role in InputRole.entries) {
val offered = quickRoleChoices(library, role).map { it.first }.toSet()
assertTrue(offered.isNotEmpty())
assertEquals(library.bindings.filter { binding ->
runCatching { library.selectPart(false, role, binding.id).validate() }.isSuccess
}.map { it.id }.toSet(), offered)
}
}
@Test fun sharedMixAndSaveLeavePinnedGameAndOtherRolesAlone() {
val original = InputLibraries.read(context).withGameProfile("pinned", "Pinned", "game")
val trackpad = quickRoleChoices(original, InputRole.SECONDARY).single { it.first == InputStockLayouts.TRACKPAD }.first
val mixed = original.selectPart(false, InputRole.SECONDARY, trackpad).validate()
assertEquals(trackpad, mixed.activePart(false, InputRole.SECONDARY, "follows-default").bindings)
for (role in InputRole.entries) {
assertEquals(original.activePart(false, role, "pinned"), mixed.activePart(false, role, "pinned"))
if (role != InputRole.SECONDARY) assertEquals(original.activePart(false, role), mixed.activePart(false, role))
}
val saved = mixed.saveSelection(false, "Combined controls", "combined-controls").validate()
assertEquals(original.games, saved.games)
assertEquals(original.selection(true), saved.selection(true))
assertTrue(saved.selection(false).parts.isEmpty())
for (role in InputRole.entries) {
assertEquals(original.activePart(false, role, "pinned"), saved.activePart(false, role, "pinned"))
val before = mixed.preset(mixed.activePart(false, role).bindings)
val after = saved.preset(saved.activePart(false, role, "follows-default").bindings)
assertEquals(before.elements, after.elements)
assertEquals(before.clicks, after.clicks)
}
assertEquals(saved, InputLibraries.decode(InputLibraries.encode(saved)))
}
@Test fun mixedStatusIdNeverShadowsARealProfile() {
val library = InputLibraries.read(context).duplicateProfile("game", "Mixed import", "mixed")
assertNotEquals("mixed", quickMixedChoiceId(library))
assertFalse(library.profiles.any { it.id == quickMixedChoiceId(library) })
}
}