feat(input): Settings Controller is the in-game page for the default, with per-game layouts, Just this game and a direct remap page

This commit is contained in:
Kurt Himebauch committed 2026-11-18 23:45:46 -05:00
1 parent afa696cef2
commit 446480aa19
15 files changed
+561 -570

No files matched your search

@@ -645,6 +645,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var layoutOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
private var layoutChoice by mutableStateOf("")
private var layoutEditor by mutableStateOf<Triple<String, String, String>?>(null)
private var layoutEditorScope: String? = null
private var layoutEditorSplit: com.droiddeck.launcher.ui.InputEditorSplit? = null
private var controlsGame: Long? = null
private var controllerInUse = false
private var controlsHiddenByTap = false
@@ -1258,9 +1260,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
layoutEditor = null; inputSettingsOpen = false
refreshInputProfile(); updateOnScreenControls()
}, onChanged = { refreshInputProfile() }, role = InputRole.PRIMARY, layoutId = layout, bindingsId = bindings,
scope = primaryInputLayout?.name?.let { name -> controlsGameName()?.let { getString(R.string.osc_scope_game, name, it) } ?: getString(R.string.osc_scope_default, name) })
scope = layoutEditorScope, split = layoutEditorSplit)
}
if (inputSettingsOpen && layoutEditor == null) com.droiddeck.launcher.ui.InputSettingsDialog(
desktop = loadingMode() == SessionService.MODE_DESKTOP,
onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() },
onChanged = {
controllerSettings = ControllerPrefs.read(this@SessionActivity)
@@ -1723,10 +1726,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
layoutChoice = layoutChoice,
onLayout = ::chooseLayout,
onEditLayout = when {
layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> if (steamTouchAvailable && onScreenButtonsVisible) ({
layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> steamTouchControls?.takeIf { steamTouchAvailable && onScreenButtonsVisible && it.visibility == View.VISIBLE }?.let { view -> {
drawerOpen = false
steamTouchControls?.startEditing()
}) else null
view.startEditing()
} }
primaryInputLayout?.editable == true -> ({ openLayoutEditor() })
else -> null
},
@@ -4370,56 +4373,50 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun controlsGameName(): String? = controlsGameId()?.let { frameGenTargetGameName() }
/** The input library with the current game's main-screen layout selected, without saving it. */
private fun gameLibrary(): com.droiddeck.launcher.input.InputLibrary {
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val chosen = com.droiddeck.launcher.input.GameControls.bindings(this, controlsGameId())
?.takeIf { id -> library.bindings.any { it.id == id && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true } }
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
private fun gameLibrary(): com.droiddeck.launcher.input.InputLibrary =
com.droiddeck.launcher.input.ControlsChoice.library(this, controlsGameId(), loadingMode() == SessionService.MODE_DESKTOP)
private fun refreshLayoutOptions(library: com.droiddeck.launcher.input.InputLibrary) {
private fun refreshLayoutOptions() {
val steam = SessionState.mode == SessionService.MODE_STEAM
layoutOptions = listOf(com.droiddeck.launcher.input.InputLibraries.OVERLAY to getString(R.string.osc_layout_gamepad)) +
(if (steam) listOf(com.droiddeck.launcher.input.GameControls.STEAM to getString(R.string.osc_layout_steam)) else emptyList()) +
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != com.droiddeck.launcher.input.InputLibraries.OVERLAY }.map { it.id to it.name }
layoutChoice = if (steam && com.droiddeck.launcher.input.GameControls.steamLayout(this, controlsGameId())) com.droiddeck.launcher.input.GameControls.STEAM
else primaryInputLayout?.id ?: com.droiddeck.launcher.input.InputLibraries.OVERLAY
val game = controlsGameId()
layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName())
layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, loadingMode() == SessionService.MODE_DESKTOP)
}
private fun chooseLayout(id: String) {
val game = controlsGameId()
val name = controlsGameName()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val steam = id == com.droiddeck.launcher.input.GameControls.STEAM
runCatching {
val bindings = if (steam) null else {
var library = com.droiddeck.launcher.input.InputLibraries.read(this)
val layout = library.layouts.first { it.id == id }
library.bindings.firstOrNull { !it.physical && it.compatible(layout) }?.id ?: com.droiddeck.launcher.input.newInputId().also { newId ->
library = com.droiddeck.launcher.input.InputLibraries.update(this) {
it.withPreset(com.droiddeck.launcher.input.SavedInputBindings(newId, layout.name, false, layout.id))
}
}
}
if (game != null) com.droiddeck.launcher.input.GameControls.choose(this, game, bindings, steam)
else {
SessionPrefs.setSteamTouchLayout(this, steam)
if (bindings != null) com.droiddeck.launcher.input.InputLibraries.update(this) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
}
}.onFailure { Log.w(TAG, "could not choose layout $id", it) }
val created = runCatching {
if (id == com.droiddeck.launcher.input.ControlsChoice.NEW) {
if (game != null && name != null) com.droiddeck.launcher.input.ControlsChoice.newForGame(this, game, name, desktop) else null
} else { com.droiddeck.launcher.input.ControlsChoice.choose(this, game, id, desktop, name); null }
}.onFailure { Log.w(TAG, "could not choose layout $id", it) }.getOrNull()
releasePads()
refreshInputProfile()
updateOnScreenControls()
if (created != null) openLayoutEditor()
}
private fun openLayoutEditor() {
val library = gameLibrary()
val game = controlsGameId()
val name = controlsGameName()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val layout = primaryInputLayout ?: return
val target = com.droiddeck.launcher.input.ControlsChoice.editTarget(this, game, desktop) ?: return
val layoutName = com.droiddeck.launcher.input.InputLibraries.read(this).layouts.firstOrNull { it.id == target.second }?.name ?: return
val own = com.droiddeck.launcher.input.ControlsChoice.hasOwn(this, game)
val shared = com.droiddeck.launcher.input.ControlsChoice.shared(this, game)
layoutEditorScope = when {
game == null || name == null || !own -> getString(R.string.osc_scope_default, layoutName)
shared -> getString(R.string.osc_scope_shared, layoutName)
layoutName == name -> getString(R.string.osc_scope_own, name)
else -> getString(R.string.osc_scope_game, layoutName, name)
}
layoutEditorSplit = if (game != null && name != null && shared) com.droiddeck.launcher.ui.InputEditorSplit(getString(R.string.osc_just_this_game),
getString(R.string.osc_scope_game, layoutName, name)) { com.droiddeck.launcher.input.ControlsChoice.newForGame(this, game, name, desktop) } else null
releasePads()
drawerOpen = false
layoutEditor = Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
layoutEditor = target
inputSettingsOpen = true
}
@@ -4429,7 +4426,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this))
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
refreshLayoutOptions(library)
refreshLayoutOptions()
secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this))
deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings) }
inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native }
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** The on-screen layout each game draws, shared by the in-game Controller page and Settings › Controller. A null game is the default. */
object ControlsChoice {
const val NEW = "new"
const val DEFAULT = "default"
data class Game(val id: Long, val name: String, val layout: String)
private fun own(library: InputLibrary, id: String?): String? = id?.takeIf { bindings ->
library.bindings.any { it.id == bindings && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true }
}
private fun own(context: Context, library: InputLibrary, game: Long?) = own(library, GameControls.bindings(context, game))
/** The input library with [game]'s main-screen layout selected, without saving it. */
fun library(context: Context, game: Long?, desktop: Boolean): InputLibrary {
val library = InputLibraries.read(context)
val chosen = own(context, library, game)
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List<Pair<String, String>> {
val library = InputLibraries.read(context)
val own = game != null && game in GameControls.games(context)
return (if (own) listOf(DEFAULT to context.getString(R.string.osc_default)) else emptyList()) +
listOf(InputLibraries.OVERLAY to context.getString(R.string.osc_layout_gamepad)) +
(if (steamMode) listOf(GameControls.STEAM to context.getString(R.string.osc_layout_steam)) else emptyList()) +
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }.map { it.id to it.name } +
(if (game != null && !gameName.isNullOrBlank()) listOf(NEW to context.getString(R.string.osc_layout_new_for, gameName)) else emptyList())
}
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
if (steamMode && GameControls.steamLayout(context, game)) GameControls.STEAM
else library(context, game, desktop).activeLayout(desktop, InputRole.PRIMARY)?.id ?: InputLibraries.OVERLAY
fun choose(context: Context, game: Long?, id: String, desktop: Boolean, gameName: String? = null) {
require(id != NEW)
if (id == DEFAULT) { if (game != null) useDefault(context, game); return }
val steam = id == GameControls.STEAM
val bindings = if (steam) null else {
val library = InputLibraries.read(context)
val layout = library.layouts.first { it.id == id }
library.bindings.firstOrNull { !it.physical && it.compatible(layout) }?.id ?: newInputId().also { newId ->
InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) }
}
}
if (game != null) GameControls.choose(context, game, bindings, steam, gameName)
else {
SessionPrefs.setSteamTouchLayout(context, steam)
if (bindings != null) InputLibraries.update(context) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
}
}
/** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */
fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair<String, String> {
val layoutId = newInputId()
val bindingsId = newInputId()
InputLibraries.update(context) { latest ->
val chosen = own(context, latest, game)
val part = (if (chosen == null) latest else latest.selectPart(desktop, InputRole.PRIMARY, chosen)).activePart(desktop, InputRole.PRIMARY)
val source = latest.layouts.firstOrNull { it.id == part.layout && it.editable } ?: latest.layouts.first { it.id == InputLibraries.OVERLAY }
val actions = latest.bindings.firstOrNull { it.id == part.bindings && it.compatible(source) }
?: latest.bindings.firstOrNull { !it.physical && it.compatible(source) }
?: SavedInputBindings(bindingsId, source.name, false, source.id)
val title = name.trim().take(80).ifEmpty { source.name }
latest.withLayout(source.derived(layoutId, title)).withPreset(actions.copy(id = bindingsId, name = title, layoutId = layoutId))
}
GameControls.choose(context, game, bindingsId, steam = false, name = name)
return layoutId to bindingsId
}
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
val library = library(context, game, desktop)
val layout = library.activeLayout(desktop, InputRole.PRIMARY)?.takeIf { it.editable } ?: return null
return Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
}
/** Whether [game] has a layout of its own, rather than the default. */
fun hasOwn(context: Context, game: Long?): Boolean = own(context, InputLibraries.read(context), game) != null
/** Whether saving an edit of [game]'s layout would also change the default or another game. */
fun shared(context: Context, game: Long?): Boolean {
game ?: return false
val library = InputLibraries.read(context)
val bindings = own(context, library, game) ?: return true
val layout = library.preset(bindings).layoutId
fun drawsLayout(id: String) = library.bindings.firstOrNull { it.id == id }?.layoutId == layout
return library.usersOfLayout(layout ?: return true).isNotEmpty() ||
library.selections.values.any { s -> s.parts[InputRole.PRIMARY]?.let(::drawsLayout) == true } ||
GameControls.games(context).any { it != game && own(context, library, it)?.let(::drawsLayout) == true }
}
fun useDefault(context: Context, game: Long) = GameControls.clear(context, game)
/** Games with a layout of their own, by name. */
fun games(context: Context): List<Game> {
val library = InputLibraries.read(context)
return GameControls.games(context).mapNotNull { id ->
val layout = when {
GameControls.steamLayout(context, id) -> context.getString(R.string.osc_layout_steam)
else -> own(context, library, id)?.let { b -> library.layouts.firstOrNull { it.id == library.preset(b).layoutId }?.name } ?: return@mapNotNull null
}
val name = GameControls.name(context, id)
?: id.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.let { runCatching { SteamTouchConfig.gameName(context, it.toInt()) }.getOrNull() }
?: id.toString()
Game(id, name, layout)
}.sortedBy { it.name.lowercase() }
}
}
@@ -17,8 +17,20 @@ object GameControls {
return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context)
}
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean) {
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean, name: String? = null) {
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
.apply { if (!name.isNullOrBlank()) putString("$game.name", name) }
.putBoolean("$game.steam", steam).apply()
}
/** Games with their own choice, in the order of their ids. */
fun games(context: Context): List<Long> = prefs(context).all.keys
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
fun clear(context: Context, game: Long) {
prefs(context).edit().remove("$game.bindings").remove("$game.steam").apply()
}
}
@@ -27,7 +27,7 @@ object GamepadGeometry {
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = true, upright: Boolean = false,
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = false, upright: Boolean = false,
trackpads: Boolean = false): Map<Slot, Box> {
if (w <= 0f || h <= 0f) return emptyMap()
if (upright || portraitDock && h >= w * 0.6f && w >= 300 * density && h >= 300 * density) {
@@ -72,6 +72,7 @@ object GamepadGeometry {
else -> 1
}
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
if (grips) gripsBetween(boxes, w, gap - 2 * gutter, boxes.values.maxOf { if (it.cx in (w - gap) / 2f..(w + gap) / 2f) it.bottom else 0f } + gutter, h - pad, density)
} else {
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
val main = side * 0.62f
@@ -87,13 +88,30 @@ object GamepadGeometry {
val gap = w - 2 * (side * 0.40f + main / 2f)
val columns = if (gap >= 2 * gridButton) 2 else 1
val rows = (middle.size + columns - 1) / columns
middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
val gridTop = h - pad - rows * buttonH - (rows - 1) * 10 * density
middleGrid(columns, gap - 2 * gutter, gridTop)
if (grips) gripsBetween(boxes, w, gap - 2 * gutter, shoulderY + buttonH / 2f + gutter, gridTop - gutter, density)
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
}
return boxes
}
/** The back grips in the gap between a landscape panel's two clusters: one row of four, or two rows of two. */
private fun gripsBetween(boxes: MutableMap<Slot, Box>, w: Float, span: Float, top: Float, bottom: Float, density: Float) {
val gap = 8 * density
val minimum = 44 * density
val rows = if ((span - 3 * gap) / 4f >= minimum) 1 else if ((span - gap) / 2f >= minimum) 2 else return
val perRow = 4 / rows
val cellW = ((span - (perRow - 1) * gap) / perRow).coerceAtMost(96 * density)
val cellH = ((bottom - top - (rows - 1) * gap) / rows).coerceAtMost(64 * density)
if (cellH < minimum) return
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
val col = i % perRow; val row = i / perRow
boxes[slot] = Box(w / 2f + (col - (perRow - 1) / 2f) * (cellW + gap), bottom - (rows - 1 - row) * (cellH + gap) - cellH / 2f, cellW, cellH)
}
}
/**
* The panel under a portrait game: shoulders with View and Menu across the top, the back grips under them when the kit has
* them, then the d-pad and face buttons and, along the bottom edge, the sticks or trackpads, each as large as the panel allows.
@@ -93,12 +93,12 @@ object KitLayout {
fun x(ref: Float) = when {
ref < REF_W / 3f -> safe.left + ref * unit
ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit
else -> w / 2f + (ref - REF_W / 2f) * unit
else -> (w / 2f + (ref - REF_W / 2f) * unit).between(safe.left + ref * unit, w - safe.right - (REF_W - ref) * unit)
}
fun y(ref: Float) = when {
ref < REF_H / 3f -> safe.top + ref * unit
ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit
else -> h / 2f + (ref - REF_H / 2f) * unit
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
}
val density = context.resources.displayMetrics.density
var edge = safe.left + CORNER_DP * density
@@ -204,4 +204,7 @@ object KitLayout {
val mm = shortSide / dpi * 25.4f
return min(1f, MAX_HEIGHT_MM / max(mm, 1f))
}
/** The middle band never comes closer to an edge than the edge rows' own reference spacing allows. */
private fun Float.between(low: Float, high: Float) = coerceIn(low, max(low, high))
}
@@ -3,44 +3,8 @@ package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.view.View
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
@Composable
internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.weight(1f).focusRow(onClick = onPick).padding(12.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
InputLayoutThumbnail(layout, role)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(layout.name, style = MaterialTheme.typography.titleMedium)
Text(detail ?: stringResource(R.string.input_layout_count, layout.elements.size),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
PadTextButton(onClick = onManage, modifier = Modifier.testTag("layout-manage-${layout.id}")) { Text("⋮", style = MaterialTheme.typography.titleLarge) }
}
}
@Composable
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
update = { it.update(layout, role) })
}
internal class InputLayoutPreviewView(context: Context) : View(context) {
private val renderer = InputSurfaceView(context)
private var sourceHeight = 563
@@ -1,18 +1,10 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import android.util.DisplayMetrics
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.focus.focusRequester
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
@@ -20,142 +12,85 @@ 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.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** The in-game Remap buttons page. */
@Composable
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit) {
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit, desktop: Boolean = false) {
val context = LocalContext.current
val activity = context.findActivity() as? com.droiddeck.launcher.SessionActivity
val target = activity?.inputEditorDisplay(InputRole.SECONDARY)
if (activity != null && target != null && target.displayId != activity.window.decorView.display?.displayId) {
InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged) }
} else InputSettingsWindow(onBack, onChanged)
}
@Composable
private fun InputSettingsWindow(onBack: () -> Unit, onChanged: () -> Unit) {
Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) {
InputSettingsPane(onBack, onChanged)
InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged, desktop) }
} else Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) {
InputSettingsPane(onBack, onChanged, desktop)
}
}
@Composable
private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
var editingSurface by remember { mutableStateOf(false) }
val window = (androidx.compose.ui.platform.LocalView.current.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window
DisposableEffect(window, editingSurface) {
window?.setDimAmount(if (editingSurface) 0f else .32f)
onDispose { }
}
private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit, desktop: Boolean) {
BoxWithConstraints(Modifier.fillMaxSize().systemBarsPadding().padding(8.dp)) {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
Surface(Modifier.fillMaxSize(), color = if (editingSurface) androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) {
InputSettingsPage(onBack, onChanged, onSurfaceEditing = { editingSurface = it })
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {
InputSettingsPage(onBack, onChanged, remapOnly = true, desktop = desktop)
}
}
}
}
private enum class InputPage { HOME, PROFILE, 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)
private data class InputConfirmation(val title: String, val detail: String, val action: () -> Unit)
private data class InputReuseRequest(val name: String, val layoutOnly: Boolean, val apply: (Boolean) -> Unit)
private enum class InputPage { HOME, REMAP }
private data class InputBindingEdit(val preset: String, val control: InputControl, val key: PhysicalInputKey? = null)
/** Settings › Controller: the in-game Controller page for the default, or with [remapOnly] just the physical controller's buttons. */
@Composable
fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {}) {
fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {},
remapOnly: Boolean = false, desktop: Boolean = false) {
CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onBackground) {
InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing)
InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing, remapOnly, desktop)
}
}
@Composable
private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit) {
private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit,
remapOnly: Boolean, desktop: Boolean) {
val context = LocalContext.current
val host = rememberMenuHost()
var library by remember { mutableStateOf(InputLibraries.read(context)) }
var page by remember { mutableStateOf(InputPage.HOME) }
var page by remember { mutableStateOf(if (remapOnly) InputPage.REMAP else InputPage.HOME) }
var bindingsTab by remember { mutableIntStateOf(0) }
var profileId by remember { mutableStateOf(InputProfile.GAME) }
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
var edit by remember { mutableStateOf<InputBindingEdit?>(null) }
var naming by remember { mutableStateOf<InputNameRequest?>(null) }
var confirmation by remember { mutableStateOf<InputConfirmation?>(null) }
var reuse by remember { mutableStateOf<InputReuseRequest?>(null) }
var capture by remember { mutableStateOf(false) }
var surface by remember { mutableStateOf(false) }
LaunchedEffect(surface) { onSurfaceEditing(surface) }
var surface by remember { mutableStateOf<Triple<String, String, String>?>(null) }
var revision by remember { mutableIntStateOf(0) }
LaunchedEffect(surface) { onSurfaceEditing(surface != null) }
DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } }
var managingLayout by remember { mutableStateOf<SavedInputLayout?>(null) }
var exporting by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) }
val scope = rememberCoroutineScope()
val controller = rememberControllerSettings()
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
fun changed() { library = InputLibraries.read(context); revision++; onChanged() }
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
fun go(next: InputPage) { page = next; host.open = null }
fun back() {
when {
edit != null -> edit = null
page == InputPage.HOME -> onBack()
page == InputPage.PROFILE -> go(InputPage.HOME)
page == InputPage.SOURCE -> go(InputPage.PROFILE)
else -> go(InputPage.SOURCE)
page == InputPage.REMAP && !remapOnly -> go(InputPage.HOME)
else -> onBack()
}
}
BackHandler(enabled = !embedded || page != InputPage.HOME || edit != null, onBack = ::back)
val profile = library.profile(profileId)
val preset = library.preset(profile.binding(role))
val layout = library.layout(profileId, role)
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
val target = role
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) }
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)
}
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri ->
val text = exporting
exporting = null
if (uri != null && text != null) scope.launch {
val saved = withContext(Dispatchers.IO) { runCatching { context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray()) } != null }.getOrDefault(false) }
if (!saved) error = context.getString(R.string.input_save_failed)
}
}
fun rename(title: Int, name: String, save: (String) -> Unit) {
naming = InputNameRequest(title, name) { value, _, _ -> save(value) }
}
fun newProfile(copy: Boolean) {
naming = InputNameRequest(if (copy) R.string.input_copy_profile else R.string.input_new_profile,
if (copy) profile.name else "", library.profiles.map { it.id to it.name }, profileId, offerSharing = true) { name, source, shared ->
val id = newInputId()
if (update { it.duplicateProfile(source, name, id, sharePhysical = shared) }) { profileId = id; go(InputPage.PROFILE) }
}
}
fun editPart(nextRole: InputRole) { role = nextRole; bindingsTab = 0; go(InputPage.SOURCE) }
val profile = library.profile(library.activeId(desktop))
val preset = library.preset(library.activePart(desktop, InputRole.PHYSICAL).bindings)
val pageFocus = remember { androidx.compose.ui.focus.FocusRequester() }
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
var settled by remember { mutableStateOf(false) }
LaunchedEffect(page, role, profileId, edit != null, surface) {
LaunchedEffect(page, edit != null, surface) {
if (!settled) { settled = true; return@LaunchedEffect }
if (surface || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
if (surface != null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
repeat(2) { withFrameNanos { } }
runCatching { pageFocus.requestFocus() }
}
@@ -163,73 +98,45 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
Box(Modifier.focusRequester(pageFocus).focusGroup()) {
if (editing != null) {
val b = library.preset(editing.preset)
var elementProperties by remember(editing) { mutableStateOf(editing.element) }
val current = editing.element?.let { if (editing.click) b.clickAction(it) else b.action(it) }
?: editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled }
val current = editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled }
?: b.controls[editing.control] ?: InputAction.Native()
InputActionEditor(editing.control, current, if (editing.click) stringResource(R.string.input_click_name, editing.element!!.name)
else editing.element?.name ?: editing.key?.label ?: editing.control.label,
properties = { action ->
if (!editing.click && layout?.elements?.any { it.id == editing.element?.id } == true)
elementProperties?.let { e -> InputElementProperties(e, action) { elementProperties = it } }
},
onBack = { edit = null }, element = editing.element, nativeTargets = editing.key == null, click = editing.click,
detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size)
else "${profile.name} · ${roleLabel(role)}", onSave = { action ->
if (update { l ->
val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map {
if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it
})) else l
geometry.withPreset(when {
editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action))
editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action))
InputActionEditor(editing.control, current, editing.key?.label ?: editing.control.label,
onBack = { edit = null }, nativeTargets = editing.key == null, detail = stringResource(R.string.input_remap_buttons), onSave = { action ->
if (update { l -> l.withPreset(when {
editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
else -> b.copy(controls = b.controls + (editing.control to action))
}) }) edit = null
})
} else if (!surface) key(page, profileId, role) {
} else if (surface == null) key(page) {
SettingsPage(host, title = when (page) {
InputPage.HOME -> if (embedded) null else stringResource(R.string.setup_controller)
InputPage.PROFILE -> profile.name
InputPage.SOURCE -> roleLabel(role)
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
}, eyebrow = when (page) {
InputPage.SOURCE -> profile.name
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
else -> null
},
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
InputPage.REMAP -> stringResource(R.string.input_remap_buttons)
}, 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) }
PadTextButton(onClick = { newProfile(false) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_profile)) }
}
SettingsGroup(stringResource(R.string.input_device_settings)) {
DefaultControlsGroup(host, revision, onEdit = { surface = it }, onChanged = ::changed)
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
var padType by remember { mutableStateOf(SessionPrefs.steamController(context)) }
ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), null,
listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam),
SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4),
SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)),
padType) { SessionPrefs.setSteamController(context, it); padType = it; onChanged() }
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() }
ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), stringResource(R.string.ctrl_joycon_vr_hint), controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() }
ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), null, controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() }
ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit), { go(InputPage.REMAP) },
modifier = Modifier.testTag("input-remap"))
}
val games = remember(revision) { ControlsChoice.games(context) }
if (games.isNotEmpty()) SettingsGroup(stringResource(R.string.osc_games_own)) {
for (game in games) ActionRow(game.name, game.layout, stringResource(R.string.osc_use_default), {
ControlsChoice.useDefault(context, game.id); changed()
}, modifier = Modifier.testTag("osc-use-default-${game.id}"))
}
SettingsGroup(stringResource(R.string.shortcuts_title)) { PhysicalShortcutRows() }
SettingsGroup(stringResource(R.string.input_latency)) {
@@ -247,188 +154,70 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
} }, confirmButton = { PadTextButton(onClick = { reading = false }) { Text(stringResource(R.string.common_close)) } })
}
}
InputPage.PROFILE -> {
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) }
}
Spacer(Modifier.height(16.dp))
Actions {
SecondaryButton(stringResource(R.string.input_rename)) { rename(R.string.input_rename, profile.name) { name -> update { it.withProfile(profile.copy(name = name)) } } }
SecondaryButton(stringResource(R.string.input_copy_profile)) { newProfile(true) }
SecondaryButton(stringResource(R.string.input_reset_actions)) {
confirmation = InputConfirmation(context.getString(R.string.input_reset_actions), context.getString(R.string.input_reset_profile_detail, profile.name)) { update { it.resetProfile(profileId) } }
InputPage.REMAP -> {
SettingsGroup(stringResource(R.string.input_physical)) {
Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) {
SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes), stringResource(R.string.input_extra_keys)), bindingsTab) { bindingsTab = it }
}
if (profileId !in listOf(InputProfile.GAME, InputProfile.DESKTOP)) SecondaryButton(stringResource(R.string.input_delete)) {
confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_profile_detail, profile.name)) {
if (update { it.removeProfile(profileId) }) { profileId = InputProfile.GAME; go(InputPage.HOME) }
if (bindingsTab != 2) InputControlGrid(preset, InputControl.padControls.asList(), bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) }
else {
for (b in preset.keys) {
InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) }
PadTextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) }
}
InputNavigationRow(stringResource(R.string.input_capture), null) { capture = true }
}
val defaults = InputProfile.defaults(profile.base).bindings[InputRole.PHYSICAL].orEmpty()
if (preset.controls != defaults || preset.keys.isNotEmpty()) ActionRow(stringResource(R.string.input_reset_actions), null,
stringResource(R.string.hud_reset_button), { update { it.withPreset(preset.copy(controls = defaults, keys = emptyList())) } },
modifier = Modifier.testTag("input-remap-reset"))
}
}
InputPage.SOURCE -> {
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_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) {
if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true }
else InputHint(layout.name)
InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) }
if (layout.editable) {
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))) } }
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
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 }))
val elements = layout?.takeIf { it.editable }?.let { l ->
if (OnScreenLayout.generated(l)) InputLibraries.defaultPositions(context, library, l)?.first.orEmpty() + l.elements else l.elements
}
if (elements != null) {
if (elements.isEmpty()) InputHint(stringResource(R.string.input_empty_elements))
for (e in elements) {
InputNavigationRow(e.name, actionLabel(preset.action(e)), Modifier.testTag("input-element-${e.id}")) { edit = InputBindingEdit(preset.id, e.control, e) }
if (e.hasClick) InputNavigationRow(stringResource(R.string.input_click_name, e.name), actionLabel(preset.clickAction(e)), Modifier.testTag("input-click-${e.id}")) { edit = InputBindingEdit(preset.id, InputControl.A, e, click = true) }
}
} else {
Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) {
SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes)) +
if (preset.physical) listOf(stringResource(R.string.input_extra_keys)) else emptyList(), bindingsTab) { bindingsTab = it }
}
val controls = InputControl.padControls.asList()
if (bindingsTab != 2) InputControlGrid(preset, controls, bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) }
else {
for (b in preset.keys) {
InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) }
PadTextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) }
}
InputNavigationRow(stringResource(R.string.input_capture), stringResource(R.string.input_capture_hint)) { capture = true }
}
}
}
SettingsGroup(stringResource(R.string.input_reuse)) {
InputNavigationRow(stringResource(R.string.input_use_settings_from), stringResource(R.string.input_reuse_hint)) { go(InputPage.REUSE) }
if (library.usersOfBindings(preset.id).size > 1 || layout?.let { it.editable && library.usersOfLayout(it.id).size > 1 } == true)
InputNavigationRow(stringResource(R.string.input_make_independent), stringResource(R.string.input_independent_hint), Modifier.testTag("input-make-independent")) {
update { it.usePart(profileId, role, profileId, shared = false) }
}
}
}
InputPage.LAYOUTS -> {
InputHint(stringResource(R.string.input_layout_geometry_hint))
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 &&
library.usersOfLayout(saved.id).isEmpty() && library.bindings.none { it.layoutId == saved.id && library.selectedBindings(it.id) } }
for (saved in available.filter { showOther || it !in other }) {
InputLayoutRow(saved, role, if (saved.id == layout?.id) stringResource(R.string.input_current_layout) else null,
onManage = { managingLayout = saved }) {
reuse = InputReuseRequest(saved.name, layoutOnly = true) { shared -> if (update { it.useLayout(profileId, role, saved.id, shared) }) go(InputPage.SOURCE) }
}
}
if (other.isNotEmpty()) PadTextButton(onClick = { showOther = !showOther }, modifier = Modifier.padding(8.dp)) {
Text(stringResource(if (showOther) R.string.input_hide_other_layouts else R.string.input_other_layouts, other.size))
}
Row {
PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ ->
val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY)
if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true }
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) }
PadTextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "application/octet-stream", "*/*")) },
modifier = Modifier.padding(8.dp).testTag("input-layout-import")) { Text(stringResource(R.string.boot_movie_import)) }
}
}
}
InputPage.REUSE -> {
InputHint(stringResource(R.string.input_reuse_explanation, roleLabel(role)))
SettingsGroup(stringResource(R.string.input_profiles)) {
for (p in library.profiles.filterNot { it.id == profileId }) InputNavigationRow(p.name, library.layout(p.id, role)?.name) {
reuse = InputReuseRequest(p.name, layoutOnly = false) { shared -> if (update { it.usePart(profileId, role, p.id, shared) }) go(InputPage.SOURCE) }
}
}
}
}
}
}
}
managingLayout?.let { saved -> AlertDialog(onDismissRequest = { managingLayout = null }, title = { Text(saved.name) },
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.input_layout_count, saved.elements.size))
SecondaryButton(stringResource(R.string.input_rename)) {
managingLayout = null
rename(R.string.input_rename_layout, saved.name) { name -> update { it.withLayout(saved.copy(name = name)) } }
}
val exported = remember(saved, library) {
val metrics = inputDisplayMetrics(context, if (saved.screen == InputLayoutScreen.SECONDARY) InputRole.SECONDARY else InputRole.PRIMARY)
InputLayoutFile.export(saved, library.bindings.firstOrNull { it.id == preset.id && it.layoutId == saved.id }
?: library.bindings.firstOrNull { it.layoutId == saved.id }, metrics.widthPixels, metrics.heightPixels)
}
if (exported != null) SecondaryButton(stringResource(R.string.screen_key_layout_export)) {
managingLayout = null
exporting = exported
exporter.launch(InputLayoutFile.fileName(saved))
}
val used = library.usersOfLayout(saved.id).isNotEmpty() || library.bindings.any { it.layoutId == saved.id && library.selectedBindings(it.id) }
if (!used && saved.editable) SecondaryButton(stringResource(R.string.input_delete)) {
managingLayout = null
confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_layout_detail, saved.name)) { update { it.removeLayout(saved.id) } }
}
} }, confirmButton = { PadTextButton(onClick = { managingLayout = null }) { Text(stringResource(R.string.common_close)) } }) }
if (capture) InputCaptureDialog(onDismiss = { capture = false }) { capture = false; edit = InputBindingEdit(preset.id, InputControl.A, key = it) }
if (surface) InputSurfaceDialog(profileId, onDismiss = { surface = false; library = InputLibraries.read(context) }, onChanged = {
library = InputLibraries.read(context); onChanged()
}, role = role, layoutId = layout?.id, bindingsId = preset.id)
naming?.let { request -> key(request) { InputNameDialog(request) { naming = null } } }
reuse?.let { request -> key(request) { InputReuseDialog(request) { reuse = null } } }
confirmation?.let { request -> AlertDialog(onDismissRequest = { confirmation = null }, title = { Text(request.title) },
text = { Text(request.detail) }, confirmButton = { PadTextButton(onClick = { confirmation = null; request.action() }) { Text(stringResource(R.string.common_ok)) } },
dismissButton = { PadTextButton(onClick = { confirmation = null }) { Text(stringResource(R.string.common_cancel)) } }) }
surface?.let { (profileId, layoutId, bindingsId) ->
val name = library.layouts.firstOrNull { it.id == layoutId }?.name.orEmpty()
InputSurfaceDialog(profileId, onDismiss = { surface = null; changed() }, onChanged = ::changed, role = InputRole.PRIMARY,
layoutId = layoutId, bindingsId = bindingsId, scope = stringResource(R.string.osc_scope_default, name))
}
error?.let { message -> AlertDialog(onDismissRequest = { error = null }, title = { Text(stringResource(R.string.input_save_failed)) },
text = { Text(message) }, confirmButton = { PadTextButton(onClick = { error = null }) { Text(stringResource(R.string.common_ok)) } }) }
}
/** The in-game "On-screen controls" group, for games without a layout of their own. */
@Composable
private fun InputNameDialog(request: InputNameRequest, onDismiss: () -> Unit) {
var name by remember { mutableStateOf(request.initial) }
var source by remember { mutableStateOf(request.source) }
var shared by remember { mutableStateOf(false) }
val host = rememberMenuHost()
AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(request.title)) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
OutlinedTextField(name, { name = it.take(80) }, label = { Text(stringResource(R.string.input_name)) }, singleLine = true, modifier = Modifier.testTag("input-name"))
if (request.sources.isNotEmpty()) ChoiceRow(host, "input-copy-source", stringResource(R.string.input_start_from), null, request.sources, source) { source = it }
if (request.offerSharing) {
Row(Modifier.fillMaxWidth().focusRow(role = Role.Checkbox, checked = shared) { shared = !shared }.testTag("input-share-physical"), verticalAlignment = Alignment.CenterVertically) {
Checkbox(shared, null)
Text(stringResource(R.string.input_share_physical))
}
Text(stringResource(R.string.input_new_independent_hint), style = MaterialTheme.typography.bodySmall)
private fun DefaultControlsGroup(host: MenuHost, revision: Int, onEdit: (Triple<String, String, String>) -> Unit, onChanged: () -> Unit) {
val context = LocalContext.current
val options = remember(revision) { ControlsChoice.options(context, null, steamMode = true) }
val choice = remember(revision) { ControlsChoice.current(context, null, steamMode = true) }
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
var touch by remember { mutableStateOf(SessionPrefs.touchMode(context)) }
var below by remember { mutableStateOf(SessionPrefs.unfoldedControls(context)) }
SettingsGroup(stringResource(R.string.osc_group_for, stringResource(R.string.osc_default))) {
ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), null, options, choice) { id ->
runCatching { ControlsChoice.choose(context, null, id, desktop = false) }
onChanged()
}
} }, confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { request.save(name.trim(), source, shared); onDismiss() }) { Text(stringResource(R.string.gesture_save_changes)) } },
dismissButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } })
}
@Composable
private fun InputReuseDialog(request: InputReuseRequest, onDismiss: () -> Unit) {
var shared by remember { mutableStateOf(false) }
AlertDialog(onDismissRequest = onDismiss, title = { Text(request.name) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
Text(stringResource(if (request.layoutOnly) R.string.input_reuse_layout_detail else R.string.input_reuse_part_detail))
for (link in listOf(false, true)) Row(Modifier.fillMaxWidth().focusRow(role = Role.RadioButton, checked = shared == link) { shared = link }, verticalAlignment = Alignment.CenterVertically) {
RadioButton(shared == link, null)
Text(stringResource(if (link) R.string.input_keep_shared else R.string.input_independent_copy))
if (choice != GameControls.STEAM) ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), {
host.open = null
ControlsChoice.editTarget(context, null, desktop = false)?.let(onEdit)
}, modifier = Modifier.testTag("osc-edit"))
SettingsRow(stringResource(R.string.osc_show), null) {
SegmentedTabs(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)), oscMode,
tabModifier = { Modifier.testTag("osc-$it") }) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
} }, confirmButton = { PadTextButton(onClick = { request.apply(shared); onDismiss() }) { Text(stringResource(R.string.common_ok)) } },
dismissButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } })
ChoiceRow(host, "touch", stringResource(R.string.input_touches), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse),
SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures),
SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), touch) { SessionPrefs.setTouchMode(context, it); touch = it; onChanged() }
ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), null, below) {
SessionPrefs.setUnfoldedControls(context, it); below = it; onChanged()
}
}
}
@Composable
@@ -451,10 +240,9 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List<InputCo
}
@Composable
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, onClick: () -> Unit) {
Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
leading?.invoke()
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleMedium)
if (detail != null) Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -463,37 +251,6 @@ private fun InputNavigationRow(title: String, detail: String?, modifier: Modifie
}
}
@Suppress("DEPRECATION")
internal fun inputDisplayMetrics(context: Context, role: InputRole): DisplayMetrics = DisplayMetrics().also { metrics ->
(context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputEditorDisplay(role)?.getRealMetrics(metrics)
?: metrics.setTo(context.resources.displayMetrics)
}
private fun readLayoutFile(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.openInputStream(uri)?.use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
if (out.size() > 1_000_000) return@use null
}
out.toString(Charsets.UTF_8.name())
}
}.getOrNull()
private fun layoutFileName(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0)?.substringBeforeLast('.')?.trim()?.takeIf { it.isNotEmpty() } else null
}
}.getOrNull()
@Composable
internal fun roleLabel(role: InputRole) = stringResource(when (role) {
InputRole.PHYSICAL -> R.string.input_physical; InputRole.PRIMARY -> R.string.input_primary; InputRole.SECONDARY -> R.string.input_secondary
})
@Composable
private fun InputHint(text: String) {
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -128,16 +128,20 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
/** Offered when the layout being edited is shared: [create] makes the copy that Done then saves into, and [scope] describes it. */
class InputEditorSplit(val label: String, val scope: String, val create: () -> Pair<String, String>)
@Composable
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, scope: String? = null) {
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, scope: String? = null,
split: InputEditorSplit? = null) {
val context = LocalContext.current
val host = LocalInputActivity.current ?: context.findActivity() as? ComponentActivity
val library = remember { InputLibraries.read(context) }
val savedLayout = remember { library.layouts.first { it.id == (layoutId ?: library.profile(profile).parts.getValue(role).layout) } }
val savedBindings = remember { library.preset(bindingsId ?: library.profile(profile).binding(role)) }
val layoutUsers = library.usersOfLayout(savedLayout.id).size
val bindingUsers = library.usersOfBindings(savedBindings.id).size
var splitting by remember { mutableStateOf(false) }
val draft = remember {
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
val start = if (OnScreenLayout.generated(savedLayout) && defaults != null) savedLayout.copy(elements = defaults.first +
@@ -160,9 +164,10 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
fun leave() { if (draft.dirty) draft.confirmDiscard = true else onDismiss() }
fun save() {
runCatching {
val (layoutTarget, bindingsTarget) = split?.takeIf { splitting }?.create?.invoke() ?: (savedLayout.id to savedBindings.id)
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
val l = latest.layouts.first { it.id == layoutTarget }
val p = latest.preset(bindingsTarget)
val generated = draft.kitAtDefaults && OnScreenLayout.generated(l.copy(elements = emptyList(), kitless = false))
val extras = draft.elements.filterNot { KitLayout.isKit(it.id) }
latest.withLayout(if (generated) l.copy(elements = extras, aspect = if (extras.isEmpty()) 0f else draft.aspect, scale = draft.layoutScale, kitless = false)
@@ -209,7 +214,8 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) {
val element = draft.element
BackHandler { if (draft.properties) draft.properties = false else leave() }
val editorScope = scope ?: if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name
val editorScope = split?.scope?.takeIf { splitting } ?: scope ?: if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name
val splitLabel = split?.label?.takeIf { !splitting }
val propertiesEditor: @Composable (InputSurfaceElement) -> Unit = { element ->
var properties by remember(element.id) { mutableStateOf(element) }
InputActionEditor(if (draft.clickProperties) InputControl.A else element.control,
@@ -218,11 +224,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
onBack = { draft.properties = false }, element = element, click = draft.clickProperties,
properties = { action ->
if (!draft.clickProperties) InputElementProperties(properties, action) { properties = it }
if (layoutUsers > 1) Text(stringResource(R.string.input_editor_shared, layoutUsers),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 12.dp))
}, detail = if (bindingUsers > 1) stringResource(R.string.input_shared_detail, savedBindings.name, bindingUsers)
else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action ->
}, detail = editorScope, onSave = { action ->
draft.checkpoint()
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
@@ -240,15 +242,15 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
PrimaryButton(stringResource(R.string.input_editor_done)) { save() }
}
remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave,
lede = if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name) {
remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave, lede = editorScope) {
splitLabel?.let { SecondaryButton(it, compact = true, modifier = Modifier.padding(horizontal = 8.dp).testTag("input-editor-split")) { splitting = true } }
SurfaceToolbar(draft, ::save, ::leave, onDismiss)
SurfaceSelection(draft)
when (draft.popover) { EditorPopover.ADD -> AddRows(draft); EditorPopover.HIDDEN -> HiddenRows(draft); null -> Unit }
}
else -> Box(Modifier.fillMaxSize()) {
SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY)
EditorChrome(draft, editorScope, failure, ::save, ::leave, onDismiss)
EditorChrome(draft, editorScope, splitLabel, { splitting = true }, failure, ::save, ::leave, onDismiss)
if (draft.properties && element != null) Surface(Modifier.align(Alignment.CenterEnd).fillMaxHeight().fillMaxWidth(.44f),
color = MaterialTheme.colorScheme.surface, shadowElevation = 12.dp) {
propertiesEditor(element)
@@ -286,7 +288,8 @@ private fun EditorBar(modifier: Modifier = Modifier, content: @Composable RowSco
/** The editor's tools over the canvas: one toolbar, a bar on the selected control, and the Add and Hidden lists. */
@Composable
private fun EditorChrome(draft: SurfaceDraft, scope: String, failure: String?, onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) {
private fun EditorChrome(draft: SurfaceDraft, scope: String, splitLabel: String?, onSplit: () -> Unit, failure: String?,
onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) {
val context = LocalContext.current
BoxWithConstraints(Modifier.fillMaxSize()) {
Column(Modifier.align(Alignment.TopCenter).padding(top = 10.dp).widthIn(max = maxWidth - 16.dp),
@@ -319,8 +322,11 @@ private fun EditorChrome(draft: SurfaceDraft, scope: String, failure: String?, o
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
}
Text(scope, Modifier.background(MaterialTheme.colorScheme.background.copy(alpha = .7f), RoundedCornerShape(50)).padding(horizontal = 12.dp, vertical = 4.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Row(Modifier.background(MaterialTheme.colorScheme.background.copy(alpha = .7f), RoundedCornerShape(50)).padding(horizontal = 12.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(scope, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
splitLabel?.let { SecondaryButton(it, compact = true, modifier = Modifier.testTag("input-editor-split"), onClick = onSplit) }
}
failure?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) }
when (draft.popover) {
EditorPopover.ADD -> EditorList { AddRows(draft) }