diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 8fbd97ebb..f52cce011 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -645,6 +645,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var layoutOptions by mutableStateOf>>(emptyList()) private var layoutChoice by mutableStateOf("") private var layoutEditor by mutableStateOf?>(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 } diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt b/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt new file mode 100644 index 000000000..48c712eb8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt @@ -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> { + 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 { + 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? { + 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 { + 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() } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/GameControls.kt b/app/src/main/java/com/droiddeck/launcher/input/GameControls.kt index 4d76af54e..8faead159 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/GameControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/GameControls.kt @@ -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 = 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() + } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt index d29064b78..e733fca3a 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt @@ -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 { 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, 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. diff --git a/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt index 4df24d56a..faf9fec0f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt @@ -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)) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt index 5687670bf..414105ee6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputLayoutWidgets.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index 7addb75f1..c6e43f692 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -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> = 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(null) } - var naming by remember { mutableStateOf(null) } - var confirmation by remember { mutableStateOf(null) } - var reuse by remember { mutableStateOf(null) } var capture by remember { mutableStateOf(false) } - var surface by remember { mutableStateOf(false) } - LaunchedEffect(surface) { onSurfaceEditing(surface) } + var surface by remember { mutableStateOf?>(null) } + var revision by remember { mutableIntStateOf(0) } + LaunchedEffect(surface) { onSurfaceEditing(surface != null) } DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } } - var managingLayout by remember { mutableStateOf(null) } - var exporting by remember { mutableStateOf(null) } var error by remember { mutableStateOf(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) -> 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 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) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index 0c55b68a2..4cad7d8fb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -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) + @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) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8f4b5dacc..1249173b3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -345,6 +345,13 @@ Click %1$s · saved for %2$s %1$s · default for games without their own + Saved for %1$s + %1$s · shared with other games + Just this game + + New for %1$s + Default + Games with their own layout + Use default Controller in use. Touch the screen to show the controls. Steam touch layout Image diff --git a/app/src/test/java/com/droiddeck/launcher/input/ControlsChoiceTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ControlsChoiceTest.kt new file mode 100644 index 000000000..d38ce2892 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/ControlsChoiceTest.kt @@ -0,0 +1,125 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import androidx.compose.runtime.MutableState +import com.droiddeck.launcher.R +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], shadows = [JoyConPadTest.RecordingWriter::class]) +class ControlsChoiceTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + for (name in listOf("session", "game-controls", "input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() + } + + @After fun mode() { SessionState.mode = SessionService.MODE_STEAM } + + private fun bigSticks(): String { + val id = "big-sticks" + InputLibraries.update(context) { library -> + val stick = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, "jump", InputElementKind.BUTTON, "Jump") + library.withLayout(SavedInputLayout(id, "Big sticks", listOf(stick), screen = InputLayoutScreen.MAIN)) + .withPreset(SavedInputBindings("big-sticks.actions", "Big sticks", false, id, elements = mapOf("jump" to InputAction.Keys(listOf(57))))) + } + return id + } + + @Test fun aNewLayoutForOneGameCopiesTheLayoutAndItsActionsForThatGameOnly() { + val source = bigSticks() + ControlsChoice.choose(context, null, source, desktop = false) + val (layoutId, bindingsId) = ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) + val library = InputLibraries.read(context) + val copy = library.layouts.first { it.id == layoutId } + assertEquals("Castle Crashers", copy.name) + assertEquals(library.layouts.first { it.id == source }.elements, copy.elements) + assertEquals(InputAction.Keys(listOf(57)), library.preset(bindingsId).elements["jump"]) + assertEquals(layoutId, library.preset(bindingsId).layoutId) + assertEquals(bindingsId, GameControls.bindings(context, 7)) + assertEquals(layoutId, ControlsChoice.current(context, 7, steamMode = true)) + assertEquals(source, ControlsChoice.current(context, 8, steamMode = true)) + assertEquals(source, ControlsChoice.current(context, null, steamMode = true)) + assertEquals(Triple(InputProfile.GAME, layoutId, bindingsId), ControlsChoice.editTarget(context, 7, desktop = false)) + } + + @Test fun aCopyOfTheBuiltInGamepadKeepsFollowingTheKit() { + val extra = InputSurfaceElement(InputControl.A, .45f, .1f, .08f, .1f, "extra", InputElementKind.BUTTON, "Extra") + InputLibraries.update(context) { it.withLayout(it.layouts.first { l -> l.id == InputLibraries.OVERLAY }.copy(elements = listOf(extra), aspect = 2f)) } + val (layoutId, _) = ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) + val copy = InputLibraries.read(context).layouts.first { it.id == layoutId } + assertEquals(InputLibraries.OVERLAY, copy.origin) + assertTrue(OnScreenLayout.generated(copy)) + assertEquals(listOf(extra), copy.elements) + assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, null, steamMode = false)) + } + + @Test fun onlyAGameWithItsOwnUnsharedLayoutEditsWithoutChangingOthers() { + assertFalse(ControlsChoice.shared(context, null)) + assertTrue(ControlsChoice.shared(context, 7)) + ControlsChoice.choose(context, 7, InputLibraries.OVERLAY, desktop = false) + assertTrue(ControlsChoice.shared(context, 7)) + ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) + assertFalse(ControlsChoice.shared(context, 7)) + ControlsChoice.choose(context, 8, ControlsChoice.current(context, 7, steamMode = false), desktop = false) + assertTrue(ControlsChoice.shared(context, 7)) + } + + @Test fun useDefaultForgetsTheGamesChoice() { + ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) + ControlsChoice.choose(context, 9, GameControls.STEAM, desktop = false, gameName = "Portal") + assertEquals(listOf("Castle Crashers" to "Castle Crashers", "Portal" to context.getString(R.string.osc_layout_steam)), + ControlsChoice.games(context).map { it.name to it.layout }) + ControlsChoice.useDefault(context, 7) + assertNull(GameControls.bindings(context, 7)) + assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(context, 7, steamMode = true)) + assertEquals(listOf(9L), ControlsChoice.games(context).map { it.id }) + } + + @Test fun newIsOfferedOnlyForAGame() { + assertTrue(ControlsChoice.options(context, null, steamMode = true).none { it.first == ControlsChoice.NEW }) + assertEquals(ControlsChoice.NEW to context.getString(R.string.osc_layout_new_for, "Castle Crashers"), + ControlsChoice.options(context, 7, steamMode = true, gameName = "Castle Crashers").last()) + assertEquals(listOf(InputLibraries.OVERLAY, GameControls.STEAM), ControlsChoice.options(context, null, steamMode = true).map { it.first }.take(2)) + } + + @Test fun newForTheGameInTheControllerPageCopiesTheLayoutAndOpensTheEditorOnIt() { + SessionState.mode = SessionService.MODE_STEAM + val activity = Robolectric.buildActivity(SessionActivity::class.java).get() + ReflectionHelpers.getField>(activity, "frameGenActiveGameId\$delegate").value = 77L + ReflectionHelpers.getField>(activity, "frameGenActiveGameName\$delegate").value = "Castle Crashers" + ReflectionHelpers.callInstanceMethod(activity, "refreshInputProfile") + val options = ReflectionHelpers.getField>>>(activity, "layoutOptions\$delegate").value + assertEquals(ControlsChoice.NEW to "+ New for Castle Crashers", options.last()) + ReflectionHelpers.callInstanceMethod(activity, "chooseLayout", ReflectionHelpers.ClassParameter.from(String::class.java, ControlsChoice.NEW)) + val editor = ReflectionHelpers.getField?>>(activity, "layoutEditor\$delegate").value!! + assertEquals(GameControls.bindings(activity, 77), editor.third) + assertEquals("Castle Crashers", InputLibraries.read(activity).layouts.first { it.id == editor.second }.name) + assertEquals(editor.second, ReflectionHelpers.getField>(activity, "layoutChoice\$delegate").value) + assertEquals("Saved for Castle Crashers", ReflectionHelpers.getField(activity, "layoutEditorScope")) + assertNull(ReflectionHelpers.getField(activity, "layoutEditorSplit")) + assertNull(GameControls.bindings(activity, 78)) + assertEquals(InputLibraries.OVERLAY, ControlsChoice.current(activity, null, steamMode = true)) + } + + @Test fun aGameWithItsOwnLayoutCanGoBackToTheDefault() { + assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT }) + ControlsChoice.newForGame(context, 42L, "Game", desktop = false) + assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").first().first == ControlsChoice.DEFAULT) + ControlsChoice.choose(context, 42L, ControlsChoice.DEFAULT, desktop = false) + assertFalse(ControlsChoice.hasOwn(context, 42L)) + assertTrue(ControlsChoice.options(context, 42L, steamMode = true, gameName = "Game").none { it.first == ControlsChoice.DEFAULT }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt index ea5d49aac..0616c2f2c 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt @@ -234,8 +234,9 @@ class KitLayoutTest { val density = context.resources.displayMetrics.density for (kit in PadKit.entries) { val placed = KitLayout.dock(context, kit, 1080, 1300, true, InputControl.LS, InputControl.RS) - val boxes = GamepadGeometry.layout(1080f, 1300f, density, true) + val boxes = GamepadGeometry.layout(1080f, 1300f, density, true, grips = kit.steam, trackpads = kit.steam) assertEquals(kit.name, kit.steam && boxes.containsKey(GamepadGeometry.Slot.L4), placed.any { it.control == InputControl.L4 }) + assertEquals(kit.name, kit.steam, placed.any { it.control == InputControl.L4 }) assertNull(placed.firstOrNull { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) assertEquals(1, placed.count { it.id == KitLayout.DPAD_ID }) assertTrue(placed.none { it.floating }) @@ -272,4 +273,13 @@ class KitLayoutTest { assertTrue("$kit stick", e.getValue("legacy:ls").width * 1920 / 2 >= 40 * dp) } } + + @Test fun aTopCutoutNeverPushesTheShoulderRowIntoTheMiddleControls() { + for (kit in PadKit.entries) for (top in listOf(0, 20, 60, 120)) { + val elements = KitLayout.elements(context, kit, 1600, 900, Rect(0, top, 0, 0)) + val lb = elements.single { it.id == "legacy:lb" } + val middle = elements.filter { it.id == KitLayout.DPAD_ID || it.id == "legacy:y" } + for (m in middle) assertTrue("$kit $top ${m.id}", m.y * 900 >= (lb.y + lb.height) * 900 - .5f || m.x * 1600 >= (lb.x + lb.width) * 1600) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index 31bd54aa0..50b60fa05 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -150,7 +150,7 @@ class OnScreenLayoutTest { assertEquals(box.height, ls.height * h, 1f) assertSquare(placed.first { it.id == "legacy:a" }, w, h) assertNull(placed.firstOrNull { it.control == InputControl.GUIDE || it.control == InputControl.QAM }) - assertEquals(portrait, placed.any { it.control == InputControl.L4 }) + assertEquals(steam && GamepadGeometry.Slot.L4 in boxes, placed.any { it.control == InputControl.L4 }) assertInside(placed, w, h) val solid = placed.filter { it.kind != InputElementKind.STICK } for (a in solid) for (b in solid) if (a !== b) { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt index 72e566cd3..14a268330 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/GamepadGeometryTest.kt @@ -33,7 +33,7 @@ class GamepadGeometryTest { private val grips = setOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4) private val portraitPanels get() = panels.take(3) + Panel("312dp phone portrait", 720, 1280, 369 / 160f) private fun portraitBoxes(panel: Panel) = - GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true) + GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, portraitDock = true, grips = true) @Test fun everyControlIsPlacedAndPanelsOnlyWhenUpright() { for (panel in panels) { @@ -173,4 +173,15 @@ class GamepadGeometryTest { for ((slot, box) in b) assertTrue("${panel.name}: $slot", box.bottom <= panel.controlsHeight + .5f && box.right <= panel.width + .5f) } } + + @Test fun landscapePanelsGiveTheGripsSlotsWithoutOverlap() { + for (panel in panels.filter { it.width > it.height }) { + val b = GamepadGeometry.layout(panel.width.toFloat(), panel.controlsHeight.toFloat(), panel.density, grips = true) + assertTrue(panel.name, grips.all { it in b }) + val placed = b.entries.toList() + for (i in placed.indices) for (j in i + 1 until placed.size) + assertFalse("${panel.name}: ${placed[i].key} overlaps ${placed[j].key}", placed[i].value.overlaps(placed[j].value)) + for ((slot, box) in b) assertTrue("${panel.name}: $slot", box.top >= -.5f && box.bottom <= panel.controlsHeight + .5f) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index ecbd28226..3330dd334 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -9,6 +9,7 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.ui.test.* import com.droiddeck.launcher.input.* import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionService import org.junit.Assert.* @@ -35,6 +36,8 @@ class InputSettingsTest { context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit() context.getSharedPreferences("input-surfaces", Context.MODE_PRIVATE).edit().clear().commit() context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit() + context.getSharedPreferences("game-controls", Context.MODE_PRIVATE).edit().clear().commit() + context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() } @Test fun commandSymbolsAreSelectableForAnyCustomButton() { @@ -84,8 +87,7 @@ class InputSettingsTest { @Test fun bindingEditorPersistsDisabledWithoutChangingTouchControls() { var changed = false compose.setContent { DroidDeckTheme { InputSettingsPage({}, { changed = true }) } } - compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() - compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() + compose.onNodeWithTag("input-remap").performScrollTo().performClick() compose.onNodeWithTag("input-binding-a").performScrollTo().performClick() compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() compose.runOnIdle { assertFalse(changed) } @@ -116,43 +118,94 @@ class InputSettingsTest { } } - @Test fun aNewProfileIsIndependentAndDoesNotBecomeActive() { + @Test fun remapButtonsOpensThePhysicalControllerAndBackReturnsToTheControllerPage() { compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick() - compose.onNodeWithTag("input-name").performTextInput("Minecraft") - compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick() + compose.onNodeWithTag("input-remap").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.input_physical).uppercase()).assertExists() + compose.onNodeWithTag("input-binding-a").performScrollTo().performClick() + compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() + compose.onNodeWithTag("input-action-save").performClick() + compose.onNodeWithTag("input-remap-reset").performScrollTo().assertExists() + compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() + compose.onNodeWithTag("osc-edit").assertExists() compose.runOnIdle { - val library = InputLibraries.read(context) - val created = library.profiles.single { it.name == "Minecraft" } - for (role in InputRole.entries) assertNotEquals(library.profile(InputProfile.GAME).binding(role), created.binding(role)) - assertNotEquals(library.layout(InputProfile.GAME, InputRole.SECONDARY)!!.id, library.layout(created.id, InputRole.SECONDARY)!!.id) - assertEquals(InputProfiles.AUTO, library.selected) + assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) + assertEquals(InputAction.Disabled, InputProfiles.read(context, InputProfile.GAME).action(InputRole.PHYSICAL, InputControl.A)) } } - @Test fun openingAProfileDoesNotActivateItAndBackKeepsItsContext() { - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-profile-desktop").performScrollTo().performClick() - compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() - compose.onNodeWithTag("input-binding-a").performScrollTo().performClick() - compose.onNodeWithTag("input-action-save").performClick() + @Test fun inGameRemapOpensStraightOnThePhysicalController() { + var closed = false + compose.setContent { DroidDeckTheme { InputSettingsPage({ closed = true }, remapOnly = true) } } compose.onNodeWithTag("input-binding-a").assertExists() + compose.onNodeWithTag("osc-edit").assertDoesNotExist() compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() - compose.onNodeWithTag("input-part-secondary").assertExists() - compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) } + compose.runOnIdle { assertTrue(closed) } } - @Test fun profileCreationCanExplicitlyShareOnlyPhysicalControls() { + @Test fun settingsShowTheInGameControllerPageForTheDefault() { compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick() - compose.onNodeWithTag("input-name").performTextInput("Shared controls") - compose.onNodeWithTag("input-share-physical").performClick() - compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick() + compose.onNodeWithText(context.getString(R.string.osc_group_for, context.getString(R.string.osc_default)).uppercase()).assertExists() + for (label in listOf(R.string.osc_layout, R.string.osc_edit_layout, R.string.osc_show, R.string.input_touches, R.string.unfolded_controls, + R.string.input_virtual_controller, R.string.ctrl_rumble, R.string.ctrl_dead_zone, R.string.input_remap_buttons)) + compose.onNodeWithText(context.getString(label)).performScrollTo().assertExists() + for (removed in listOf(R.string.input_default_profiles, R.string.input_profiles, R.string.input_new_profile)) + compose.onNodeWithText(context.getString(removed)).assertDoesNotExist() + compose.onNodeWithTag("input-profile-game").assertDoesNotExist() + compose.onNodeWithTag("osc-${SessionPrefs.OSC_NEVER}").performScrollTo().performClick() + compose.runOnIdle { assertEquals(SessionPrefs.OSC_NEVER, SessionPrefs.oscMode(context)) } + } + + @Test fun choosingTheDefaultLayoutAppliesToGamesWithoutTheirOwn() { + InputLibraries.update(context) { it.copyLayout(InputLibraries.OVERLAY, "Big sticks", "big-sticks") } + ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("setting-osc-layout").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.osc_layout_steam)).assertExists() + compose.onNodeWithText("Big sticks").performClick() compose.runOnIdle { - val library = InputLibraries.read(context) - val created = library.profiles.single { it.name == "Shared controls" } - assertEquals(library.profile("game").binding(InputRole.PHYSICAL), created.binding(InputRole.PHYSICAL)) - assertNotEquals(library.profile("game").binding(InputRole.SECONDARY), created.binding(InputRole.SECONDARY)) + assertEquals("big-sticks", ControlsChoice.current(context, null, steamMode = true)) + assertEquals("big-sticks", ControlsChoice.current(context, 8, steamMode = true)) + assertNotEquals("big-sticks", ControlsChoice.current(context, 7, steamMode = true)) + assertEquals("big-sticks", InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!!.id) + } + compose.onNodeWithTag("osc-edit").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.osc_scope_default, "Big sticks")).assertExists() + compose.onNodeWithTag("input-editor-split").assertDoesNotExist() + } + + @Test fun useDefaultReturnsAGameToTheDefaultLayout() { + ControlsChoice.newForGame(context, 42, "Castle Crashers", desktop = false) + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithText(context.getString(R.string.osc_games_own).uppercase()).performScrollTo().assertExists() + compose.onNodeWithTag("osc-use-default-42").performScrollTo().performClick() + compose.runOnIdle { assertNull(GameControls.bindings(context, 42)) } + compose.onNodeWithText(context.getString(R.string.osc_games_own).uppercase()).assertDoesNotExist() + } + + @Test fun justThisGameSavesTheEditIntoTheGamesOwnCopy() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.PRIMARY)!! + var closed = false + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", { closed = true }, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY), + scope = context.getString(R.string.osc_scope_default, layout.name), + split = InputEditorSplit(context.getString(R.string.osc_just_this_game), "Gamepad · saved for Castle Crashers") { + ControlsChoice.newForGame(context, 7, "Castle Crashers", desktop = false) + }) } } + compose.onNodeWithTag("input-editor-split").performClick() + compose.onNodeWithText("Gamepad · saved for Castle Crashers").assertExists() + compose.onNodeWithTag("input-editor-split").assertDoesNotExist() + pressPlus(2) + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() + compose.runOnIdle { + assertTrue(closed) + val saved = InputLibraries.read(context) + assertTrue(OnScreenLayout.generated(saved.layouts.first { it.id == layout.id })) + val own = saved.layouts.first { it.id == ControlsChoice.current(context, 7, steamMode = false) } + assertNotEquals(layout.id, own.id) + assertFalse(OnScreenLayout.generated(own)) + assertEquals(layout.id, ControlsChoice.current(context, 8, steamMode = false)) } } @@ -231,59 +284,6 @@ class InputSettingsTest { compose.runOnIdle { assertEquals(InputAction.Keys(listOf(103)), InputLibraries.read(context).preset(bindingsId).elements["legacy:up"]) } } - @Test fun deckPresetOffersItsRealElementsAndTheCommonEditor() { - InputLibraries.update(context) { it.useLayout("game", InputRole.SECONDARY, InputLibraries.DECK, shared = true) } - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() - compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick() - compose.onNodeWithTag("input-element-legacy:l4").performScrollTo().assertIsDisplayed() - compose.onNodeWithTag("input-binding-a").assertDoesNotExist() - } - - @Test fun mouseTrackpadPresetIsEditableLikeAnyOtherLayout() { - InputLibraries.update(context) { it.useLayout("game", InputRole.SECONDARY, InputLibraries.TRACKPAD, shared = true) } - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() - compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick() - compose.onNodeWithTag("input-element-legacy:right-pad").performScrollTo().assertIsDisplayed() - compose.onNodeWithTag("input-surface-secondary").performScrollTo().assertIsDisplayed() - compose.onNodeWithTag("input-binding-a").assertDoesNotExist() - } - - @Test fun primaryScreenOffersItsActualElementsAndTheCommonEditor() { - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() - compose.onNodeWithTag("input-part-primary").performScrollTo().performClick() - compose.onNodeWithTag("input-element-legacy:a").performScrollTo().assertIsDisplayed() - compose.onNodeWithTag("input-binding-a").assertDoesNotExist() - compose.onNodeWithTag("input-surface-primary").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertIsDisplayed() - compose.onNodeWithTag("input-layout-canvas").assertExists() - } - - @Test fun deviceSettingsAreInlineBelowProfiles() { - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-more").assertDoesNotExist() - compose.onNodeWithText(context.getString(R.string.ctrl_dead_zone)).performScrollTo().assertIsDisplayed() - compose.onNodeWithTag("input-profile-game").performScrollTo().assertIsDisplayed() - } - - @Test fun migratedPadClicksRemainEditableWithoutChangingMovement() { - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-profile-desktop").performScrollTo().performClick() - compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick() - compose.onNodeWithTag("input-click-legacy:right-pad").performScrollTo().performClick() - compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() - compose.onNodeWithTag("input-action-save").performClick() - compose.runOnIdle { - val library = InputLibraries.read(context) - val pad = library.layout("desktop", InputRole.SECONDARY)!!.elements.first { it.control == InputControl.RIGHT_PAD } - val profile = library.compile("desktop") - assertEquals(InputAction.Disabled, profile.elementClickAction(InputRole.SECONDARY, pad)) - assertEquals(InputAction.Pointer(), profile.elementAction(InputRole.SECONDARY, pad.id, pad.control)) - } - } - @Test @Config(sdk = [34]) fun secondarySettingsCanOpenAnActivityDialogAndCloseCleanly() { val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField(Display::class.java, "TYPE_EXTERNAL")) val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId) @@ -294,8 +294,8 @@ class InputSettingsTest { val host = androidx.compose.ui.platform.LocalContext.current.findActivity() as androidx.activity.ComponentActivity if (open.value) InputDisplayContent(host, display, { open.value = false }) { InputSettingsPage({ open.value = false }) } } } - compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick() - compose.onNodeWithTag("input-name").assertExists() + compose.onNodeWithText(context.getString(R.string.input_read_timing)).performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.common_close)).assertExists() compose.runOnIdle { assertTrue(ShadowDialog.getShownDialogs().filterIsInstance().any { it.isShowing && it.display.displayId == displayId }) val dialog = ShadowDialog.getShownDialogs().last { it !is Presentation && it.isShowing } @@ -452,40 +452,6 @@ class InputSettingsTest { com.droiddeck.launcher.input.ControllerPrefs.setSnap(context, true) } - @Test fun layoutsCanBeImportedAndExported() { - val source = java.io.File(context.cacheDir, "jump.icp").apply { - writeText("""{"name":"Jump keys","elements":[{"type":"BUTTON","shape":"CIRCLE","bindings":["KEY_SPACE"],"scale":1.0,"x":0.8,"y":0.7,"text":"Jump"}]}""") - } - val target = java.io.File(context.cacheDir, "out.icp").apply { delete() } - val registry = object : androidx.activity.result.ActivityResultRegistry() { - override fun onLaunch(requestCode: Int, contract: androidx.activity.result.contract.ActivityResultContract, input: I, - options: androidx.core.app.ActivityOptionsCompat?) { - dispatchResult(requestCode, android.net.Uri.fromFile(if (input is String) target else source)) - } - } - val owner = object : androidx.activity.result.ActivityResultRegistryOwner { override val activityResultRegistry = registry } - compose.setContent { androidx.compose.runtime.CompositionLocalProvider(androidx.activity.compose.LocalActivityResultRegistryOwner provides owner) { - DroidDeckTheme { InputSettingsPage({}) } - } } - compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() - compose.onNodeWithTag("input-part-primary").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.input_saved_layouts)).performScrollTo().performClick() - compose.onNodeWithTag("layout-manage-${InputLibraries.OVERLAY}").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.screen_key_layout_export)).assertDoesNotExist() - compose.onNodeWithText(context.getString(R.string.common_close)).performClick() - compose.onNodeWithTag("input-layout-import").performScrollTo().performClick() - compose.waitUntil(5_000) { InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!.name == "Jump keys" } - val imported = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! - assertEquals(InputLayoutScreen.MAIN, imported.screen) - assertEquals(InputAction.Keys(listOf(57)), InputLibraries.read(context).compile("game").elementAction(InputRole.PRIMARY, imported.elements.single().id, InputControl.A)) - compose.onNodeWithText(context.getString(R.string.input_saved_layouts)).performScrollTo().performClick() - compose.onNodeWithTag("layout-manage-${imported.id}").performScrollTo().performClick() - compose.onNodeWithText(context.getString(R.string.screen_key_layout_export)).performClick() - compose.waitUntil(5_000) { target.isFile && target.length() > 0 } - assertEquals(source.readText().let { org.json.JSONObject(it).getString("name") }, org.json.JSONObject(target.readText()).getString("name")) - assertEquals("KEY_SPACE", org.json.JSONObject(target.readText()).getJSONArray("elements").getJSONObject(0).getJSONArray("bindings").getString(0)) - } - private fun pressPlus(times: Int) = repeat(times) { compose.onNodeWithText("+").performScrollTo().performClick() } @Test fun sizeButtonsScaleTheWholeGamepadAndUndoAsOneStep() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt index 9f28c9ccc..51df2679c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -55,12 +55,12 @@ class InputUiLayoutTest { } @Test @Config(qualifiers = "w360dp-h800dp") - fun phoneKeepsLibraryNavigationAndProfileEditingReachable() { + fun phoneKeepsTheControllerPageAndRemappingReachable() { compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { BoxWithConstraints { CompositionLocalProvider(LocalNarrowPane provides (maxWidth < 600.dp)) { InputSettingsPage({}) } } } } } - compose.onNodeWithTag("input-profile-desktop").performScrollTo().assertIsDisplayed().performClick() - compose.onNodeWithTag("input-part-physical").performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("osc-edit").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("input-remap").performScrollTo().assertIsDisplayed().performClick() compose.onNodeWithTag("input-binding-a").performScrollTo().assertIsDisplayed().performClick() compose.onNodeWithTag("input-action-save").assertIsDisplayed() screenshot("phone-properties") @@ -75,10 +75,10 @@ class InputUiLayoutTest { } @Test @Config(qualifiers = "w960dp-h600dp") - fun largeScreenShowsTheProfileLibraryInTheExistingTheme() { + fun largeScreenShowsTheControllerPageInTheExistingTheme() { compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { InputSettingsPage({}) } } } - compose.onNodeWithTag("input-profile-game").assertIsDisplayed() - screenshot("profiles") + compose.onNodeWithTag("osc-edit").assertIsDisplayed() + screenshot("controller") } @Test @Config(qualifiers = "w960dp-h600dp") @@ -108,11 +108,11 @@ class InputUiLayoutTest { } } compose.onNodeWithText(context.getString(R.string.setup_tab_controller)).performClick() - compose.onNodeWithTag("input-profile-game").assertIsDisplayed() - compose.onNodeWithText(context.getString(R.string.ctrl_layout)).assertDoesNotExist() + compose.onNodeWithTag("osc-edit").assertIsDisplayed() + compose.onAllNodesWithText(context.getString(R.string.osc_edit_layout)).assertCountEquals(1) screenshot("controller-tab") - compose.onNodeWithTag("input-profile-game").performClick() - compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() + compose.onNodeWithTag("input-remap").performScrollTo().performClick() + compose.onNodeWithTag("input-binding-a").assertExists() compose.onNodeWithText(context.getString(R.string.setup_tab_launcher)).assertIsDisplayed() screenshot("controller-physical") compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) }