feat(input): per-game controls, drawn-pad binder, docked layout editor and Winlator layouts

This commit is contained in:
Kurt Himebauch committed 2026-12-04 12:29:21 -05:00
1 parent 26b11c6838
commit 5637eed4bd
61 files changed
+2776 -250

No files matched your search

@@ -242,6 +242,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var inputRouter: InputRouter? = null
private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null
private var inputSettingsOpen by mutableStateOf(false)
/** Which editor the input window shows; none means the full controller settings. */
private var inputEditor by mutableStateOf<com.droiddeck.launcher.ui.InputEditorTarget?>(null)
@Volatile private var inputUsesLocalActions = false
private var inputUsesPointer = false
private var inputProfile = InputProfile.defaults(InputProfile.GAME)
@@ -1166,7 +1168,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (pipUi) return
when {
::loading.isInitialized && loading.ended -> finish()
inputSettingsOpen -> inputSettingsOpen = false
inputSettingsOpen -> closeInputEditor()
dockedTouchOnly || backTaps.pending -> backTaps.tap()
drawerOpen -> drawerOpen = false
achievementsOpen -> closeAchievements()
@@ -1369,6 +1371,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
gestureGame = nextGame
refreshGestureConfig()
restoreGamePanel(nextGame)
if (inputGameKey() != SessionState.inputGame) { releasePads(); refreshInputProfile() }
}
if (
SessionState.mode == SessionService.MODE_STEAM &&
@@ -1397,18 +1400,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
if (inputSettingsOpen) com.droiddeck.launcher.ui.InputSettingsDialog(
onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() },
onChanged = {
controllerSettings = ControllerPrefs.read(this@SessionActivity)
oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM)
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity))
joyConVr?.refresh()
onScreenControls?.reload()
refreshInputProfile()
refreshControls()
},
)
val inputChanged = {
controllerSettings = ControllerPrefs.read(this@SessionActivity)
oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM)
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity))
joyConVr?.refresh()
onScreenControls?.reload()
refreshInputProfile()
refreshControls()
}
if (inputSettingsOpen) when (val target = inputEditor) {
null -> com.droiddeck.launcher.ui.InputSettingsDialog(
onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() },
onChanged = inputChanged,
)
else -> com.droiddeck.launcher.ui.InputEditorWindow(target, onDismiss = { closeInputEditor() }, onChanged = inputChanged)
}
LaunchedEffect(Unit) {
val root = LinuxRuntime.rootDir(this@SessionActivity)
while (true) {
@@ -1986,10 +1993,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null)
Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show()
},
onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({
drawerOpen = false
steamTouchControls?.startEditing()
}) else null,
onSuspendPolicy = { policy ->
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
suspendPolicy = policy
@@ -2001,8 +2004,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true },
onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputEditor = null; inputSettingsOpen = true },
onInputSelection = { releasePads(); refreshInputProfile() },
inputGame = inputGameKey()?.let { it to inputGameName() },
onEditButtons = { openInputEditor(InputRole.PHYSICAL) },
onEditLayout = when {
oscMode == SessionPrefs.OSC_NEVER -> null
steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM ->
if (onScreenButtonsVisible) ({ drawerOpen = false; steamTouchControls?.startEditing() }) else null
else -> ({ openInputEditor(InputRole.PRIMARY) })
},
onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true },
touchActive = drawerTouchMode(),
directHoldBehavior = directHoldBehavior,
@@ -4717,6 +4728,51 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (SessionState.mode == SessionService.MODE_RUN) SessionState.gameId?.takeIf { it.isNotBlank() }?.let { "game:$it" } ?: gestureGame
else gestureGame
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. */
private fun openInputEditor(role: InputRole) {
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val game = inputGameKey()?.takeUnless { SessionPrefs.inputForAllGames(this) }
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 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 library.profile(library.activeId(desktop, game)).name,
game = game?.takeIf { forked }, desktop = desktop)
}.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 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) }
}
releasePads()
refreshInputProfile()
secondScreenPresentation?.refreshControls()
}
private fun inputGameName(): String = when (SessionState.mode) {
SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
SessionService.MODE_STEAM -> frameGenActiveGameName
else -> null
}?.takeIf { it.isNotBlank() }?.take(80) ?: getString(R.string.session_title_game)
private fun settleDualScreenControls() {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
@@ -5066,13 +5122,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun refreshInputProfile() {
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val desktop = loadingMode() == SessionService.MODE_DESKTOP
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this))
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
val game = inputGameKey()
SessionState.inputGame = game
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this), game)
stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this), game)
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY, game)
adaptiveSticks = primaryInputLayout?.adaptiveSticks
quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty()
secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this))
deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings) }
secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this), game)
deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings, game) }
inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native }
inputUsesPointer = inputProfile.bindings.values.any { bindings ->
bindings.values.any { it is InputAction.Pointer || it is InputAction.MouseButton || it is InputAction.Scroll }
@@ -6093,8 +6151,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.OSC_ALWAYS -> true
SessionPrefs.OSC_STEAM_QAM -> true
SessionPrefs.OSC_NEVER -> false
SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM ||
(!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP)
SessionPrefs.OSC_STEAM_TOUCH -> if (SessionState.mode == SessionService.MODE_STEAM)
SessionPrefs.oscChosen(this) || !PadBridge.anyControllerConnected() && !SteamControllerBle.connected
else !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP
else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected &&
SessionState.mode != SessionService.MODE_DESKTOP
}
@@ -113,6 +113,14 @@ 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. */
fun foldOpacity(context: Context, layoutPercent: Int) {
val folded = (onScreenOpacity(context) * layoutPercent / 100f).toInt().coerceIn(onScreenOpacityRange)
prefs(context).edit().putInt("onScreenOpacity", folded).putBoolean("opacityFolded", true).commit()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
@@ -154,6 +162,15 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("snap", on).apply()
}
/** Layout editor grid cells across the width: 0 (no grid), or one of [editorGrids]. */
val editorGrids = listOf(0, 50, 25)
fun editorGrid(context: Context): Int = prefs(context).getInt("editorGrid", 0).takeIf { it in editorGrids } ?: 0
fun setEditorGrid(context: Context, cells: Int) {
prefs(context).edit().putInt("editorGrid", cells.takeIf { it in editorGrids } ?: 0).apply()
}
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
return raw.split(';').mapNotNull { entry ->
@@ -10,7 +10,8 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 14
// 15 and 16 belong to the reverted controller redesign; see redesignVersions.
private const val VERSION = 17
private val redesignVersions = 15..16
private const val KIT_DPAD = "kit:dpad"
private const val KEYBOARD = "builtin:keyboard"
@@ -45,6 +46,7 @@ object InputLibraries {
if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library)
if (version < 17) library = singleOpacity(context, library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -293,6 +295,16 @@ 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
ControllerPrefs.foldOpacity(context, main)
}
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
@@ -371,8 +383,14 @@ object InputLibraries {
selection.parts.forEach { (role, id) -> parts.put(role.name, id) }
selections.put(mode, JSONObject().put("profile", selection.profile).put("parts", parts).put("profileSelected", selection.profileSelected))
}
val games = JSONObject()
for ((key, game) in library.games) {
val parts = JSONObject()
game.parts.forEach { (role, part) -> parts.put(role.name, JSONObject().put("bindings", part.bindings).put("layout", part.layout)) }
games.put(key, JSONObject().put("name", game.name).put("profile", game.profile ?: JSONObject.NULL).put("parts", parts))
}
return JSONObject().put("selections", selections).put("version", VERSION).put("selected", library.selected).put("steam", library.steam).put("desktop", library.desktop)
.put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString()
.put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).put("games", games).toString()
}
internal fun decode(raw: String, context: Context? = null): InputLibrary? = runCatching {
@@ -422,7 +440,17 @@ object InputLibraries {
value.optBoolean("profileSelected", profile != InputProfiles.AUTO || parts.length() == 0))
}
}.orEmpty()
val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections)
val games = doc.optJSONObject("games")?.let { saved ->
require(saved.length() <= 512)
saved.keys().asSequence().associateWith { key ->
val game = saved.getJSONObject(key)
val parts = game.getJSONObject("parts")
GameInput(game.getString("name"), game.optionalString("profile"), parts.keys().asSequence().associate { role ->
val part = parts.getJSONObject(role); InputRole.valueOf(role) to InputPart(part.getString("bindings"), part.optionalString("layout"))
})
}
}.orEmpty()
val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections, games)
(if (restore) restoreGamepads(requireNotNull(context), library, generated) else library).validate()
}.getOrNull()
@@ -69,11 +69,15 @@ data class SavedInputProfile(val id: String, val name: String, val base: String,
fun binding(role: InputRole) = parts.getValue(role).bindings
}
/** One game's own controls: a profile it always uses, and parts copied from that profile and then changed for it alone. */
data class GameInput(val name: String, val profile: String? = null, val parts: Map<InputRole, InputPart> = emptyMap())
data class InputLibrary(
val profiles: List<SavedInputProfile>, val layouts: List<SavedInputLayout>, val bindings: List<SavedInputBindings>,
val selected: String = InputProfiles.AUTO,
val steam: String = InputProfile.GAME, val desktop: String = InputProfile.DESKTOP,
val selections: Map<String, InputSelection> = emptyMap(),
val games: Map<String, GameInput> = emptyMap(),
) {
fun profile(id: String) = profiles.first { it.id == id }
fun preset(id: String) = bindings.first { it.id == id }
@@ -81,31 +85,36 @@ data class InputLibrary(
?.let { id -> layouts.firstOrNull { it.id == id } }
private fun mode(isDesktop: Boolean) = if (isDesktop) InputProfile.DESKTOP else InputProfile.GAME
fun selection(isDesktop: Boolean) = selections[mode(isDesktop)] ?: InputSelection(selected)
fun activeId(isDesktop: Boolean): String {
fun defaultId(isDesktop: Boolean) = if (isDesktop) desktop else steam
fun activeId(isDesktop: Boolean, game: String? = null): String {
games[game]?.profile?.let { return it }
val id = selection(isDesktop).profile
return if (id == InputProfiles.AUTO) { if (isDesktop) desktop else steam } else id
return if (id == InputProfiles.AUTO) defaultId(isDesktop) else id
}
fun selectProfile(isDesktop: Boolean, id: String) = copy(selections = selections + (mode(isDesktop) to InputSelection(id, profileSelected = true)))
fun selectPart(isDesktop: Boolean, role: InputRole, bindingsId: String): InputLibrary {
val previous = selection(isDesktop)
return copy(selections = selections + (mode(isDesktop) to previous.copy(parts = previous.parts + (role to bindingsId))))
}
fun activePart(isDesktop: Boolean, role: InputRole): InputPart {
val binding = selection(isDesktop).parts[role]?.let(::preset)
return if (binding != null) InputPart(binding.id, binding.layoutId) else profile(activeId(isDesktop)).parts.getValue(role)
fun activePart(isDesktop: Boolean, role: InputRole, game: String? = null): InputPart {
games[game]?.parts?.get(role)?.let { return it }
val binding = selection(isDesktop).parts[role]?.takeIf { games[game]?.profile == null }?.let(::preset)
return if (binding != null) InputPart(binding.id, binding.layoutId) else profile(activeId(isDesktop, game)).parts.getValue(role)
}
fun activeLayout(isDesktop: Boolean, role: InputRole) = activePart(isDesktop, role).layout?.let { id -> layouts.first { it.id == id } }
fun panelPart(isDesktop: Boolean, panel: String?): InputPart =
panel?.let { id -> bindings.firstOrNull { it.id == id } }?.let { InputPart(it.id, it.layoutId) } ?: activePart(isDesktop, InputRole.SECONDARY)
fun panelLayout(isDesktop: Boolean, panel: String?) = panelPart(isDesktop, panel).layout?.let { id -> layouts.firstOrNull { it.id == id } }
fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith {
preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings)
fun activeLayout(isDesktop: Boolean, role: InputRole, game: String? = null) =
activePart(isDesktop, role, game).layout?.let { id -> layouts.first { it.id == id } }
fun panelPart(isDesktop: Boolean, panel: String?, game: String? = null): InputPart =
panel?.let { id -> bindings.firstOrNull { it.id == id } }?.let { InputPart(it.id, it.layoutId) } ?: activePart(isDesktop, InputRole.SECONDARY, game)
fun panelLayout(isDesktop: Boolean, panel: String?, game: String? = null) =
panelPart(isDesktop, panel, game).layout?.let { id -> layouts.firstOrNull { it.id == id } }
fun compileActive(isDesktop: Boolean, panel: String? = null, game: String? = null): InputProfile = compileParts(activeId(isDesktop, game), InputRole.entries.associateWith {
preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel, game).bindings else activePart(isDesktop, it, game).bindings)
})
fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile {
val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base)
fun compileStock(isDesktop: Boolean, panel: String? = null, game: String? = null): InputProfile {
val defaults = InputProfile.defaults(profile(activeId(isDesktop, game)).base)
val stock = InputStockLayouts.presets(InputStockLayouts.layouts())
return compileParts(defaults.id, InputRole.entries.associateWith { role ->
val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role)
val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel, game) else activePart(isDesktop, role, game)
val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout
stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) }
?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty())
@@ -134,8 +143,67 @@ 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 }
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 } }
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. */
fun withGamePart(isDesktop: Boolean, game: String, name: String, role: InputRole,
bindingsId: String = newInputId(), layoutId: String = newInputId()): InputLibrary {
val current = games[game] ?: GameInput(inputName(name))
if (role in current.parts) return this
val source = activePart(isDesktop, role, game)
val label = (current.name + " / " + role.name.lowercase()).take(80)
val sourceLayout = source.layout?.let { id -> layouts.first { it.id == id } }
val copiedLayout = sourceLayout?.takeIf { it.editable }?.derived(layoutId, label)
val copied = preset(source.bindings).copy(id = bindingsId, name = label, layoutId = copiedLayout?.id ?: preset(source.bindings).layoutId)
val part = InputPart(copied.id, copiedLayout?.id ?: source.layout)
return (if (copiedLayout == null) this else withLayout(copiedLayout)).withPreset(copied)
.copy(games = games + (game to current.copy(parts = current.parts + (role to part))))
}
fun withGameProfile(game: String, name: String, profile: String?): InputLibrary {
require(profile == null || profiles.any { it.id == profile })
val current = games[game] ?: GameInput(inputName(name))
val next = current.copy(profile = profile)
return copy(games = if (next.profile == null && next.parts.isEmpty()) games - game else games + (game to next))
}
/** Drops [game]'s own controls (one part, or all of them) and the copies nothing else uses. */
fun resetGame(game: String, role: InputRole? = null): InputLibrary {
val current = games[game] ?: return this
val dropped = if (role == null) current.parts.values.toList() else listOfNotNull(current.parts[role])
val remaining = if (role == null) null else current.copy(parts = current.parts - role).takeIf { it.profile != null || it.parts.isNotEmpty() }
var result = copy(games = if (remaining == null) games - game else games + (game to remaining))
for (part in dropped) {
if (result.usersOfBindings(part.bindings).isEmpty() && !result.selectedBindings(part.bindings))
result = result.copy(bindings = result.bindings.filterNot { it.id == part.bindings })
val layout = part.layout ?: continue
if (result.usersOfLayout(layout).isEmpty() && !result.gamesUsingLayout(layout) && result.layouts.first { it.id == layout }.editable &&
result.bindings.none { it.layoutId == layout })
result = result.copy(layouts = result.layouts.filterNot { it.id == layout })
}
return result
}
/** How many controls [game]'s own parts set differently from the profile it would otherwise use. */
fun gameChanges(isDesktop: Boolean, game: String, only: InputRole? = null): Int {
val current = games[game] ?: return 0
return current.parts.entries.filter { only == null || it.key == only }.sumOf { (role, part) ->
val base = copy(games = games - game).activePart(isDesktop, role)
val mine = preset(part.bindings)
val theirs = preset(base.bindings)
val controls = (mine.controls.keys + theirs.controls.keys).count { (mine.controls[it] ?: InputAction.Native()) != (theirs.controls[it] ?: InputAction.Native()) }
val keys = (mine.keys.toSet() - theirs.keys.toSet()).size + (theirs.keys.toSet() - mine.keys.toSet()).size
val layout = part.layout?.let { id -> layouts.firstOrNull { it.id == id } }
val baseLayout = base.layout?.let { id -> layouts.firstOrNull { it.id == id } }
val elements = layout?.elements.orEmpty().count { e ->
val before = baseLayout?.elements?.firstOrNull { it.id == e.id }
before == null || before != e || mine.action(e) != theirs.action(e) || (e.hasClick && mine.clickAction(e) != theirs.clickAction(e))
} + if (layout == null) 0 else baseLayout?.elements.orEmpty().count { e -> layout.elements.none { it.id == e.id } }
controls + keys + if (layout?.id == baseLayout?.id) 0 else elements
}
}
fun withProfile(value: SavedInputProfile) = copy(profiles = profiles.filterNot { it.id == value.id } + value)
fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value)
fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value,
@@ -212,11 +280,12 @@ data class InputLibrary(
require(id != InputProfile.GAME && id != InputProfile.DESKTOP)
return copy(profiles = profiles.filterNot { it.id == id }, selected = selected.takeUnless { it == id } ?: InputProfiles.AUTO,
steam = steam.takeUnless { it == id } ?: InputProfile.GAME, desktop = desktop.takeUnless { it == id } ?: InputProfile.DESKTOP,
selections = selections.mapValues { (_, selection) -> if (selection.profile == id) selection.copy(profile = InputProfiles.AUTO) else selection })
selections = selections.mapValues { (_, selection) -> if (selection.profile == id) selection.copy(profile = InputProfiles.AUTO) else selection },
games = games.mapValues { (_, game) -> if (game.profile == id) game.copy(profile = null) else game }.filterValues { it.profile != null || it.parts.isNotEmpty() })
}
fun removeLayout(id: String): InputLibrary {
require(usersOfLayout(id).isEmpty() && bindings.none { it.layoutId == id && selectedBindings(it.id) } && layouts.first { it.id == id }.editable)
require(usersOfLayout(id).isEmpty() && !gamesUsingLayout(id) && bindings.none { it.layoutId == id && selectedBindings(it.id) } && layouts.first { it.id == id }.editable)
return copy(layouts = layouts.filterNot { it.id == id }, bindings = bindings.filterNot { it.layoutId == id })
}
@@ -292,6 +361,20 @@ data class InputLibrary(
require(binding.compatible(layout) && (layout == null || layout.supports(role)))
}
}
require(games.size <= 512)
for ((key, game) in games) {
require(key.isNotBlank() && key.length <= 128)
inputName(game.name)
require(game.profile == null || profiles.any { it.id == game.profile })
require(game.profile != null || game.parts.isNotEmpty())
for ((role, part) in game.parts) {
val binding = preset(part.bindings)
require(binding.physical == (role == InputRole.PHYSICAL))
val layout = part.layout?.let { id -> layouts.first { it.id == id } }
require(if (role == InputRole.PHYSICAL) layout == null else layout?.supports(role) == true)
require(binding.compatible(layout))
}
}
for (p in profiles) {
inputName(p.name); require(p.base == InputProfile.GAME || p.base == InputProfile.DESKTOP)
require(p.parts.keys == InputRole.entries.toSet())
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.input
import org.json.JSONObject
import java.net.URLEncoder
/**
* Winlator's input-control profiles (`.icp`): a list of touch elements centred at fractions of the screen, sized in
* hundredths of the screen width times their scale, each sending keyboard keys, mouse buttons or gamepad controls.
*/
object WinlatorLayouts {
private const val BASE = "https://raw.githubusercontent.com/brunodev85/winlator/main/input_controls/"
const val INDEX_URL = BASE + "index.txt"
fun fileUrl(name: String) = BASE + URLEncoder.encode(name, "UTF-8").replace("+", "%20")
/** The profile file names a community index lists. */
fun parseIndex(text: String): List<String> = text.lineSequence().map { it.trim() }
.filter { it.endsWith(".icp", ignoreCase = true) && it.length <= 128 && '/' !in it && '\\' !in it }.distinct().take(500).toList()
fun isIcp(raw: String) = runCatching { JSONObject(raw).let { it.has("elements") && it.optJSONArray("elements") != null && it.has("cursorSpeed") } }.getOrDefault(false)
private val keys: Map<String, Int> = mapOf(
"ESC" to 1, "1" to 2, "2" to 3, "3" to 4, "4" to 5, "5" to 6, "6" to 7, "7" to 8, "8" to 9, "9" to 10, "0" to 11,
"MINUS" to 12, "EQUAL" to 13, "BKSP" to 14, "TAB" to 15, "Q" to 16, "W" to 17, "E" to 18, "R" to 19, "T" to 20, "Y" to 21,
"U" to 22, "I" to 23, "O" to 24, "P" to 25, "BRACKET_LEFT" to 26, "BRACKET_RIGHT" to 27, "ENTER" to 28, "CTRL_L" to 29,
"A" to 30, "S" to 31, "D" to 32, "F" to 33, "G" to 34, "H" to 35, "J" to 36, "K" to 37, "L" to 38, "SEMICOLON" to 39,
"APOSTROPHE" to 40, "GRAVE" to 41, "SHIFT_L" to 42, "BACKSLASH" to 43, "Z" to 44, "X" to 45, "C" to 46, "V" to 47,
"B" to 48, "N" to 49, "M" to 50, "COMMA" to 51, "PERIOD" to 52, "SLASH" to 53, "SHIFT_R" to 54, "KP_MULTIPLY" to 55,
"ALT_L" to 56, "SPACE" to 57, "CAPS_LOCK" to 58, "F1" to 59, "F2" to 60, "F3" to 61, "F4" to 62, "F5" to 63, "F6" to 64,
"F7" to 65, "F8" to 66, "F9" to 67, "F10" to 68, "NUM_LOCK" to 69, "SCROLL_LOCK" to 70, "KP_7" to 71, "KP_8" to 72,
"KP_9" to 73, "KP_SUBTRACT" to 74, "KP_4" to 75, "KP_5" to 76, "KP_6" to 77, "KP_ADD" to 78, "KP_1" to 79, "KP_2" to 80,
"KP_3" to 81, "KP_0" to 82, "KP_DEL" to 83, "F11" to 87, "F12" to 88, "KP_ENTER" to 96, "CTRL_R" to 97, "KP_DIVIDE" to 98,
"PRTSCN" to 99, "ALT_R" to 100, "HOME" to 102, "UP" to 103, "PG_UP" to 104, "PRIOR" to 104, "LEFT" to 105, "RIGHT" to 106,
"END" to 107, "DOWN" to 108, "PG_DOWN" to 109, "NEXT" to 109, "INSERT" to 110, "DEL" to 111,
)
private val gamepad: Map<String, InputControl> = mapOf(
"A" to InputControl.A, "B" to InputControl.B, "X" to InputControl.X, "Y" to InputControl.Y,
"L1" to InputControl.LB, "R1" to InputControl.RB, "L2" to InputControl.LT, "R2" to InputControl.RT,
"L3" to InputControl.L3, "R3" to InputControl.R3, "SELECT" to InputControl.SELECT, "START" to InputControl.START,
)
private val dpad = mapOf("UP" to InputControl.UP, "RIGHT" to InputControl.RIGHT, "DOWN" to InputControl.DOWN, "LEFT" to InputControl.LEFT)
private val ranges = mapOf(
"FROM_A_TO_Z" to ('A'..'Z').map { it.toString() }, "FROM_0_TO_9" to (listOf("0") + ('1'..'9').map { it.toString() }),
"FROM_F1_TO_F12" to (1..12).map { "F$it" }, "FROM_NP0_TO_NP9" to (0..9).map { "KP_$it" },
)
private fun key(binding: String) = keys[binding.removePrefix("KEY_")]?.takeIf { binding.startsWith("KEY_") }
/** What one button binding does here, or null when it has no button equivalent. */
internal fun buttonAction(binding: String): InputAction? = when {
binding.startsWith("KEY_") -> key(binding)?.let { InputAction.Keys(listOf(it)) }
binding == "MOUSE_LEFT_BUTTON" -> InputAction.MouseButton(272)
binding == "MOUSE_RIGHT_BUTTON" -> InputAction.MouseButton(273)
binding == "MOUSE_MIDDLE_BUTTON" -> InputAction.MouseButton(274)
binding.startsWith("GAMEPAD_BUTTON_") -> gamepad[binding.removePrefix("GAMEPAD_BUTTON_")]?.let { InputAction.Native(it) }
binding.startsWith("GAMEPAD_DPAD_") -> dpad[binding.removePrefix("GAMEPAD_DPAD_")]?.let { InputAction.Native(it) }
else -> null
}
/** What four direction bindings (up, right, down, left) do on a stick, D-pad or trackpad. */
private fun directionAction(bindings: List<String>, kind: InputElementKind): InputAction {
val all = bindings.take(4)
return when {
all.any { it.startsWith("GAMEPAD_LEFT_THUMB") } -> if (kind == InputElementKind.DPAD) InputAction.Native() else InputAction.Native(InputControl.LS)
all.any { it.startsWith("GAMEPAD_RIGHT_THUMB") } -> if (kind == InputElementKind.DPAD) InputAction.Native() else InputAction.Native(InputControl.RS)
all.any { it.startsWith("GAMEPAD_DPAD") } -> if (kind == InputElementKind.DPAD) InputAction.Native() else InputAction.Native(InputControl.LS)
all.any { it.startsWith("MOUSE_MOVE") } -> InputAction.Pointer()
all.any { it.startsWith("KEY_") } -> all.map { key(it) ?: 0 }.let { InputAction.Directions(it[0], it[1], it[2], it[3]) }
else -> InputAction.Disabled
}
}
private fun label(binding: String): String = when {
binding.startsWith("KEY_") -> binding.removePrefix("KEY_").replace('_', ' ')
binding.startsWith("MOUSE_") -> binding.removePrefix("MOUSE_").removeSuffix("_BUTTON").replace('_', ' ')
binding.startsWith("GAMEPAD_BUTTON_") -> binding.removePrefix("GAMEPAD_BUTTON_")
binding.startsWith("GAMEPAD_DPAD_") -> binding.removePrefix("GAMEPAD_")
else -> binding.replace('_', ' ')
}.lowercase().replaceFirstChar { it.uppercase() }.take(80)
/** Converts an `.icp` file for a [width]×[height] screen into a layout and the actions of its controls. */
fun import(raw: String, fallbackName: String, screen: InputLayoutScreen, width: Int, height: Int,
id: String = newInputId(), bindingsId: String = newInputId()): Pair<SavedInputLayout, SavedInputBindings>? = runCatching {
require(raw.length <= 1_000_000)
val doc = JSONObject(raw)
val source = doc.getJSONArray("elements")
val aspect = (width.coerceAtLeast(1).toFloat() / height.coerceAtLeast(1)).coerceIn(.05f, 20f)
val elements = mutableListOf<InputSurfaceElement>()
val actions = mutableMapOf<String, InputAction>()
fun place(kind: InputElementKind, name: String, cx: Float, cy: Float, halfW: Float, halfH: Float, action: InputAction,
shape: InputButtonShape = InputButtonShape.ROUNDED, toggle: Boolean = false) {
if (elements.size >= 64) return
val w = halfW * .01f; val h = halfH * .01f * aspect
val element = InputSurfaceElement(kind.control, cx - w, cy - h, 2 * w, 2 * h, newInputId(), kind, name.ifBlank { "?" }.take(80),
toggle = toggle && (kind == InputElementKind.BUTTON || kind == InputElementKind.TRIGGER), buttonShape = shape).bounded()
elements += element
actions[element.id] = action.takeIf { it.validFor(element) } ?: InputAction.Disabled
}
for (i in 0 until minOf(source.length(), 128)) {
val e = source.optJSONObject(i) ?: continue
val bindings = e.optJSONArray("bindings")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
val scale = e.optDouble("scale", 1.0).toFloat().coerceIn(.2f, 5f)
val cx = e.optDouble("x", .5).toFloat(); val cy = e.optDouble("y", .5).toFloat()
val text = e.optString("text").trim()
val shape = when (e.optString("shape")) { "CIRCLE" -> InputButtonShape.CIRCLE; "RECT", "SQUARE" -> InputButtonShape.RECTANGLE; else -> InputButtonShape.ROUNDED }
when (e.optString("type")) {
"BUTTON" -> {
val binding = bindings.firstOrNull { it != "NONE" } ?: continue
val action = buttonAction(binding) ?: InputAction.Disabled
val trigger = action is InputAction.Native && (action.target == InputControl.LT || action.target == InputControl.RT)
val (hw, hh) = when (e.optString("shape")) { "RECT", "ROUND_RECT" -> 4f to 2f; "SQUARE" -> 2.5f to 2.5f; else -> 3f to 3f }
place(if (trigger) InputElementKind.TRIGGER else InputElementKind.BUTTON, text.ifEmpty { label(binding) }, cx, cy, hw * scale, hh * scale,
action, shape, e.optBoolean("toggleSwitch"))
}
"D_PAD" -> place(InputElementKind.DPAD, text.ifEmpty { "D-pad" }, cx, cy, 7 * scale, 7 * scale, directionAction(bindings, InputElementKind.DPAD))
"STICK" -> place(InputElementKind.STICK, text.ifEmpty { "Stick" }, cx, cy, 6 * scale, 6 * scale, directionAction(bindings, InputElementKind.STICK))
"TRACKPAD" -> place(InputElementKind.TRACKPAD, text.ifEmpty { "Trackpad" }, cx, cy, 6 * scale, 6 * scale,
directionAction(bindings, InputElementKind.TRACKPAD).takeIf { it !is InputAction.Directions } ?: InputAction.Pointer())
"RANGE_BUTTON" -> {
val range = ranges[e.optString("range", "FROM_A_TO_Z")] ?: continue
val count = bindings.size.coerceIn(1, range.size)
val vertical = e.optInt("orientation", 0) == 1
for (n in 0 until count) {
val offset = (n - (count - 1) / 2f) * 4 * scale * .01f
val code = keys[range[n]] ?: continue
place(InputElementKind.BUTTON, label("KEY_" + range[n]), cx + if (vertical) 0f else offset, cy + if (vertical) offset * aspect else 0f,
2 * scale, 2 * scale, InputAction.Keys(listOf(code)), shape)
}
}
}
}
require(elements.isNotEmpty())
val name = doc.optString("name").trim().take(80).ifEmpty { fallbackName.trim().take(80) }.ifEmpty { "Winlator" }
val layout = SavedInputLayout(id, name, elements, screen = screen, aspect = aspect)
layout to SavedInputBindings(bindingsId, name, false, id, elements = actions)
}.getOrNull()
}
@@ -23,6 +23,10 @@ object GameProfileManager {
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
clear("bottom screen") { SessionPrefs.clearGameBottomScreen(context, scope) }
clear("controls") {
if (com.droiddeck.launcher.input.InputLibraries.read(context).games.containsKey(scope))
com.droiddeck.launcher.input.InputLibraries.update(context) { it.resetGame(scope) }
}
clear("guides") {
SteamGuides.clear(context, scope)
GuideLibrary.clear(context, scope)
@@ -828,8 +828,9 @@ object SessionPrefs {
prefs(context).getString("shape", null)
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
/** Until the player picks, Steam sessions use Steam's own touch controls and other sessions DroidDeck's. */
fun oscMode(context: Context, steamSession: Boolean = true): String {
val saved = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO
val saved = prefs(context).getString("osc", null) ?: return if (steamSession) OSC_STEAM_TOUCH else OSC_AUTO
return if (!steamSession && saved == OSC_STEAM_QAM) OSC_AUTO else saved
}
@@ -837,6 +838,15 @@ object SessionPrefs {
prefs(context).edit().putString("osc", mode).apply()
}
fun oscChosen(context: Context) = prefs(context).contains("osc")
/** Whether changes made in a game apply to that game alone, or to the profile every game shares. */
fun inputForAllGames(context: Context) = prefs(context).getBoolean("inputForAllGames", false)
fun setInputForAllGames(context: Context, all: Boolean) {
prefs(context).edit().putBoolean("inputForAllGames", all).apply()
}
fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false)
fun setOscRearButtons(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscRearButtons", shown).apply() }
@@ -138,6 +138,8 @@ object SessionState {
@Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE
@Volatile var bottomMenu = false
@Volatile var secondScreenDisplay = -1
/** The game whose own controls apply now, keyed like its other per-game session settings. */
@Volatile var inputGame: String? = null
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
@Volatile var secondScreenAutomatic = false
@@ -0,0 +1,80 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
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
import java.net.HttpURLConnection
import java.net.URL
private fun fetchText(url: String): String? = runCatching {
(URL(url).openConnection() as HttpURLConnection).run {
connectTimeout = 10_000; readTimeout = 15_000
try {
if (responseCode != 200) return@run null
inputStream.use { stream -> stream.readBytes().takeIf { it.size <= 1_000_000 }?.toString(Charsets.UTF_8) }
} finally { disconnect() }
}
}.getOrNull()
/** Shared Winlator layouts: the list, a preview of one as it would sit on this screen, and Use. */
@Composable
internal fun CommunityLayouts(role: InputRole, onUse: (Pair<SavedInputLayout, SavedInputBindings>) -> Unit) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
var names by remember { mutableStateOf<List<String>?>(null) }
var failed by remember { mutableStateOf(false) }
var attempt by remember { mutableIntStateOf(0) }
val previews = remember { mutableStateMapOf<String, Pair<SavedInputLayout, SavedInputBindings>?>() }
var loading by remember { mutableStateOf<String?>(null) }
LaunchedEffect(attempt) {
failed = false
val text = withContext(Dispatchers.IO) { fetchText(WinlatorLayouts.INDEX_URL) }
names = text?.let(WinlatorLayouts::parseIndex)
failed = names.isNullOrEmpty()
}
Text(stringResource(R.string.flow_community_hint), Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
SettingsGroup(stringResource(R.string.flow_community)) {
val list = names
when {
failed -> ActionRow(stringResource(R.string.flow_community_failed), null, stringResource(R.string.input_capture_retry), { attempt++ })
list == null -> Text(stringResource(R.string.flow_loading), Modifier.padding(16.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
else -> for (file in list) {
val title = file.removeSuffix(".icp").removeSuffix(".ICP")
val preview = previews[file]
SettingsRow(title, null) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
preview?.let { InputLayoutThumbnail(it.first, role) }
if (preview == null) SecondaryButton(stringResource(if (loading == file) R.string.flow_loading else R.string.flow_preview),
enabled = loading == null, compact = true, modifier = Modifier.testTag("community-preview-$title")) {
loading = file
scope.launch {
val metrics = inputDisplayMetrics(context, role)
val raw = withContext(Dispatchers.IO) { fetchText(WinlatorLayouts.fileUrl(file)) }
previews[file] = raw?.let {
WinlatorLayouts.import(it, title, if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY,
metrics.widthPixels, metrics.heightPixels)
}
if (previews[file] == null) failed = raw == null
loading = null
}
}
else PrimaryButton(stringResource(R.string.flow_use), compact = true, modifier = Modifier.testTag("community-use-$title")) { onUse(preview) }
}
}
}
}
}
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
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 com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
/** The library as it is saved now, re-read whenever something else saves it. */
@Composable
internal fun rememberInputLibrary(): State<InputLibrary> {
val context = LocalContext.current
val library = remember { mutableStateOf(InputLibraries.read(context)) }
DisposableEffect(context) {
val preferences = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "library") library.value = InputLibraries.read(context) }
preferences.registerOnSharedPreferenceChangeListener(listener)
onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) }
}
return library
}
/** The session menu's Controls section: which profile applies, whether changes are for this game, and the two editors. */
@Composable
internal fun DrawerControlsGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val context = LocalContext.current
val library by rememberInputLibrary()
var forAll by remember { mutableStateOf(SessionPrefs.inputForAllGames(context)) }
var failure by remember { mutableStateOf<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) }
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
val gameKey = game?.first
val active = library.profile(library.activeId(a.desktop, gameKey))
val changes = gameKey?.let { library.gameChanges(a.desktop, it) } ?: 0
val own = gameKey?.let { library.games[it] }
val defaultName = library.profile(library.defaultId(a.desktop)).name
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.flow_default_profile, defaultName)) + library.profiles.map { it.id to it.name }
val selected = if (gameScope) own?.profile ?: InputProfiles.AUTO else library.selection(a.desktop).profile
val detail = listOfNotNull(active.name, if (changes > 0 && game != null) stringResource(R.string.flow_game_changes, game.second, changes) else null).joinToString(" · ")
SettingsGroup(stringResource(R.string.flow_controls), key = "controller-input", detail = detail) {
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) }
}
if (game != null) ChoiceRow(host, "input-scope", stringResource(R.string.flow_save_for), stringResource(R.string.flow_save_for_hint),
listOf(false to game.second, true to stringResource(R.string.flow_all_games)), forAll, chipModifier = track("input-scope")) {
forAll = it; SessionPrefs.setInputForAllGames(context, it)
}
val physical = if (gameKey != null && own?.parts?.containsKey(InputRole.PHYSICAL) == true)
stringResource(R.string.flow_game_changes, game.second, library.gameChanges(a.desktop, gameKey, InputRole.PHYSICAL))
else active.name
ActionRow(stringResource(R.string.flow_buttons), physical, stringResource(R.string.ctrl_edit), a.onEditButtons,
modifier = track("input-buttons").testTag("input-edit-buttons"))
a.onEditLayout?.let { edit ->
val layoutName = if (a.oscMode == SessionPrefs.OSC_STEAM_TOUCH && a.steam) stringResource(R.string.osc_steam_layout)
else library.activeLayout(a.desktop, InputRole.PRIMARY, gameKey)?.name
ActionRow(stringResource(R.string.flow_layout), layoutName, stringResource(R.string.ctrl_edit), edit,
modifier = track("input-layout").testTag("input-edit-layout"))
}
if (gameKey != null && own != null) ActionRow(stringResource(R.string.flow_use_profile), stringResource(R.string.flow_use_profile_hint, game.second),
stringResource(R.string.ctrl_reset), { update { it.resetGame(gameKey) } }, modifier = track("input-game-reset").testTag("input-game-reset"))
ActionRow(stringResource(R.string.flow_all_settings), null, stringResource(R.string.ctrl_edit), a.onInputSettings,
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)) } }) }
}
@@ -12,6 +12,32 @@ import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
/** The action being edited, with what each kind of action was set to so switching kinds and back loses nothing. */
internal class InputActionDraft(initial: InputAction) {
var action by mutableStateOf(initial)
private val drafts = mutableMapOf<String, InputAction>()
var localType by mutableStateOf(typeOf(initial).takeUnless { it == "native" || it == "disabled" } ?: "keys")
private set
fun switch(type: String, initial: () -> InputAction) {
drafts[typeOf(action)] = action
action = drafts[type] ?: initial()
if (type != "native" && type != "disabled") localType = type
}
companion object {
fun typeOf(action: InputAction): String = when (action) {
is InputAction.Native -> "native"; InputAction.Disabled -> "disabled"
is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command"
is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"
is InputAction.Directions -> "directions"; is InputAction.Keys -> "keys"
}
}
}
internal fun InputAction.validAs(control: InputControl, element: InputSurfaceElement?, click: Boolean) =
if (click) validForClick() else if (element != null) validFor(element) else validFor(control)
@Composable
internal fun InputActionEditor(
control: InputControl, current: InputAction, title: String, onBack: () -> Unit, onSave: (InputAction) -> Unit,
@@ -19,118 +45,114 @@ internal fun InputActionEditor(
properties: (@Composable ColumnScope.(InputAction) -> Unit)? = null,
click: Boolean = false,
) {
val context = LocalContext.current
val host = rememberMenuHost()
var draft by remember(current, title) { mutableStateOf(current) }
val drafts = remember(current, title) { mutableMapOf<String, InputAction>() }
fun typeOf(action: InputAction): String = when (action) {
is InputAction.Native -> "native"; InputAction.Disabled -> "disabled"
is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command"
is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"
is InputAction.Directions -> "directions"; is InputAction.Keys -> "keys"
}
var localType by remember(current, title) { mutableStateOf(typeOf(current).takeUnless { it == "native" || it == "disabled" } ?: "keys") }
fun switch(type: String, initial: () -> InputAction) {
drafts[typeOf(draft)] = draft
draft = drafts[type] ?: initial()
if (type != "native" && type != "disabled") localType = type
}
var keys by remember { mutableStateOf(false) }
var direction by remember { mutableStateOf<Int?>(null) }
fun valid(action: InputAction) = if (click) action.validForClick() else if (element != null) action.validFor(element) else action.validFor(control)
val nativeOptions = remember(control, element, nativeTargets, click) {
(listOf(InputAction.Native()) + if (nativeTargets) InputControl.entries.map { InputAction.Native(it) } else emptyList()).filter(::valid)
}
val route = when (draft) { is InputAction.Native -> 0; InputAction.Disabled -> 2; else -> 1 }
val draft = remember(current, title) { InputActionDraft(current) }
BackHandler(onBack = onBack)
SettingsPage(host, title, onBack, eyebrow = stringResource(R.string.input_properties), lede = detail,
action = { PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = valid(draft),
modifier = Modifier.testTag("input-action-save")) { onSave(draft) } }) {
properties?.invoke(this, draft)
action = { PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = draft.action.validAs(control, element, click),
modifier = Modifier.testTag("input-action-save")) { onSave(draft.action) } }) {
properties?.invoke(this, draft.action)
Spacer(Modifier.height(12.dp))
SheetChips(listOf(stringResource(R.string.input_route_controller), stringResource(R.string.input_route_local), stringResource(R.string.input_disabled)), route) {
when (it) {
0 -> switch("native") { nativeOptions.firstOrNull() ?: InputAction.Disabled }
2 -> switch("disabled") { InputAction.Disabled }
else -> switch(localType) { InputAction.Keys(listOf(28)) }
}
InputActionFields(host, control, draft, element, nativeTargets, click)
}
}
/** Where an action goes (the controller, DroidDeck's own input, or nowhere) and its settings. Edits [draft] in place. */
@Composable
internal fun InputActionFields(
host: MenuHost, control: InputControl, draft: InputActionDraft,
element: InputSurfaceElement? = null, nativeTargets: Boolean = true, click: Boolean = false,
) {
val context = LocalContext.current
var keys by remember { mutableStateOf(false) }
var direction by remember { mutableStateOf<Int?>(null) }
val nativeOptions = remember(control, element, nativeTargets, click) {
(listOf(InputAction.Native()) + if (nativeTargets) InputControl.entries.map { InputAction.Native(it) } else emptyList())
.filter { it.validAs(control, element, click) }
}
val route = when (draft.action) { is InputAction.Native -> 0; InputAction.Disabled -> 2; else -> 1 }
SheetChips(listOf(stringResource(R.string.input_route_controller), stringResource(R.string.input_route_local), stringResource(R.string.input_disabled)), route) {
when (it) {
0 -> draft.switch("native") { nativeOptions.firstOrNull() ?: InputAction.Disabled }
2 -> draft.switch("disabled") { InputAction.Disabled }
else -> draft.switch(draft.localType) { InputAction.Keys(listOf(28)) }
}
Spacer(Modifier.height(16.dp))
when (route) {
0 -> SettingsGroup(stringResource(R.string.input_route_controller)) {
ChoiceRow(host, "native-target", stringResource(R.string.input_remap_native), stringResource(R.string.input_controller_route_hint),
nativeOptions.map { it to (it.target?.label ?: stringResource(if (nativeTargets) R.string.input_native else R.string.input_normal_binding)) },
draft as InputAction.Native) { draft = it }
}
2 -> Text(stringResource(R.string.input_disabled_hint), Modifier.padding(16.dp))
else -> {
val types = listOf("keys" to stringResource(R.string.input_keys), "mouse" to stringResource(R.string.input_mouse_click),
"command" to stringResource(R.string.input_command)) + if (control.dimensions == 2) listOf(
"pointer" to stringResource(R.string.input_pointer), "scroll" to stringResource(R.string.input_scroll),
"directions" to stringResource(R.string.input_direction_keys)) else emptyList()
val type = when (draft) { is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command";
is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"; is InputAction.Directions -> "directions"; else -> "keys" }
SettingsGroup(stringResource(R.string.input_action)) {
ChoiceRow(host, "action-type", stringResource(R.string.input_action), null, types, type) {
switch(it) { when (it) { "mouse" -> InputAction.MouseButton(272); "command" -> InputAction.Command(InputCommand.MENU);
"pointer" -> InputAction.Pointer(); "scroll" -> InputAction.Scroll();
"directions" -> InputAction.Directions(103, 106, 108, 105); else -> InputAction.Keys(listOf(28)) } }
}
Spacer(Modifier.height(16.dp))
when (route) {
0 -> SettingsGroup(stringResource(R.string.input_route_controller)) {
ChoiceRow(host, "native-target", stringResource(R.string.input_remap_native), stringResource(R.string.input_controller_route_hint),
nativeOptions.map { it to (it.target?.label ?: stringResource(if (nativeTargets) R.string.input_native else R.string.input_normal_binding)) },
draft.action as InputAction.Native) { draft.action = it }
}
2 -> Text(stringResource(R.string.input_disabled_hint), Modifier.padding(16.dp))
else -> {
val types = listOf("keys" to stringResource(R.string.input_keys), "mouse" to stringResource(R.string.input_mouse_click),
"command" to stringResource(R.string.input_command)) + if (control.dimensions == 2) listOf(
"pointer" to stringResource(R.string.input_pointer), "scroll" to stringResource(R.string.input_scroll),
"directions" to stringResource(R.string.input_direction_keys)) else emptyList()
val type = when (draft.action) { is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command";
is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"; is InputAction.Directions -> "directions"; else -> "keys" }
SettingsGroup(stringResource(R.string.input_action)) {
ChoiceRow(host, "action-type", stringResource(R.string.input_action), null, types, type) {
draft.switch(it) { when (it) { "mouse" -> InputAction.MouseButton(272); "command" -> InputAction.Command(InputCommand.MENU);
"pointer" -> InputAction.Pointer(); "scroll" -> InputAction.Scroll();
"directions" -> InputAction.Directions(103, 106, 108, 105); else -> InputAction.Keys(listOf(28)) } }
}
if (!click && draft.action !is InputAction.Pointer && draft.action !is InputAction.Scroll && draft.action !is InputAction.Directions) {
val hint = when {
control.isTrackpad -> R.string.input_contact_action_hint
control.dimensions == 2 -> R.string.input_axis_action_hint
control == InputControl.LT || control == InputControl.RT -> R.string.input_trigger_action_hint
else -> null
}
if (!click && draft !is InputAction.Pointer && draft !is InputAction.Scroll && draft !is InputAction.Directions) {
val hint = when {
control.isTrackpad -> R.string.input_contact_action_hint
control.dimensions == 2 -> R.string.input_axis_action_hint
control == InputControl.LT || control == InputControl.RT -> R.string.input_trigger_action_hint
else -> null
}
hint?.let { Text(stringResource(it), Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) }
hint?.let { Text(stringResource(it), Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) }
}
when (val action = draft.action) {
is InputAction.Keys -> ActionRow(stringResource(R.string.input_keys), actionLabel(action), stringResource(R.string.ctrl_edit), { keys = true })
is InputAction.MouseButton -> ChoiceRow(host, "mouse-button", stringResource(R.string.input_mouse_click), null,
(272..274).map { it to actionLabel(InputAction.MouseButton(it)) }, action.code) { draft.action = InputAction.MouseButton(it) }
is InputAction.Command -> ChoiceRow(host, "command", stringResource(R.string.input_command), null,
InputCommand.entries.map { it to commandLabel(it) }, action.command) { draft.action = InputAction.Command(it) }
is InputAction.Pointer -> {
Text(stringResource(R.string.input_pointer_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface)
Slider(action.speed, { draft.action = action.copy(speed = it) }, valueRange = 100f..3000f, modifier = Modifier.padding(horizontal = 16.dp))
}
when (val action = draft) {
is InputAction.Keys -> ActionRow(stringResource(R.string.input_keys), actionLabel(action), stringResource(R.string.ctrl_edit), { keys = true })
is InputAction.MouseButton -> ChoiceRow(host, "mouse-button", stringResource(R.string.input_mouse_click), null,
(272..274).map { it to actionLabel(InputAction.MouseButton(it)) }, action.code) { draft = InputAction.MouseButton(it) }
is InputAction.Command -> ChoiceRow(host, "command", stringResource(R.string.input_command), null,
InputCommand.entries.map { it to commandLabel(it) }, action.command) { draft = InputAction.Command(it) }
is InputAction.Pointer -> {
Text(stringResource(R.string.input_pointer_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface)
Slider(action.speed, { draft = action.copy(speed = it) }, valueRange = 100f..3000f, modifier = Modifier.padding(horizontal = 16.dp))
is InputAction.Scroll -> {
ChoiceRow(host, "scroll-axis", stringResource(R.string.input_scroll_axis), null,
listOf(false to stringResource(R.string.input_vertical), true to stringResource(R.string.input_horizontal)), action.horizontal) {
draft.action = action.copy(horizontal = it)
}
is InputAction.Scroll -> {
ChoiceRow(host, "scroll-axis", stringResource(R.string.input_scroll_axis), null,
listOf(false to stringResource(R.string.input_vertical), true to stringResource(R.string.input_horizontal)), action.horizontal) {
draft = action.copy(horizontal = it)
}
Text(stringResource(R.string.input_scroll_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface)
Slider(action.speed, { draft = action.copy(speed = it) }, valueRange = 1f..60f, modifier = Modifier.padding(horizontal = 16.dp))
}
is InputAction.Directions -> {
ToggleRow(host, "direction-diagonals", stringResource(R.string.input_diagonal_keys), stringResource(R.string.input_diagonal_keys_hint), action.diagonals != null) {
draft = action.copy(diagonals = if (it) action.diagonals ?: listOf(0, 0, 0, 0) else null)
}
val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty()
val arrows = listOf("↑", "→", "↓", "←", "↗", "↘", "↙", "↖")
codes.forEachIndexed { i, code ->
ActionRow(arrows[i], if (code == 0) stringResource(if (i < 4) R.string.input_disabled else R.string.input_diagonal_neighbors) else pcKeyLabel(context, code), stringResource(R.string.ctrl_edit), { direction = i })
}
}
else -> Unit
Text(stringResource(R.string.input_scroll_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface)
Slider(action.speed, { draft.action = action.copy(speed = it) }, valueRange = 1f..60f, modifier = Modifier.padding(horizontal = 16.dp))
}
is InputAction.Directions -> {
ToggleRow(host, "direction-diagonals", stringResource(R.string.input_diagonal_keys), stringResource(R.string.input_diagonal_keys_hint), action.diagonals != null) {
draft.action = action.copy(diagonals = if (it) action.diagonals ?: listOf(0, 0, 0, 0) else null)
}
val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty()
val arrows = listOf("↑", "→", "↓", "←", "↗", "↘", "↙", "↖")
codes.forEachIndexed { i, code ->
ActionRow(arrows[i], if (code == 0) stringResource(if (i < 4) R.string.input_disabled else R.string.input_diagonal_neighbors) else pcKeyLabel(context, code), stringResource(R.string.ctrl_edit), { direction = i })
}
}
else -> Unit
}
}
}
}
if (keys) KeyCombinationPicker(onDismiss = { keys = false }, initial = (draft as? InputAction.Keys)?.codes.orEmpty(),
if (keys) KeyCombinationPicker(onDismiss = { keys = false }, initial = (draft.action as? InputAction.Keys)?.codes.orEmpty(),
sequence = true, sequenceLimit = 8, title = stringResource(R.string.input_keys), confirm = stringResource(R.string.gesture_save_changes), onAdd = {
draft = InputAction.Keys(it.sortedBy { code -> if (code in PC_MODIFIERS) 0 else 1 }); keys = false
draft.action = InputAction.Keys(it.sortedBy { code -> if (code in PC_MODIFIERS) 0 else 1 }); keys = false
})
direction?.let { at ->
val action = draft as? InputAction.Directions ?: return@let
val action = draft.action as? InputAction.Directions ?: return@let
val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty()
KeyCombinationPicker(onDismiss = { direction = null }, initial = listOf(codes[at]).filter { it != 0 }, sequence = true, sequenceLimit = 1, allowEmpty = true,
title = stringResource(R.string.input_direction_keys), confirm = stringResource(R.string.gesture_save_changes), onAdd = {
val next = codes.toMutableList().also { values -> values[at] = it.firstOrNull() ?: 0 }
draft = InputAction.Directions(next[0], next[1], next[2], next[3], if (action.diagonals != null) next.drop(4) else null); direction = null
draft.action = InputAction.Directions(next[0], next[1], next[2], next[3], if (action.diagonals != null) next.drop(4) else null); direction = null
})
}
}
@@ -0,0 +1,193 @@
package com.droiddeck.launcher.ui
import android.view.KeyEvent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
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.
*/
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,
)
@Composable
internal fun InputEditorWindow(target: InputEditorTarget, onDismiss: () -> Unit, onChanged: () -> 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)
}
} else InputSurfaceDialog(target.profile, onDismiss, onChanged, role = target.role, layoutId = target.layout, bindingsId = target.bindings)
}
private val controllerKeys = mapOf(
KeyEvent.KEYCODE_BUTTON_A to InputControl.A, KeyEvent.KEYCODE_BUTTON_B to InputControl.B,
KeyEvent.KEYCODE_BUTTON_X to InputControl.X, KeyEvent.KEYCODE_BUTTON_Y to InputControl.Y,
KeyEvent.KEYCODE_BUTTON_L1 to InputControl.LB, KeyEvent.KEYCODE_BUTTON_R1 to InputControl.RB,
KeyEvent.KEYCODE_BUTTON_L2 to InputControl.LT, KeyEvent.KEYCODE_BUTTON_R2 to InputControl.RT,
KeyEvent.KEYCODE_BUTTON_THUMBL to InputControl.L3, KeyEvent.KEYCODE_BUTTON_THUMBR to InputControl.R3,
KeyEvent.KEYCODE_BUTTON_SELECT to InputControl.SELECT, KeyEvent.KEYCODE_BUTTON_START to InputControl.START,
KeyEvent.KEYCODE_BUTTON_MODE to InputControl.GUIDE,
KeyEvent.KEYCODE_DPAD_UP to InputControl.UP, KeyEvent.KEYCODE_DPAD_RIGHT to InputControl.RIGHT,
KeyEvent.KEYCODE_DPAD_DOWN to InputControl.DOWN, KeyEvent.KEYCODE_DPAD_LEFT to InputControl.LEFT,
)
/** The control a controller key press stands for, when it is one of the standard gamepad keys. */
internal fun controlForKey(keyCode: Int): InputControl? = controllerKeys[keyCode]
/**
* Buttons and sticks: tap a control on a drawing of the controller, or press it, then set what it does. Saves into the
* bindings [bindingsId]; [baseId] is the profile's own bindings when these are a game's copy, so a control can go back.
*/
@Composable
internal fun InputButtonsPane(bindingsId: String, scope: String, baseId: String?, onBack: () -> Unit, onChanged: () -> Unit,
onMore: (() -> Unit)? = null) {
val context = LocalContext.current
val host = rememberMenuHost()
val library by rememberInputLibrary()
val preset = library.bindings.firstOrNull { it.id == bindingsId } ?: 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) }
var failure by remember { mutableStateOf<String?>(null) }
val current = preset.controls[selected] ?: InputAction.Native()
val draft = remember(selected, current) { 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)) }) } }
.onSuccess { onChanged() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
val changed = InputControl.padControls.filter { c ->
(preset.controls[c] ?: InputAction.Native()) != (base?.controls?.get(c) ?: InputAction.Native())
}
BackHandlerCompat(onBack)
BoxWithConstraints(Modifier.fillMaxSize().padding(16.dp).onPreviewKeyEvent { event ->
val control = controlForKey(event.nativeKeyEvent.keyCode)
if (!capturing || control == null) return@onPreviewKeyEvent false
if (event.nativeKeyEvent.action == KeyEvent.ACTION_UP) { selected = control; capturing = false }
true
}.testTag("input-buttons")) {
val wide = maxWidth > 700.dp
val boxWidth = maxWidth
val pad: @Composable (Modifier) -> Unit = { modifier ->
Column(modifier, verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.flow_buttons), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f, fill = false))
ScopePill(stringResource(R.string.flow_saving_for, scope))
}
Text(stringResource(if (capturing) R.string.flow_press_now else R.string.flow_buttons_hint), fontSize = 13.sp,
color = if (capturing) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant)
Box((if (wide) Modifier.fillMaxWidth().weight(1f) else Modifier.fillMaxWidth().height(boxWidth * .6f)).clip(RoundedCornerShape(14.dp)).background(MaterialTheme.colorScheme.background)
.border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(14.dp))) {
ControllerDrawing(selected, Modifier.fillMaxSize()) { selected = it }
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(stringResource(if (capturing) R.string.common_cancel else R.string.flow_press), compact = true,
modifier = Modifier.testTag("input-buttons-press")) { capturing = !capturing }
onMore?.let { SecondaryButton(stringResource(R.string.flow_more_buttons), compact = true, onClick = it) }
}
OtherControls(selected) { selected = it }
val summaries = mutableListOf<String>()
for (c in changed) summaries += "${c.label} → ${actionLabel(preset.controls[c] ?: InputAction.Native())}"
if (summaries.isNotEmpty()) Text(summaries.joinToString(" · "),
fontSize = 13.sp, color = MaterialTheme.colorScheme.primary, modifier = Modifier.testTag("input-buttons-changed"))
}
}
val panel: @Composable (Modifier) -> Unit = { modifier ->
Column(if (wide) modifier.verticalScroll(rememberScrollState()) else modifier) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(selected.label, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.weight(1f))
SecondaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onBack)
}
Spacer(Modifier.height(12.dp))
InputActionFields(host, selected, draft)
Spacer(Modifier.height(12.dp))
Actions {
PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = draft.action != current && draft.action.validFor(selected),
modifier = Modifier.testTag("input-buttons-save")) { save(draft.action) }
val profileAction = base?.controls?.get(selected) ?: InputAction.Native()
if (base != null && current != profileAction) SecondaryButton(stringResource(R.string.flow_profile_binding, actionLabel(profileAction)),
modifier = Modifier.testTag("input-buttons-reset")) { save(profileAction) }
}
}
}
if (wide) Row(horizontalArrangement = Arrangement.spacedBy(20.dp)) { pad(Modifier.weight(1.2f).fillMaxHeight()); panel(Modifier.weight(1f)) }
else Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp)) {
pad(Modifier.fillMaxWidth()); panel(Modifier.fillMaxWidth())
}
}
failure?.let { message -> androidx.compose.material3.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)) } }) }
}
@Composable
private fun BackHandlerCompat(onBack: () -> Unit) = androidx.activity.compose.BackHandler(onBack = onBack)
@Composable
internal fun ScopePill(text: String) {
Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.primary,
modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.primary.copy(alpha = .14f)).padding(horizontal = 8.dp, vertical = 4.dp))
}
/** The standard pad, drawn with the selected virtual controller's art; tapping a control picks it. */
@Composable
private fun ControllerDrawing(selected: InputControl, modifier: Modifier, onPick: (InputControl) -> Unit) {
val context = LocalContext.current
val pick by rememberUpdatedState(onPick)
AndroidView(factory = { InputSurfaceEditorView(it).apply { selectOnly = true; setBackgroundColor(android.graphics.Color.TRANSPARENT) } },
modifier = modifier.testTag("input-buttons-pad"), update = { view ->
view.onSelect = { id -> id?.removePrefix("legacy:")?.let(InputControl::fromId)?.let(pick) }
view.onResize = { _, _ -> }
fun place() {
if (view.width <= 0 || view.height <= 0) return
val stock = LegacyGamepadLayout(context, view.width, view.height).elements().filter { it.id.startsWith("legacy:") }
val layout = SavedInputLayout(InputLibraries.OVERLAY, "", stock)
view.sourceLayout = layout
view.aspect = view.width.toFloat() / view.height
view.elements = OnScreenLayout.editorElements(context, layout, view.width, view.height).filter { it.id.startsWith("legacy:") }
}
view.selected = "legacy:${selected.id}"
if (view.elements.isEmpty()) view.post { place() }
})
}
/** Controls the drawing doesn't show: back buttons, Steam and Quick Access, stick clicks and trackpads. */
@Composable
private fun OtherControls(selected: InputControl, onPick: (InputControl) -> Unit) {
val others = listOf(InputControl.L3, InputControl.R3, InputControl.L4, InputControl.R4, InputControl.L5, InputControl.R5,
InputControl.GUIDE, InputControl.QAM, InputControl.LEFT_PAD, InputControl.RIGHT_PAD, InputControl.LEFT_CLICK, InputControl.RIGHT_CLICK)
Text(stringResource(R.string.flow_other_controls), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
@OptIn(ExperimentalLayoutApi::class)
FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
for (control in others) {
if (control == selected) PrimaryButton(control.label, compact = true, modifier = Modifier.testTag("input-other-${control.id}")) { onPick(control) }
else SecondaryButton(control.label, compact = true, modifier = Modifier.testTag("input-other-${control.id}")) { onPick(control) }
}
}
}
@@ -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, BUTTONS, SOURCE, LAYOUTS, REUSE }
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)
@@ -101,7 +101,6 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
var error by remember { mutableStateOf<String?>(null) }
val scope = rememberCoroutineScope()
val controller = rememberControllerSettings()
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 }
@@ -110,7 +109,8 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
edit != null -> edit = null
page == InputPage.HOME -> onBack()
page == InputPage.PROFILE -> go(InputPage.HOME)
page == InputPage.SOURCE -> go(InputPage.PROFILE)
page == InputPage.SOURCE && role == InputRole.PHYSICAL -> go(InputPage.BUTTONS)
page == InputPage.SOURCE || page == InputPage.BUTTONS -> go(InputPage.PROFILE)
else -> go(InputPage.SOURCE)
}
}
@@ -124,9 +124,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
scope.launch {
val raw = withContext(Dispatchers.IO) { readLayoutFile(context, uri) }
val metrics = inputDisplayMetrics(context, target)
val imported = raw?.let { InputLayoutFile.import(context, it, layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout),
if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, layout?.style ?: InputSurfaceStyle(),
metrics.widthPixels, metrics.heightPixels, metrics.density) }
val screen = if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY
val name = layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout)
val imported = raw?.let {
if (WinlatorLayouts.isIcp(it)) WinlatorLayouts.import(it, name, screen, metrics.widthPixels, metrics.heightPixels)
else InputLayoutFile.import(context, it, name, screen, layout?.style ?: InputSurfaceStyle(), metrics.widthPixels, metrics.heightPixels, metrics.density)
}
if (imported == null) error = context.getString(R.string.input_layout_import_failed)
else if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, target, imported.first.id) }) go(InputPage.SOURCE)
}
@@ -185,10 +188,14 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
else -> currentPreset.copy(controls = currentPreset.controls + (editing.control to action))
}) }) edit = null
})
} else if (!surface && page == InputPage.BUTTONS) {
InputButtonsPane(profile.binding(InputRole.PHYSICAL), profile.name, null, onBack = ::back, onChanged = { library = InputLibraries.read(context); onChanged() },
onMore = { role = InputRole.PHYSICAL; bindingsTab = 2; go(InputPage.SOURCE) })
} else if (!surface) key(page, profileId, role) {
SettingsPage(host, title = when (page) {
InputPage.HOME -> if (embedded) null else stringResource(R.string.setup_controller)
InputPage.PROFILE -> profile.name
InputPage.BUTTONS -> stringResource(R.string.flow_buttons)
InputPage.SOURCE -> roleLabel(role)
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
@@ -200,30 +207,45 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
when (page) {
InputPage.HOME -> {
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) } }
ChoiceRow(host, "auto-game", stringResource(R.string.input_game_mode), null,
library.profiles.map { it.id to it.name }, library.steam) { id -> update { it.copy(steam = id) } }
for (desktop in listOf(true, false)) {
val selection = library.selection(desktop)
if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint,
stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode)))
}
}
if (InputLibraries.hasPendingScreenKeyMigration(context)) InputHint(stringResource(R.string.input_import_failed))
if (InputLibraries.hasLibraryRecovery(context)) InputHint(stringResource(R.string.input_library_recovered))
if (library.profiles.any { it.id.startsWith("migrated.screenkeys.") }) Text(stringResource(R.string.input_imported_keys_hint),
Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
SettingsGroup(stringResource(R.string.input_profiles)) {
for (p in library.profiles) InputNavigationRow(p.name, when {
p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both)
p.id == library.steam -> stringResource(R.string.input_default_game)
p.id == library.desktop -> stringResource(R.string.input_default_desktop)
else -> null
}, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) }
for (p in library.profiles) {
val pinned = library.games.values.count { it.profile == p.id }
val uses = listOfNotNull(when {
p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both)
p.id == library.steam -> stringResource(R.string.input_default_game)
p.id == library.desktop -> stringResource(R.string.input_default_desktop)
else -> null
}, if (pinned > 0) stringResource(R.string.flow_used_games, pinned) else null)
InputNavigationRow(p.name, uses.joinToString(" · ").ifEmpty { null }, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) }
}
for (desktop in listOf(true, false)) {
val selection = library.selection(desktop)
if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint,
stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode)))
}
PadTextButton(onClick = { newProfile(false) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_profile)) }
}
if (library.games.isNotEmpty()) SettingsGroup(stringResource(R.string.flow_games)) {
InputHint(stringResource(R.string.flow_games_hint))
for ((key, game) in library.games.entries.sortedBy { it.value.name.lowercase() }) {
val pinned = game.profile?.let { id -> library.profiles.firstOrNull { it.id == id }?.name }
val changes = library.gameChanges(false, key)
ActionRow(game.name, listOfNotNull(pinned, if (changes > 0) stringResource(R.string.flow_game_changes, game.name, changes) else null)
.joinToString(" · ").ifEmpty { null }, stringResource(R.string.ctrl_reset), { update { it.resetGame(key) } },
modifier = Modifier.testTag("input-game-$key"))
}
}
SettingsGroup(stringResource(R.string.flow_touch_controls)) {
var touch by remember { mutableStateOf(ControllerPrefs.read(context)) }
SliderRow(stringResource(R.string.ctrl_size), null, touch.size, ControllerPrefs.sizes.first()..ControllerPrefs.sizes.last(), step = 5,
format = { "$it%" }) { ControllerPrefs.setSize(context, it); touch = ControllerPrefs.read(context); onChanged() }
SliderRow(stringResource(R.string.ctrl_opacity), null, touch.onScreenOpacity, ControllerPrefs.onScreenOpacityRange, step = 5,
format = { "$it%" }) { ControllerPrefs.setOnScreenOpacity(context, it); touch = ControllerPrefs.read(context); onChanged() }
}
SettingsGroup(stringResource(R.string.input_device_settings)) {
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, controller.rumble) { ControllerPrefs.setRumble(context, it); onChanged() }
ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, controller.deadZone) { ControllerPrefs.setDeadZone(context, it); onChanged() }
@@ -246,12 +268,32 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
}
InputPage.PROFILE -> {
val uses = when {
library.steam == profileId && library.desktop == profileId -> "both"
library.steam == profileId -> "game"
library.desktop == profileId -> "desktop"
else -> "none"
}
val builtIn = profileId == InputProfile.GAME || profileId == InputProfile.DESKTOP
SettingsGroup(stringResource(R.string.flow_default_for)) {
ChoiceRow(host, "profile-default", stringResource(R.string.flow_default_for), null, listOfNotNull(
"game" to stringResource(R.string.input_game_mode), "desktop" to stringResource(R.string.input_desktop_mode),
"both" to stringResource(R.string.flow_both_modes), if (builtIn) null else "none" to stringResource(R.string.flow_no_mode)), uses) { pick ->
update { l ->
l.copy(steam = if (pick == "game" || pick == "both") profileId else if (l.steam == profileId) InputProfile.GAME else l.steam,
desktop = if (pick == "desktop" || pick == "both") profileId else if (l.desktop == profileId) InputProfile.DESKTOP else l.desktop)
}
}
}
SettingsGroup(stringResource(R.string.input_profile_controls)) {
for (r in InputRole.entries) InputNavigationRow(roleLabel(r),
if (r == InputRole.PHYSICAL) stringResource(R.string.input_physical_hint) else library.layout(profileId, r)?.name,
Modifier.testTag("input-part-${r.name.lowercase()}"), leading = {
library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) }
}) { editPart(r) }
InputNavigationRow(stringResource(R.string.flow_buttons), stringResource(R.string.input_physical_hint),
Modifier.testTag("input-part-physical")) { role = InputRole.PHYSICAL; go(InputPage.BUTTONS) }
for (r in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) {
InputNavigationRow(if (r == InputRole.PRIMARY) stringResource(R.string.flow_layout) else roleLabel(r), library.layout(profileId, r)?.name,
Modifier.testTag("input-part-${r.name.lowercase()}"), leading = {
library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) }
}) { editPart(r) }
}
}
Spacer(Modifier.height(16.dp))
Actions {
@@ -276,19 +318,9 @@ 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))) } }
}
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } }
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)) } }
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
SettingsGroup(stringResource(R.string.input_assign_actions)) {
val users = library.usersOfBindings(preset.id)
if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name }))
@@ -324,8 +356,15 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
}
InputPage.LAYOUTS -> {
InputHint(stringResource(R.string.input_layout_geometry_hint))
SettingsGroup(stringResource(R.string.input_saved_layouts)) {
var community by remember { mutableStateOf(false) }
Box(Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {
SheetChips(listOf(stringResource(R.string.flow_mine), stringResource(R.string.flow_community)), if (community) 1 else 0) { community = it == 1 }
}
if (community) CommunityLayouts(role) { imported ->
if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, role, imported.first.id) }) go(InputPage.SOURCE)
}
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 other = available.filter { saved -> !saved.id.startsWith("builtin.") && saved.id != layout?.id &&
@@ -350,6 +389,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
}
}
InputPage.BUTTONS -> Unit
InputPage.REUSE -> {
InputHint(stringResource(R.string.input_reuse_explanation, roleLabel(role)))
SettingsGroup(stringResource(R.string.input_profiles)) {
@@ -88,6 +88,8 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var toolsX by mutableFloatStateOf(-1f)
var toolsY by mutableFloatStateOf(.02f)
var snap by mutableStateOf(snap)
var grid by mutableIntStateOf(0)
var hidden by mutableStateOf(layout.style.hidden)
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
@@ -117,9 +119,11 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
}
val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale ||
aspect != layout.aspect || hidden != layout.style.hidden
private var lastAssigned: String? = null
fun checkpoint() { lastAssigned = null; history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { lastAssigned = null; history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
private fun adoptDisplayedFrame(context: android.content.Context): Boolean {
if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false
val open = toolsExpanded
@@ -203,6 +207,34 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
elements = elements.map { if (it.id == element.id) element else it }
}
/** A D-pad arm is part of one control and can't be copied on its own. */
fun canDuplicate(e: InputSurfaceElement) = !e.dpadPiece && elements.size < 64
/** Adds a copy of [id] next to it, doing what the original does, and selects it. */
fun duplicate(id: String) {
val original = (elements.firstOrNull { it.id == id } ?: shown.firstOrNull { it.id == id })?.takeIf(::canDuplicate) ?: return
if (elements.any { it.id == id }) checkpoint() else stored(id)
val copy = original.copy(id = newInputId(), control = original.kind.control,
x = original.x + .03f, y = original.y + .03f).bounded()
fun resolved(action: InputAction) = if (action is InputAction.Native && action.target == null && original.kind != InputElementKind.DPAD)
InputAction.Native(original.control) else action
val action = resolved(action(original)).takeIf { it.validFor(copy) } ?: InputAction.Disabled
elements = elements + copy
actions = actions + (copy.id to action)
if (copy.hasClick) clickAction(original).takeIf { it.validForClick() }?.let { clicks = clicks + (copy.id to it) }
selected = copy.id
}
/** Sets what [id] does (or, with [click], what clicking it does), keeping one undo step per control. */
fun assign(id: String, action: InputAction, click: Boolean) {
val e = elements.firstOrNull { it.id == id } ?: shown.firstOrNull { it.id == id } ?: return
if (if (click) clickAction(e) == action else action(e) == action) return
val key = "$id/$click"
if (lastAssigned != key) { checkpoint(); lastAssigned = key }
stored(id)
if (click) clicks = clicks + (id to action) else actions = actions + (id to action)
}
fun resetPositions(context: android.content.Context) {
val adopted = adoptDisplayedFrame(context)
positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f }
@@ -229,6 +261,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
.also { it.grid = ControllerPrefs.editorGrid(context) }
}
val manager = remember { context.getSystemService(DisplayManager::class.java) }
var revision by remember { mutableIntStateOf(0) }
@@ -249,7 +282,8 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
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)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == 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 } }))
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
@@ -323,7 +357,9 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
else -> Box(Modifier.fillMaxSize()) {
SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY)
FloatingSurfaceTools(draft, ::save, ::leave)
val selected = draft.element
if (selected != null) DockedElementPanel(draft, selected, ::save)
else FloatingSurfaceTools(draft, ::save, ::leave)
}
}
}
@@ -356,6 +392,7 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.grid = if (draft.grid > 0) 1f / draft.grid else 0f
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) }
view.onResize = { w, h -> draft.canvas = IntSize(w, h) }
@@ -415,10 +452,55 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav
}
}
/** The selected control's settings, docked on the side of the screen away from it so it never covers what is being edited. */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun DockedElementPanel(draft: SurfaceDraft, element: InputSurfaceElement, onSave: () -> Unit) {
val context = LocalContext.current
val host = rememberMenuHost()
val onRight = element.x + element.width / 2 < .5f
var click by remember(element.id) { mutableStateOf(false) }
val clicking = click && element.hasClick
val current = if (clicking) draft.clickAction(element) else draft.action(element)
val actionDraft = remember(element.id, clicking) { InputActionDraft(current) }
val control = if (clicking) InputControl.A else element.control
LaunchedEffect(actionDraft.action) {
if (actionDraft.action.validAs(control, element.takeUnless { clicking }, clicking)) draft.assign(element.id, actionDraft.action, clicking)
}
BoxWithConstraints(Modifier.fillMaxSize()) {
Surface(Modifier.align(if (onRight) Alignment.CenterEnd else Alignment.CenterStart).padding(8.dp)
.width(minOf(380.dp, maxWidth * .48f)).fillMaxHeight().testTag("input-editor-panel"),
shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface, tonalElevation = 6.dp, shadowElevation = 10.dp) {
Column {
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(element.name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, modifier = Modifier.testTag("input-editor-done"), onClick = onSave)
}
Column(Modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, bottom = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (element.hasClick) SheetChips(listOf(stringResource(R.string.input_action), stringResource(R.string.input_click_name, element.name)),
if (clicking) 1 else 0) { click = it == 1 }
InputActionFields(host, control, actionDraft, element.takeUnless { clicking }, click = clicking)
if (!clicking) InputElementProperties(element, actionDraft.action) { draft.update(it) }
SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleSelected(context, it) }
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
SecondaryButton(stringResource(R.string.flow_duplicate), enabled = draft.canDuplicate(element), compact = true,
modifier = Modifier.testTag("input-editor-duplicate")) { draft.duplicate(element.id) }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(element.id) }
SecondaryButton(stringResource(R.string.common_close), compact = true) { draft.selected = null }
}
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) {
val context = LocalContext.current
val host = rememberMenuHost()
FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true }
@@ -432,6 +514,14 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
}
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { if (draft.element != null) draft.scaleSelected(context, it) else draft.scaleAll(context, it) }
ChoiceRow(host, "editor-grid", stringResource(R.string.flow_grid), null,
ControllerPrefs.editorGrids.map { it to stringResource(when (it) { 0 -> R.string.widgets_off; 50 -> R.string.flow_grid_fine; else -> R.string.flow_grid_coarse }) },
draft.grid) { draft.grid = it; ControllerPrefs.setEditorGrid(context, it) }
for (button in QUICK_BUTTONS.filter { b -> draft.elements.any { it.quickButton == b } }) {
ToggleRow(host, "editor-quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null, button !in draft.hidden) { shown ->
draft.hidden = if (shown) draft.hidden - button else draft.hidden + button
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@@ -38,6 +38,12 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
set(value) { field = value; updatePreviewStyle() }
var snap = true
set(value) { field = value; if (!value) clearGuides() }
/** Grid spacing as a fraction of the width; 0 for no grid. */
var grid = 0f
set(value) { field = value; invalidate() }
/** Taps select a control; nothing moves. */
var selectOnly = false
private val gridPaint = Paint().apply { color = Color.argb(40, 255, 255, 255); strokeWidth = 1f }
private var guideX: Float? = null
private var guideY: Float? = null
var selected: String? = null
@@ -99,6 +105,13 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
}
override fun dispatchDraw(canvas: Canvas) {
if (grid > 0f && !selectOnly && width > 0) {
val step = grid * width
var x = step
while (x < width) { canvas.drawLine(x, 0f, x, height.toFloat(), gridPaint); x += step }
var y = step
while (y < height) { canvas.drawLine(0f, y, width.toFloat(), y, gridPaint); y += step }
}
super.dispatchDraw(canvas)
paint.style = Paint.Style.STROKE
guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) }
@@ -114,6 +127,18 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
private fun clearGuides() { guideX = null; guideY = null; invalidate() }
private fun onGrid(e: InputSurfaceElement, corner: Int): InputSurfaceElement {
val sx = grid
val sy = grid * width / height.coerceAtLeast(1)
fun round(value: Float, step: Float) = (Math.round(value / step) * step)
if (corner == 0) return e.copy(x = round(e.x, sx).coerceIn(0f, 1f - e.width), y = round(e.y, sy).coerceIn(0f, 1f - e.height))
val right = if (corner and 2 != 0) round(e.x + e.width, sx).coerceIn(e.x + .03f, 1f) else e.x + e.width
val bottom = if (corner and 8 != 0) round(e.y + e.height, sy).coerceIn(e.y + .03f, 1f) else e.y + e.height
val left = if (corner and 1 != 0) round(e.x, sx).coerceIn(0f, right - .03f) else e.x
val top = if (corner and 4 != 0) round(e.y, sy).coerceIn(0f, bottom - .03f) else e.y
return e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded()
}
override fun onInterceptTouchEvent(event: MotionEvent) = true
@SuppressLint("ClickableViewAccessibility")
@@ -124,7 +149,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
clearGuides()
downX = event.x; downY = event.y; dragging = false; corner = 0
val current = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() }
if (current != null) {
if (current != null && !selectOnly) {
val left = width * current.x; val top = height * current.y
val right = left + width * current.width; val bottom = top + height * current.height
val horizontal = if (abs(downX - left) < radius) 1 else if (abs(downX - right) < radius) 2 else 0
@@ -139,7 +164,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
selected = touched?.id; onSelect(selected)
}
MotionEvent.ACTION_MOVE -> {
if (original.isEmpty()) return true
if (original.isEmpty() || selectOnly) return true
val e = original.frame()
if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) {
dragging = true; onBeginEdit(visibleElements, width, height)
@@ -160,7 +185,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
9 * resources.displayMetrics.density / height, corner) else null
if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
guideX = aligned?.x; guideY = aligned?.y
val f = aligned?.element ?: next
val f = aligned?.element ?: next.takeIf { grid > 0f }?.let { onGrid(it, corner) } ?: next
val sx = f.width / e.width; val sy = f.height / e.height
onChange(original.map { it.copy(x = f.x + (it.x - e.x) * sx, y = f.y + (it.y - e.y) * sy, width = it.width * sx, height = it.height * sy) })
invalidate()
@@ -336,17 +336,20 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
note = stringResource(R.string.mode_touch_note),
onPick = a.onTouch,
)
if (steam && s.oscMode != null) ChoiceRow(
host, "osc", stringResource(R.string.mode_osc), null,
listOf(
SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto),
SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch),
SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam),
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never),
), s.oscMode,
note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
)
if (steam && s.oscMode != null) {
val source = touchSource(s.oscMode)
ChoiceRow(
host, "osc", stringResource(R.string.flow_touch_controls), null,
listOf(TOUCH_STEAM to stringResource(R.string.osc_steam_touch), TOUCH_DROIDDECK to stringResource(R.string.flow_touch_droiddeck),
TOUCH_OFF to stringResource(R.string.widgets_off)), source,
note = stringResource(R.string.mode_osc_note),
) { a.onOsc(touchMode(it)) }
if (source == TOUCH_DROIDDECK) ChoiceRow(
host, "osc-show", stringResource(R.string.flow_show), null,
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam)), s.oscMode, onPick = a.onOsc,
)
}
if (steam && s.steamController != null) ChoiceRow(
host, "controller", stringResource(R.string.mode_controller), stringResource(R.string.mode_controller_hint),
listOf(
@@ -415,7 +415,7 @@ class SecondScreenPresentation(
}
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context), SessionState.inputGame)
private fun bar(mode: SecondScreenMode) {
val first = barModel(mode) ?: return
@@ -335,7 +335,6 @@ class DrawerActions(
val achievementsTitle: String? = null,
val achievementsProgress: Pair<Int, Int>? = null,
val onOsc: (String) -> Unit,
val onEditSteamTouch: (() -> Unit)? = null,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val onControllerSize: (Int) -> Unit = {},
val onControllerOpacity: (Int) -> Unit = {},
@@ -354,6 +353,10 @@ class DrawerActions(
val onTouch: (String) -> Unit,
val onInputSettings: () -> Unit = {},
val onInputSelection: (com.droiddeck.launcher.input.InputRole?) -> Unit = {},
/** The game in front, as its key and name, when its controls can differ from the profile's. */
val inputGame: Pair<String, String>? = null,
val onEditButtons: () -> Unit = {},
val onEditLayout: (() -> Unit)? = null,
val onGestureSettings: () -> Unit = {},
val touchActive: String = "",
val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK,
@@ -731,9 +734,7 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
val off = stringResource(R.string.widgets_off)
val padTag = if (padConnected) stringResource(R.string.drawer_tag_controller) else null
val noPadTag = if (padConnected) null else stringResource(R.string.drawer_tag_no_controller)
SettingsGroup(stringResource(R.string.drawer_section_input), key = "controller-input") {
InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings, track = track)
}
DrawerControlsGroup(host, a, track)
val c = a.controller
val padTypes = listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam),
@@ -753,12 +754,19 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
ToggleRow(host, "rumble", rumbleLabel, null, it.rumble, chipModifier = track("rumble"), onChange = a.onRumble)
}
}
val oscChoices = if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
val oscValue = if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode
SettingsGroup(stringResource(R.string.input_screen_visibility), key = "controller-osc", tag = noPadTag,
detail = summary(oscChoices.labelOf(oscValue), c?.let { "${it.size}%" })) {
ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, oscChoices, oscValue, chipModifier = track("osc"), onPick = a.onOsc)
val source = touchSource(oscValue)
val sources = listOfNotNull(if (a.steam) TOUCH_STEAM to stringResource(R.string.osc_steam_touch) else null,
TOUCH_DROIDDECK to stringResource(R.string.flow_touch_droiddeck), TOUCH_OFF to stringResource(R.string.widgets_off))
val shows = listOfNotNull(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
if (a.steam) SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam) else null)
SettingsGroup(stringResource(R.string.flow_touch_controls), key = "controller-osc", tag = noPadTag,
detail = summary(sources.labelOf(source), if (source == TOUCH_DROIDDECK) shows.labelOf(oscValue) else null, c?.let { "${it.size}%" }, c?.let { "${it.onScreenOpacity}%" })) {
ChoiceRow(host, "osc", stringResource(R.string.flow_touch_type), null, sources, source, chipModifier = track("osc")) { picked ->
a.onOsc(touchMode(picked))
}
if (source == TOUCH_DROIDDECK) ChoiceRow(host, "osc-show", stringResource(R.string.flow_show), null, shows, oscValue,
chipModifier = track("osc-show"), onPick = a.onOsc)
c?.let {
SliderRow(stringResource(R.string.ctrl_size), null, it.size, 80..125, step = 5,
format = { v -> "$v%" }, modifier = track("controller-size"), onChange = a.onControllerSize)
@@ -781,10 +789,6 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown,
chipModifier = track(key)) { a.onQuickButton(button, it) }
}
a.onEditSteamTouch?.let { edit ->
ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit,
modifier = track("steam-touch-layout"))
}
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
chipModifier = track("unfolded-controls"), onChange = a.onUnfoldedControls)
@@ -1155,6 +1159,23 @@ private fun <T> List<Pair<T, String>>.labelOf(value: T): String? = firstOrNull {
private fun summary(vararg parts: String?): String = parts.filterNot { it.isNullOrEmpty() }.joinToString(" · ")
internal const val TOUCH_STEAM = "steam"
internal const val TOUCH_DROIDDECK = "droiddeck"
internal const val TOUCH_OFF = "off"
/** Which touch controls a stored mode draws: Steam's, DroidDeck's, or none. How DroidDeck's show is the rest of the mode. */
internal fun touchSource(mode: String) = when (mode) {
SessionPrefs.OSC_STEAM_TOUCH -> TOUCH_STEAM
SessionPrefs.OSC_NEVER -> TOUCH_OFF
else -> TOUCH_DROIDDECK
}
internal fun touchMode(source: String) = when (source) {
TOUCH_STEAM -> SessionPrefs.OSC_STEAM_TOUCH
TOUCH_OFF -> SessionPrefs.OSC_NEVER
else -> SessionPrefs.OSC_AUTO
}
@Composable
private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier = Modifier, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -139,8 +139,9 @@ internal object SettingsIndex {
d(R.string.drawer_hud, R.string.drawer_hud, "fps", "counter", "overlay", "performance"),
d(R.string.drawer_hud, R.string.perf_gpuclock, "gpu", "clock", "max"),
d(R.string.drawer_page_controller, R.string.input_touchscreen, "touch", "mouse", "direct", "touchpad", "click"),
d(R.string.drawer_page_controller, R.string.mode_osc, "on-screen", "controls", "touch controls", "buttons"),
d(R.string.drawer_page_controller, R.string.osc_steam_layout, "touch layout", "edit layout", "on-screen"),
d(R.string.drawer_page_controller, R.string.flow_touch_controls, "on-screen", "controls", "steam touch", "visibility", "opacity", "size"),
d(R.string.drawer_page_controller, R.string.flow_layout, "touch layout", "edit layout", "on-screen", "osc"),
d(R.string.drawer_page_controller, R.string.flow_buttons, "remap", "mapping", "bindings", "buttons", "per game", "profile"),
d(R.string.drawer_page_controller, R.string.drawer_pc_keyboard, "keyboard", "typing"),
d(R.string.mode_session, R.string.report_problem, "logs", "log", "bug", "crash", "share", "zip"),
d(R.string.mode_session, R.string.mode_suspend, "sleep", "background", "native", "resume"),