diff --git a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt index 05d9559271..08f75ea91a 100644 --- a/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt +++ b/app/src/debug/java/com/droiddeck/launcher/ui/LauncherPreviews.kt @@ -108,6 +108,22 @@ private fun BottomPanelBar() = PreviewHost { @DroidDeckPreviews @Composable private fun SessionMenuDockedDisplayPreview() = DockedMenu(SessionDrawerPage.DISPLAY) @DroidDeckPreviews @Composable private fun BottomPanelBarPreview() = BottomPanelBar() +/** Controller settings as the launcher opens them: profiles, what they are used for, and touch control size. */ +@Composable +private fun ControllerSettings() = PreviewHost { InputSettingsPage(onBack = {}) } + +/** Buttons and sticks: the controller drawing with A picked, and what it does. */ +@Composable +private fun ControllerButtons() = PreviewHost { + val context = androidx.compose.ui.platform.LocalContext.current + val library = androidx.compose.runtime.remember { com.droiddeck.launcher.input.InputLibraries.read(context) } + InputButtonsPane(library.profile(com.droiddeck.launcher.input.InputProfile.GAME).binding(com.droiddeck.launcher.input.InputRole.PHYSICAL), + library.profile(com.droiddeck.launcher.input.InputProfile.GAME).name, null, {}, {}) +} + +@DroidDeckPreviews @Composable private fun ControllerSettingsPreview() = ControllerSettings() +@DroidDeckPreviews @Composable private fun ControllerButtonsPreview() = ControllerButtons() + /** The Library and Stores tabs read store accounts, which load on a background thread. */ private val storesLoaded = { com.droiddeck.launcher.stores.StoresState.accountsLoaded } @@ -133,4 +149,6 @@ internal val previewCases: List = listOf( PreviewCase("session-menu-docked") { DockedMenu(SessionDrawerPage.CONTROLLER) }, PreviewCase("session-menu-docked-display") { DockedMenu(SessionDrawerPage.DISPLAY) }, PreviewCase("bottom-panel-bar") { BottomPanelBar() }, + PreviewCase("controller-settings") { ControllerSettings() }, + PreviewCase("controller-buttons") { ControllerButtons() }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index d371dd5491..8aa8acd8b8 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -242,6 +242,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var inputRouter: InputRouter? = null private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null private var inputSettingsOpen by mutableStateOf(false) + /** Which editor the input window shows; none means the full controller settings. */ + private var inputEditor by mutableStateOf(null) @Volatile private var inputUsesLocalActions = false private var inputUsesPointer = false private var inputProfile = InputProfile.defaults(InputProfile.GAME) @@ -1166,7 +1168,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (pipUi) return when { ::loading.isInitialized && loading.ended -> finish() - inputSettingsOpen -> inputSettingsOpen = false + inputSettingsOpen -> closeInputEditor() dockedTouchOnly || backTaps.pending -> backTaps.tap() drawerOpen -> drawerOpen = false achievementsOpen -> closeAchievements() @@ -1369,6 +1371,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde gestureGame = nextGame refreshGestureConfig() restoreGamePanel(nextGame) + if (inputGameKey() != SessionState.inputGame) { releasePads(); refreshInputProfile() } } if ( SessionState.mode == SessionService.MODE_STEAM && @@ -1397,18 +1400,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture) - if (inputSettingsOpen) com.droiddeck.launcher.ui.InputSettingsDialog( - onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() }, - onChanged = { - controllerSettings = ControllerPrefs.read(this@SessionActivity) - oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM) - padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity)) - joyConVr?.refresh() - onScreenControls?.reload() - refreshInputProfile() - refreshControls() - }, - ) + val inputChanged = { + controllerSettings = ControllerPrefs.read(this@SessionActivity) + oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM) + padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity)) + joyConVr?.refresh() + onScreenControls?.reload() + refreshInputProfile() + refreshControls() + } + if (inputSettingsOpen) when (val target = inputEditor) { + null -> com.droiddeck.launcher.ui.InputSettingsDialog( + onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() }, + onChanged = inputChanged, + ) + else -> com.droiddeck.launcher.ui.InputEditorWindow(target, onDismiss = { closeInputEditor() }, onChanged = inputChanged) + } LaunchedEffect(Unit) { val root = LinuxRuntime.rootDir(this@SessionActivity) while (true) { @@ -1986,10 +1993,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null) Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show() }, - onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({ - drawerOpen = false - steamTouchControls?.startEditing() - }) else null, onSuspendPolicy = { policy -> SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy) suspendPolicy = policy @@ -2001,8 +2004,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionService.suspendPolicyChanged(this@SessionActivity) }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, - onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputSettingsOpen = true }, + onInputSettings = { leaveImmersiveForDialog(); releasePads(); drawerOpen = false; inputEditor = null; inputSettingsOpen = true }, onInputSelection = { releasePads(); refreshInputProfile() }, + inputGame = inputGameKey()?.let { it to inputGameName() }, + onEditButtons = { openInputEditor(InputRole.PHYSICAL) }, + onEditLayout = when { + oscMode == SessionPrefs.OSC_NEVER -> null + steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM -> + if (onScreenButtonsVisible) ({ drawerOpen = false; steamTouchControls?.startEditing() }) else null + else -> ({ openInputEditor(InputRole.PRIMARY) }) + }, onGestureSettings = { leaveImmersiveForDialog(); drawerOpen = false; gestureSettingsOpen = true }, touchActive = drawerTouchMode(), directHoldBehavior = directHoldBehavior, @@ -4717,6 +4728,51 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (SessionState.mode == SessionService.MODE_RUN) SessionState.gameId?.takeIf { it.isNotBlank() }?.let { "game:$it" } ?: gestureGame else gestureGame + private fun inputGameKey(): String? = bottomGameKey() + + /** Opens the button binder or the on-screen layout editor on what this game uses, giving the game its own copy first when changes are for it. */ + private fun openInputEditor(role: InputRole) { + val desktop = loadingMode() == SessionService.MODE_DESKTOP + val game = inputGameKey()?.takeUnless { SessionPrefs.inputForAllGames(this) } + val name = inputGameName() + val forked = game != null && runCatching { com.droiddeck.launcher.input.InputLibraries.read(this).games[game]?.parts?.containsKey(role) != true }.getOrDefault(false) + val opened = runCatching { + val library = if (game != null) com.droiddeck.launcher.input.InputLibraries.update(this) { it.withGamePart(desktop, game, name, role) } + else com.droiddeck.launcher.input.InputLibraries.read(this) + val part = library.activePart(desktop, role, game) + val layout = part.layout?.let { id -> library.layouts.first { it.id == id } } + if (role != InputRole.PHYSICAL && layout?.editable != true) null + else com.droiddeck.launcher.ui.InputEditorTarget(role, library.activeId(desktop, game), part.bindings, part.layout, + scope = if (game != null) name else library.profile(library.activeId(desktop, game)).name, + game = game?.takeIf { forked }, desktop = desktop) + }.onFailure { Toast.makeText(this, it.message ?: getString(R.string.input_save_failed), Toast.LENGTH_LONG).show() }.getOrNull() + leaveImmersiveForDialog(); releasePads(); drawerOpen = false + inputEditor = opened + inputSettingsOpen = true + if (forked) refreshInputProfile() + } + + private fun closeInputEditor() { + val target = inputEditor + inputSettingsOpen = false + inputEditor = null + val game = target?.game + if (game != null) runCatching { + val library = com.droiddeck.launcher.input.InputLibraries.read(this) + if (library.gameChanges(target.desktop, game, target.role) == 0) + com.droiddeck.launcher.input.InputLibraries.update(this) { it.resetGame(game, target.role) } + } + releasePads() + refreshInputProfile() + secondScreenPresentation?.refreshControls() + } + + private fun inputGameName(): String = when (SessionState.mode) { + SessionService.MODE_RUN -> com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) + SessionService.MODE_STEAM -> frameGenActiveGameName + else -> null + }?.takeIf { it.isNotBlank() }?.take(80) ?: getString(R.string.session_title_game) + private fun settleDualScreenControls() { if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return dualControlsProvisional = false @@ -5066,13 +5122,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun refreshInputProfile() { val library = com.droiddeck.launcher.input.InputLibraries.read(this) val desktop = loadingMode() == SessionService.MODE_DESKTOP - inputProfile = library.compileActive(desktop, secondScreenMode.panel(this)) - stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this)) - primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY) + val game = inputGameKey() + SessionState.inputGame = game + inputProfile = library.compileActive(desktop, secondScreenMode.panel(this), game) + stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this), game) + primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY, game) adaptiveSticks = primaryInputLayout?.adaptiveSticks quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty() - secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this)) - deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings) } + secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this), game) + deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings, game) } inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native } inputUsesPointer = inputProfile.bindings.values.any { bindings -> bindings.values.any { it is InputAction.Pointer || it is InputAction.MouseButton || it is InputAction.Scroll } @@ -6093,8 +6151,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionPrefs.OSC_ALWAYS -> true SessionPrefs.OSC_STEAM_QAM -> true SessionPrefs.OSC_NEVER -> false - SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM || - (!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP) + SessionPrefs.OSC_STEAM_TOUCH -> if (SessionState.mode == SessionService.MODE_STEAM) + SessionPrefs.oscChosen(this) || !PadBridge.anyControllerConnected() && !SteamControllerBle.connected + else !PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected && SessionState.mode != SessionService.MODE_DESKTOP } diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt index 73782d7e63..0b11a64135 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt @@ -113,6 +113,14 @@ object ControllerPrefs { prefs(context).edit().putInt("onScreenOpacity", percent.coerceIn(onScreenOpacityRange)).apply() } + fun opacityFolded(context: Context) = prefs(context).getBoolean("opacityFolded", false) + + /** Multiplies the old per-layout opacity into the global one, once. */ + fun foldOpacity(context: Context, layoutPercent: Int) { + val folded = (onScreenOpacity(context) * layoutPercent / 100f).toInt().coerceIn(onScreenOpacityRange) + prefs(context).edit().putInt("onScreenOpacity", folded).putBoolean("opacityFolded", true).commit() + } + fun setAdaptiveSticks(context: Context, on: Boolean) { prefs(context).edit().putBoolean("adaptiveSticks", on).apply() } @@ -154,6 +162,15 @@ object ControllerPrefs { prefs(context).edit().putBoolean("snap", on).apply() } + /** Layout editor grid cells across the width: 0 (no grid), or one of [editorGrids]. */ + val editorGrids = listOf(0, 50, 25) + + fun editorGrid(context: Context): Int = prefs(context).getInt("editorGrid", 0).takeIf { it in editorGrids } ?: 0 + + fun setEditorGrid(context: Context, cells: Int) { + prefs(context).edit().putInt("editorGrid", cells.takeIf { it in editorGrids } ?: 0).apply() + } + fun layout(context: Context, width: Int, height: Int): Map> { val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap() return raw.split(';').mapNotNull { entry -> diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt index 4683aece97..a2f3c21ae3 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -10,7 +10,8 @@ import org.json.JSONObject import java.util.UUID object InputLibraries { - private const val VERSION = 14 + // 15 and 16 belong to the reverted controller redesign; see redesignVersions. + private const val VERSION = 17 private val redesignVersions = 15..16 private const val KIT_DPAD = "kit:dpad" private const val KEYBOARD = "builtin:keyboard" @@ -45,6 +46,7 @@ object InputLibraries { if (version < 12) library = barStockLayouts(library) if (version < 13) library = LegacyScreenKeyMigration.pin(library) if (version < 14) library = deckGamepadSurfaces(context, library) + if (version < 17) library = singleOpacity(context, library) if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) { val legacy = LegacyScreenKeyMigration.snapshot(context) if (legacy != null) { @@ -293,6 +295,16 @@ object InputLibraries { return addStockLayouts(result) } + /** Each layout used to carry its own opacity on top of the global one; the main-screen layout's share moves into the global value. */ + internal fun singleOpacity(context: Context, library: InputLibrary): InputLibrary { + if (library.layouts.all { it.style.opacity == 100 }) return library + if (!ControllerPrefs.opacityFolded(context)) { + val main = runCatching { library.activeLayout(false, InputRole.PRIMARY) }.getOrNull()?.style?.opacity ?: 100 + ControllerPrefs.foldOpacity(context, main) + } + return library.copy(layouts = library.layouts.map { it.copy(style = it.style.copy(opacity = 100)) }) + } + private fun deckGamepadSurfaces(context: Context, library: InputLibrary): InputLibrary { val leftPad = SessionPrefs.gamepadSurface(context, right = false) == SessionPrefs.SURFACE_TRACKPAD val rightStick = SessionPrefs.gamepadSurface(context, right = true) == SessionPrefs.SURFACE_STICK @@ -371,8 +383,14 @@ object InputLibraries { selection.parts.forEach { (role, id) -> parts.put(role.name, id) } selections.put(mode, JSONObject().put("profile", selection.profile).put("parts", parts).put("profileSelected", selection.profileSelected)) } + val games = JSONObject() + for ((key, game) in library.games) { + val parts = JSONObject() + game.parts.forEach { (role, part) -> parts.put(role.name, JSONObject().put("bindings", part.bindings).put("layout", part.layout)) } + games.put(key, JSONObject().put("name", game.name).put("profile", game.profile ?: JSONObject.NULL).put("parts", parts)) + } return JSONObject().put("selections", selections).put("version", VERSION).put("selected", library.selected).put("steam", library.steam).put("desktop", library.desktop) - .put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString() + .put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).put("games", games).toString() } internal fun decode(raw: String, context: Context? = null): InputLibrary? = runCatching { @@ -422,7 +440,17 @@ object InputLibraries { value.optBoolean("profileSelected", profile != InputProfiles.AUTO || parts.length() == 0)) } }.orEmpty() - val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections) + val games = doc.optJSONObject("games")?.let { saved -> + require(saved.length() <= 512) + saved.keys().asSequence().associateWith { key -> + val game = saved.getJSONObject(key) + val parts = game.getJSONObject("parts") + GameInput(game.getString("name"), game.optionalString("profile"), parts.keys().asSequence().associate { role -> + val part = parts.getJSONObject(role); InputRole.valueOf(role) to InputPart(part.getString("bindings"), part.optionalString("layout")) + }) + } + }.orEmpty() + val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections, games) (if (restore) restoreGamepads(requireNotNull(context), library, generated) else library).validate() }.getOrNull() diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt index 9532f51778..e016021109 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -69,11 +69,15 @@ data class SavedInputProfile(val id: String, val name: String, val base: String, fun binding(role: InputRole) = parts.getValue(role).bindings } +/** One game's own controls: a profile it always uses, and parts copied from that profile and then changed for it alone. */ +data class GameInput(val name: String, val profile: String? = null, val parts: Map = emptyMap()) + data class InputLibrary( val profiles: List, val layouts: List, val bindings: List, val selected: String = InputProfiles.AUTO, val steam: String = InputProfile.GAME, val desktop: String = InputProfile.DESKTOP, val selections: Map = emptyMap(), + val games: Map = emptyMap(), ) { fun profile(id: String) = profiles.first { it.id == id } fun preset(id: String) = bindings.first { it.id == id } @@ -81,31 +85,36 @@ data class InputLibrary( ?.let { id -> layouts.firstOrNull { it.id == id } } private fun mode(isDesktop: Boolean) = if (isDesktop) InputProfile.DESKTOP else InputProfile.GAME fun selection(isDesktop: Boolean) = selections[mode(isDesktop)] ?: InputSelection(selected) - fun activeId(isDesktop: Boolean): String { + fun defaultId(isDesktop: Boolean) = if (isDesktop) desktop else steam + fun activeId(isDesktop: Boolean, game: String? = null): String { + games[game]?.profile?.let { return it } val id = selection(isDesktop).profile - return if (id == InputProfiles.AUTO) { if (isDesktop) desktop else steam } else id + return if (id == InputProfiles.AUTO) defaultId(isDesktop) else id } fun selectProfile(isDesktop: Boolean, id: String) = copy(selections = selections + (mode(isDesktop) to InputSelection(id, profileSelected = true))) fun selectPart(isDesktop: Boolean, role: InputRole, bindingsId: String): InputLibrary { val previous = selection(isDesktop) return copy(selections = selections + (mode(isDesktop) to previous.copy(parts = previous.parts + (role to bindingsId)))) } - fun activePart(isDesktop: Boolean, role: InputRole): InputPart { - val binding = selection(isDesktop).parts[role]?.let(::preset) - return if (binding != null) InputPart(binding.id, binding.layoutId) else profile(activeId(isDesktop)).parts.getValue(role) + fun activePart(isDesktop: Boolean, role: InputRole, game: String? = null): InputPart { + games[game]?.parts?.get(role)?.let { return it } + val binding = selection(isDesktop).parts[role]?.takeIf { games[game]?.profile == null }?.let(::preset) + return if (binding != null) InputPart(binding.id, binding.layoutId) else profile(activeId(isDesktop, game)).parts.getValue(role) } - fun activeLayout(isDesktop: Boolean, role: InputRole) = activePart(isDesktop, role).layout?.let { id -> layouts.first { it.id == id } } - fun panelPart(isDesktop: Boolean, panel: String?): InputPart = - panel?.let { id -> bindings.firstOrNull { it.id == id } }?.let { InputPart(it.id, it.layoutId) } ?: activePart(isDesktop, InputRole.SECONDARY) - fun panelLayout(isDesktop: Boolean, panel: String?) = panelPart(isDesktop, panel).layout?.let { id -> layouts.firstOrNull { it.id == id } } - fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith { - preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings) + fun activeLayout(isDesktop: Boolean, role: InputRole, game: String? = null) = + activePart(isDesktop, role, game).layout?.let { id -> layouts.first { it.id == id } } + fun panelPart(isDesktop: Boolean, panel: String?, game: String? = null): InputPart = + panel?.let { id -> bindings.firstOrNull { it.id == id } }?.let { InputPart(it.id, it.layoutId) } ?: activePart(isDesktop, InputRole.SECONDARY, game) + fun panelLayout(isDesktop: Boolean, panel: String?, game: String? = null) = + panelPart(isDesktop, panel, game).layout?.let { id -> layouts.firstOrNull { it.id == id } } + fun compileActive(isDesktop: Boolean, panel: String? = null, game: String? = null): InputProfile = compileParts(activeId(isDesktop, game), InputRole.entries.associateWith { + preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel, game).bindings else activePart(isDesktop, it, game).bindings) }) - fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile { - val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base) + fun compileStock(isDesktop: Boolean, panel: String? = null, game: String? = null): InputProfile { + val defaults = InputProfile.defaults(profile(activeId(isDesktop, game)).base) val stock = InputStockLayouts.presets(InputStockLayouts.layouts()) return compileParts(defaults.id, InputRole.entries.associateWith { role -> - val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role) + val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel, game) else activePart(isDesktop, role, game) val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) } ?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty()) @@ -134,8 +143,67 @@ data class InputLibrary( } fun usersOfBindings(id: String) = profiles.filter { p -> p.parts.values.any { it.bindings == id } } - fun selectedBindings(id: String) = selections.values.any { id in it.parts.values } + fun selectedBindings(id: String) = selections.values.any { id in it.parts.values } || games.values.any { g -> g.parts.values.any { it.bindings == id } } fun usersOfLayout(id: String) = profiles.filter { p -> p.parts.values.any { it.layout == id } } + private fun gamesUsingLayout(id: String) = games.values.any { g -> g.parts.values.any { it.layout == id } } + + /** Gives [game] its own copy of the part it uses for [role], so edits made for it leave the profile alone. */ + fun withGamePart(isDesktop: Boolean, game: String, name: String, role: InputRole, + bindingsId: String = newInputId(), layoutId: String = newInputId()): InputLibrary { + val current = games[game] ?: GameInput(inputName(name)) + if (role in current.parts) return this + val source = activePart(isDesktop, role, game) + val label = (current.name + " / " + role.name.lowercase()).take(80) + val sourceLayout = source.layout?.let { id -> layouts.first { it.id == id } } + val copiedLayout = sourceLayout?.takeIf { it.editable }?.derived(layoutId, label) + val copied = preset(source.bindings).copy(id = bindingsId, name = label, layoutId = copiedLayout?.id ?: preset(source.bindings).layoutId) + val part = InputPart(copied.id, copiedLayout?.id ?: source.layout) + return (if (copiedLayout == null) this else withLayout(copiedLayout)).withPreset(copied) + .copy(games = games + (game to current.copy(parts = current.parts + (role to part)))) + } + + fun withGameProfile(game: String, name: String, profile: String?): InputLibrary { + require(profile == null || profiles.any { it.id == profile }) + val current = games[game] ?: GameInput(inputName(name)) + val next = current.copy(profile = profile) + return copy(games = if (next.profile == null && next.parts.isEmpty()) games - game else games + (game to next)) + } + + /** Drops [game]'s own controls (one part, or all of them) and the copies nothing else uses. */ + fun resetGame(game: String, role: InputRole? = null): InputLibrary { + val current = games[game] ?: return this + val dropped = if (role == null) current.parts.values.toList() else listOfNotNull(current.parts[role]) + val remaining = if (role == null) null else current.copy(parts = current.parts - role).takeIf { it.profile != null || it.parts.isNotEmpty() } + var result = copy(games = if (remaining == null) games - game else games + (game to remaining)) + for (part in dropped) { + if (result.usersOfBindings(part.bindings).isEmpty() && !result.selectedBindings(part.bindings)) + result = result.copy(bindings = result.bindings.filterNot { it.id == part.bindings }) + val layout = part.layout ?: continue + if (result.usersOfLayout(layout).isEmpty() && !result.gamesUsingLayout(layout) && result.layouts.first { it.id == layout }.editable && + result.bindings.none { it.layoutId == layout }) + result = result.copy(layouts = result.layouts.filterNot { it.id == layout }) + } + return result + } + + /** How many controls [game]'s own parts set differently from the profile it would otherwise use. */ + fun gameChanges(isDesktop: Boolean, game: String, only: InputRole? = null): Int { + val current = games[game] ?: return 0 + return current.parts.entries.filter { only == null || it.key == only }.sumOf { (role, part) -> + val base = copy(games = games - game).activePart(isDesktop, role) + val mine = preset(part.bindings) + val theirs = preset(base.bindings) + val controls = (mine.controls.keys + theirs.controls.keys).count { (mine.controls[it] ?: InputAction.Native()) != (theirs.controls[it] ?: InputAction.Native()) } + val keys = (mine.keys.toSet() - theirs.keys.toSet()).size + (theirs.keys.toSet() - mine.keys.toSet()).size + val layout = part.layout?.let { id -> layouts.firstOrNull { it.id == id } } + val baseLayout = base.layout?.let { id -> layouts.firstOrNull { it.id == id } } + val elements = layout?.elements.orEmpty().count { e -> + val before = baseLayout?.elements?.firstOrNull { it.id == e.id } + before == null || before != e || mine.action(e) != theirs.action(e) || (e.hasClick && mine.clickAction(e) != theirs.clickAction(e)) + } + if (layout == null) 0 else baseLayout?.elements.orEmpty().count { e -> layout.elements.none { it.id == e.id } } + controls + keys + if (layout?.id == baseLayout?.id) 0 else elements + } + } fun withProfile(value: SavedInputProfile) = copy(profiles = profiles.filterNot { it.id == value.id } + value) fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value) fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value, @@ -212,11 +280,12 @@ data class InputLibrary( require(id != InputProfile.GAME && id != InputProfile.DESKTOP) return copy(profiles = profiles.filterNot { it.id == id }, selected = selected.takeUnless { it == id } ?: InputProfiles.AUTO, steam = steam.takeUnless { it == id } ?: InputProfile.GAME, desktop = desktop.takeUnless { it == id } ?: InputProfile.DESKTOP, - selections = selections.mapValues { (_, selection) -> if (selection.profile == id) selection.copy(profile = InputProfiles.AUTO) else selection }) + selections = selections.mapValues { (_, selection) -> if (selection.profile == id) selection.copy(profile = InputProfiles.AUTO) else selection }, + games = games.mapValues { (_, game) -> if (game.profile == id) game.copy(profile = null) else game }.filterValues { it.profile != null || it.parts.isNotEmpty() }) } fun removeLayout(id: String): InputLibrary { - require(usersOfLayout(id).isEmpty() && bindings.none { it.layoutId == id && selectedBindings(it.id) } && layouts.first { it.id == id }.editable) + require(usersOfLayout(id).isEmpty() && !gamesUsingLayout(id) && bindings.none { it.layoutId == id && selectedBindings(it.id) } && layouts.first { it.id == id }.editable) return copy(layouts = layouts.filterNot { it.id == id }, bindings = bindings.filterNot { it.layoutId == id }) } @@ -292,6 +361,20 @@ data class InputLibrary( require(binding.compatible(layout) && (layout == null || layout.supports(role))) } } + require(games.size <= 512) + for ((key, game) in games) { + require(key.isNotBlank() && key.length <= 128) + inputName(game.name) + require(game.profile == null || profiles.any { it.id == game.profile }) + require(game.profile != null || game.parts.isNotEmpty()) + for ((role, part) in game.parts) { + val binding = preset(part.bindings) + require(binding.physical == (role == InputRole.PHYSICAL)) + val layout = part.layout?.let { id -> layouts.first { it.id == id } } + require(if (role == InputRole.PHYSICAL) layout == null else layout?.supports(role) == true) + require(binding.compatible(layout)) + } + } for (p in profiles) { inputName(p.name); require(p.base == InputProfile.GAME || p.base == InputProfile.DESKTOP) require(p.parts.keys == InputRole.entries.toSet()) diff --git a/app/src/main/java/com/droiddeck/launcher/input/WinlatorLayouts.kt b/app/src/main/java/com/droiddeck/launcher/input/WinlatorLayouts.kt new file mode 100644 index 0000000000..4d961a11b7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/WinlatorLayouts.kt @@ -0,0 +1,140 @@ +package com.droiddeck.launcher.input + +import org.json.JSONObject +import java.net.URLEncoder + +/** + * Winlator's input-control profiles (`.icp`): a list of touch elements centred at fractions of the screen, sized in + * hundredths of the screen width times their scale, each sending keyboard keys, mouse buttons or gamepad controls. + */ +object WinlatorLayouts { + private const val BASE = "https://raw.githubusercontent.com/brunodev85/winlator/main/input_controls/" + const val INDEX_URL = BASE + "index.txt" + + fun fileUrl(name: String) = BASE + URLEncoder.encode(name, "UTF-8").replace("+", "%20") + + /** The profile file names a community index lists. */ + fun parseIndex(text: String): List = text.lineSequence().map { it.trim() } + .filter { it.endsWith(".icp", ignoreCase = true) && it.length <= 128 && '/' !in it && '\\' !in it }.distinct().take(500).toList() + + fun isIcp(raw: String) = runCatching { JSONObject(raw).let { it.has("elements") && it.optJSONArray("elements") != null && it.has("cursorSpeed") } }.getOrDefault(false) + + private val keys: Map = mapOf( + "ESC" to 1, "1" to 2, "2" to 3, "3" to 4, "4" to 5, "5" to 6, "6" to 7, "7" to 8, "8" to 9, "9" to 10, "0" to 11, + "MINUS" to 12, "EQUAL" to 13, "BKSP" to 14, "TAB" to 15, "Q" to 16, "W" to 17, "E" to 18, "R" to 19, "T" to 20, "Y" to 21, + "U" to 22, "I" to 23, "O" to 24, "P" to 25, "BRACKET_LEFT" to 26, "BRACKET_RIGHT" to 27, "ENTER" to 28, "CTRL_L" to 29, + "A" to 30, "S" to 31, "D" to 32, "F" to 33, "G" to 34, "H" to 35, "J" to 36, "K" to 37, "L" to 38, "SEMICOLON" to 39, + "APOSTROPHE" to 40, "GRAVE" to 41, "SHIFT_L" to 42, "BACKSLASH" to 43, "Z" to 44, "X" to 45, "C" to 46, "V" to 47, + "B" to 48, "N" to 49, "M" to 50, "COMMA" to 51, "PERIOD" to 52, "SLASH" to 53, "SHIFT_R" to 54, "KP_MULTIPLY" to 55, + "ALT_L" to 56, "SPACE" to 57, "CAPS_LOCK" to 58, "F1" to 59, "F2" to 60, "F3" to 61, "F4" to 62, "F5" to 63, "F6" to 64, + "F7" to 65, "F8" to 66, "F9" to 67, "F10" to 68, "NUM_LOCK" to 69, "SCROLL_LOCK" to 70, "KP_7" to 71, "KP_8" to 72, + "KP_9" to 73, "KP_SUBTRACT" to 74, "KP_4" to 75, "KP_5" to 76, "KP_6" to 77, "KP_ADD" to 78, "KP_1" to 79, "KP_2" to 80, + "KP_3" to 81, "KP_0" to 82, "KP_DEL" to 83, "F11" to 87, "F12" to 88, "KP_ENTER" to 96, "CTRL_R" to 97, "KP_DIVIDE" to 98, + "PRTSCN" to 99, "ALT_R" to 100, "HOME" to 102, "UP" to 103, "PG_UP" to 104, "PRIOR" to 104, "LEFT" to 105, "RIGHT" to 106, + "END" to 107, "DOWN" to 108, "PG_DOWN" to 109, "NEXT" to 109, "INSERT" to 110, "DEL" to 111, + ) + + private val gamepad: Map = mapOf( + "A" to InputControl.A, "B" to InputControl.B, "X" to InputControl.X, "Y" to InputControl.Y, + "L1" to InputControl.LB, "R1" to InputControl.RB, "L2" to InputControl.LT, "R2" to InputControl.RT, + "L3" to InputControl.L3, "R3" to InputControl.R3, "SELECT" to InputControl.SELECT, "START" to InputControl.START, + ) + + private val dpad = mapOf("UP" to InputControl.UP, "RIGHT" to InputControl.RIGHT, "DOWN" to InputControl.DOWN, "LEFT" to InputControl.LEFT) + + private val ranges = mapOf( + "FROM_A_TO_Z" to ('A'..'Z').map { it.toString() }, "FROM_0_TO_9" to (listOf("0") + ('1'..'9').map { it.toString() }), + "FROM_F1_TO_F12" to (1..12).map { "F$it" }, "FROM_NP0_TO_NP9" to (0..9).map { "KP_$it" }, + ) + + private fun key(binding: String) = keys[binding.removePrefix("KEY_")]?.takeIf { binding.startsWith("KEY_") } + + /** What one button binding does here, or null when it has no button equivalent. */ + internal fun buttonAction(binding: String): InputAction? = when { + binding.startsWith("KEY_") -> key(binding)?.let { InputAction.Keys(listOf(it)) } + binding == "MOUSE_LEFT_BUTTON" -> InputAction.MouseButton(272) + binding == "MOUSE_RIGHT_BUTTON" -> InputAction.MouseButton(273) + binding == "MOUSE_MIDDLE_BUTTON" -> InputAction.MouseButton(274) + binding.startsWith("GAMEPAD_BUTTON_") -> gamepad[binding.removePrefix("GAMEPAD_BUTTON_")]?.let { InputAction.Native(it) } + binding.startsWith("GAMEPAD_DPAD_") -> dpad[binding.removePrefix("GAMEPAD_DPAD_")]?.let { InputAction.Native(it) } + else -> null + } + + /** What four direction bindings (up, right, down, left) do on a stick, D-pad or trackpad. */ + private fun directionAction(bindings: List, kind: InputElementKind): InputAction { + val all = bindings.take(4) + return when { + all.any { it.startsWith("GAMEPAD_LEFT_THUMB") } -> if (kind == InputElementKind.DPAD) InputAction.Native() else InputAction.Native(InputControl.LS) + all.any { it.startsWith("GAMEPAD_RIGHT_THUMB") } -> if (kind == InputElementKind.DPAD) InputAction.Native() else InputAction.Native(InputControl.RS) + all.any { it.startsWith("GAMEPAD_DPAD") } -> if (kind == InputElementKind.DPAD) InputAction.Native() else InputAction.Native(InputControl.LS) + all.any { it.startsWith("MOUSE_MOVE") } -> InputAction.Pointer() + all.any { it.startsWith("KEY_") } -> all.map { key(it) ?: 0 }.let { InputAction.Directions(it[0], it[1], it[2], it[3]) } + else -> InputAction.Disabled + } + } + + private fun label(binding: String): String = when { + binding.startsWith("KEY_") -> binding.removePrefix("KEY_").replace('_', ' ') + binding.startsWith("MOUSE_") -> binding.removePrefix("MOUSE_").removeSuffix("_BUTTON").replace('_', ' ') + binding.startsWith("GAMEPAD_BUTTON_") -> binding.removePrefix("GAMEPAD_BUTTON_") + binding.startsWith("GAMEPAD_DPAD_") -> binding.removePrefix("GAMEPAD_") + else -> binding.replace('_', ' ') + }.lowercase().replaceFirstChar { it.uppercase() }.take(80) + + /** Converts an `.icp` file for a [width]×[height] screen into a layout and the actions of its controls. */ + fun import(raw: String, fallbackName: String, screen: InputLayoutScreen, width: Int, height: Int, + id: String = newInputId(), bindingsId: String = newInputId()): Pair? = runCatching { + require(raw.length <= 1_000_000) + val doc = JSONObject(raw) + val source = doc.getJSONArray("elements") + val aspect = (width.coerceAtLeast(1).toFloat() / height.coerceAtLeast(1)).coerceIn(.05f, 20f) + val elements = mutableListOf() + val actions = mutableMapOf() + fun place(kind: InputElementKind, name: String, cx: Float, cy: Float, halfW: Float, halfH: Float, action: InputAction, + shape: InputButtonShape = InputButtonShape.ROUNDED, toggle: Boolean = false) { + if (elements.size >= 64) return + val w = halfW * .01f; val h = halfH * .01f * aspect + val element = InputSurfaceElement(kind.control, cx - w, cy - h, 2 * w, 2 * h, newInputId(), kind, name.ifBlank { "?" }.take(80), + toggle = toggle && (kind == InputElementKind.BUTTON || kind == InputElementKind.TRIGGER), buttonShape = shape).bounded() + elements += element + actions[element.id] = action.takeIf { it.validFor(element) } ?: InputAction.Disabled + } + for (i in 0 until minOf(source.length(), 128)) { + val e = source.optJSONObject(i) ?: continue + val bindings = e.optJSONArray("bindings")?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() + val scale = e.optDouble("scale", 1.0).toFloat().coerceIn(.2f, 5f) + val cx = e.optDouble("x", .5).toFloat(); val cy = e.optDouble("y", .5).toFloat() + val text = e.optString("text").trim() + val shape = when (e.optString("shape")) { "CIRCLE" -> InputButtonShape.CIRCLE; "RECT", "SQUARE" -> InputButtonShape.RECTANGLE; else -> InputButtonShape.ROUNDED } + when (e.optString("type")) { + "BUTTON" -> { + val binding = bindings.firstOrNull { it != "NONE" } ?: continue + val action = buttonAction(binding) ?: InputAction.Disabled + val trigger = action is InputAction.Native && (action.target == InputControl.LT || action.target == InputControl.RT) + val (hw, hh) = when (e.optString("shape")) { "RECT", "ROUND_RECT" -> 4f to 2f; "SQUARE" -> 2.5f to 2.5f; else -> 3f to 3f } + place(if (trigger) InputElementKind.TRIGGER else InputElementKind.BUTTON, text.ifEmpty { label(binding) }, cx, cy, hw * scale, hh * scale, + action, shape, e.optBoolean("toggleSwitch")) + } + "D_PAD" -> place(InputElementKind.DPAD, text.ifEmpty { "D-pad" }, cx, cy, 7 * scale, 7 * scale, directionAction(bindings, InputElementKind.DPAD)) + "STICK" -> place(InputElementKind.STICK, text.ifEmpty { "Stick" }, cx, cy, 6 * scale, 6 * scale, directionAction(bindings, InputElementKind.STICK)) + "TRACKPAD" -> place(InputElementKind.TRACKPAD, text.ifEmpty { "Trackpad" }, cx, cy, 6 * scale, 6 * scale, + directionAction(bindings, InputElementKind.TRACKPAD).takeIf { it !is InputAction.Directions } ?: InputAction.Pointer()) + "RANGE_BUTTON" -> { + val range = ranges[e.optString("range", "FROM_A_TO_Z")] ?: continue + val count = bindings.size.coerceIn(1, range.size) + val vertical = e.optInt("orientation", 0) == 1 + for (n in 0 until count) { + val offset = (n - (count - 1) / 2f) * 4 * scale * .01f + val code = keys[range[n]] ?: continue + place(InputElementKind.BUTTON, label("KEY_" + range[n]), cx + if (vertical) 0f else offset, cy + if (vertical) offset * aspect else 0f, + 2 * scale, 2 * scale, InputAction.Keys(listOf(code)), shape) + } + } + } + } + require(elements.isNotEmpty()) + val name = doc.optString("name").trim().take(80).ifEmpty { fallbackName.trim().take(80) }.ifEmpty { "Winlator" } + val layout = SavedInputLayout(id, name, elements, screen = screen, aspect = aspect) + layout to SavedInputBindings(bindingsId, name, false, id, elements = actions) + }.getOrNull() +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameProfileManager.kt b/app/src/main/java/com/droiddeck/launcher/session/GameProfileManager.kt index 7784f1f9f9..e43173eae1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameProfileManager.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameProfileManager.kt @@ -23,6 +23,10 @@ object GameProfileManager { clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) } clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) } clear("bottom screen") { SessionPrefs.clearGameBottomScreen(context, scope) } + clear("controls") { + if (com.droiddeck.launcher.input.InputLibraries.read(context).games.containsKey(scope)) + com.droiddeck.launcher.input.InputLibraries.update(context) { it.resetGame(scope) } + } clear("guides") { SteamGuides.clear(context, scope) GuideLibrary.clear(context, scope) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index b2cc52bcee..7b59e25d60 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -828,8 +828,9 @@ object SessionPrefs { prefs(context).getString("shape", null) ?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO + /** Until the player picks, Steam sessions use Steam's own touch controls and other sessions DroidDeck's. */ fun oscMode(context: Context, steamSession: Boolean = true): String { - val saved = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO + val saved = prefs(context).getString("osc", null) ?: return if (steamSession) OSC_STEAM_TOUCH else OSC_AUTO return if (!steamSession && saved == OSC_STEAM_QAM) OSC_AUTO else saved } @@ -837,6 +838,15 @@ object SessionPrefs { prefs(context).edit().putString("osc", mode).apply() } + fun oscChosen(context: Context) = prefs(context).contains("osc") + + /** Whether changes made in a game apply to that game alone, or to the profile every game shares. */ + fun inputForAllGames(context: Context) = prefs(context).getBoolean("inputForAllGames", false) + + fun setInputForAllGames(context: Context, all: Boolean) { + prefs(context).edit().putBoolean("inputForAllGames", all).apply() + } + fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false) fun setOscRearButtons(context: Context, shown: Boolean) { prefs(context).edit().putBoolean("oscRearButtons", shown).apply() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index ac62bde46c..40f8b1bfad 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -138,6 +138,8 @@ object SessionState { @Volatile var secondScreenMode = com.droiddeck.launcher.input.SecondScreenMode.NONE @Volatile var bottomMenu = false @Volatile var secondScreenDisplay = -1 + /** The game whose own controls apply now, keyed like its other per-game session settings. */ + @Volatile var inputGame: String? = null @Volatile var secondScreenAutoOpened = false @Volatile var secondScreenProvisional = false @Volatile var secondScreenAutomatic = false diff --git a/app/src/main/java/com/droiddeck/launcher/ui/CommunityLayouts.kt b/app/src/main/java/com/droiddeck/launcher/ui/CommunityLayouts.kt new file mode 100644 index 0000000000..15ae8720bc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/CommunityLayouts.kt @@ -0,0 +1,80 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.layout.* +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.net.HttpURLConnection +import java.net.URL + +private fun fetchText(url: String): String? = runCatching { + (URL(url).openConnection() as HttpURLConnection).run { + connectTimeout = 10_000; readTimeout = 15_000 + try { + if (responseCode != 200) return@run null + inputStream.use { stream -> stream.readBytes().takeIf { it.size <= 1_000_000 }?.toString(Charsets.UTF_8) } + } finally { disconnect() } + } +}.getOrNull() + +/** Shared Winlator layouts: the list, a preview of one as it would sit on this screen, and Use. */ +@Composable +internal fun CommunityLayouts(role: InputRole, onUse: (Pair) -> Unit) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var names by remember { mutableStateOf?>(null) } + var failed by remember { mutableStateOf(false) } + var attempt by remember { mutableIntStateOf(0) } + val previews = remember { mutableStateMapOf?>() } + var loading by remember { mutableStateOf(null) } + LaunchedEffect(attempt) { + failed = false + val text = withContext(Dispatchers.IO) { fetchText(WinlatorLayouts.INDEX_URL) } + names = text?.let(WinlatorLayouts::parseIndex) + failed = names.isNullOrEmpty() + } + Text(stringResource(R.string.flow_community_hint), Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant) + SettingsGroup(stringResource(R.string.flow_community)) { + val list = names + when { + failed -> ActionRow(stringResource(R.string.flow_community_failed), null, stringResource(R.string.input_capture_retry), { attempt++ }) + list == null -> Text(stringResource(R.string.flow_loading), Modifier.padding(16.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) + else -> for (file in list) { + val title = file.removeSuffix(".icp").removeSuffix(".ICP") + val preview = previews[file] + SettingsRow(title, null) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + preview?.let { InputLayoutThumbnail(it.first, role) } + if (preview == null) SecondaryButton(stringResource(if (loading == file) R.string.flow_loading else R.string.flow_preview), + enabled = loading == null, compact = true, modifier = Modifier.testTag("community-preview-$title")) { + loading = file + scope.launch { + val metrics = inputDisplayMetrics(context, role) + val raw = withContext(Dispatchers.IO) { fetchText(WinlatorLayouts.fileUrl(file)) } + previews[file] = raw?.let { + WinlatorLayouts.import(it, title, if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, + metrics.widthPixels, metrics.heightPixels) + } + if (previews[file] == null) failed = raw == null + loading = null + } + } + else PrimaryButton(stringResource(R.string.flow_use), compact = true, modifier = Modifier.testTag("community-use-$title")) { onUse(preview) } + } + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DrawerControls.kt b/app/src/main/java/com/droiddeck/launcher/ui/DrawerControls.kt new file mode 100644 index 0000000000..f568a395db --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DrawerControls.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import android.content.SharedPreferences +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.* +import com.droiddeck.launcher.session.SessionPrefs + +/** The library as it is saved now, re-read whenever something else saves it. */ +@Composable +internal fun rememberInputLibrary(): State { + val context = LocalContext.current + val library = remember { mutableStateOf(InputLibraries.read(context)) } + DisposableEffect(context) { + val preferences = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE) + val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "library") library.value = InputLibraries.read(context) } + preferences.registerOnSharedPreferenceChangeListener(listener) + onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) } + } + return library +} + +/** The session menu's Controls section: which profile applies, whether changes are for this game, and the two editors. */ +@Composable +internal fun DrawerControlsGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val context = LocalContext.current + val library by rememberInputLibrary() + var forAll by remember { mutableStateOf(SessionPrefs.inputForAllGames(context)) } + var failure by remember { mutableStateOf(null) } + val game = a.inputGame + val gameScope = game != null && !forAll + fun update(change: (InputLibrary) -> InputLibrary) { + runCatching { InputLibraries.update(context, change) }.onSuccess { a.onInputSelection(null) } + .onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } + } + val gameKey = game?.first + val active = library.profile(library.activeId(a.desktop, gameKey)) + val changes = gameKey?.let { library.gameChanges(a.desktop, it) } ?: 0 + val own = gameKey?.let { library.games[it] } + val defaultName = library.profile(library.defaultId(a.desktop)).name + val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.flow_default_profile, defaultName)) + library.profiles.map { it.id to it.name } + val selected = if (gameScope) own?.profile ?: InputProfiles.AUTO else library.selection(a.desktop).profile + val detail = listOfNotNull(active.name, if (changes > 0 && game != null) stringResource(R.string.flow_game_changes, game.second, changes) else null).joinToString(" · ") + SettingsGroup(stringResource(R.string.flow_controls), key = "controller-input", detail = detail) { + ChoiceRow(host, "input-profile", stringResource(R.string.input_profile), null, profiles, selected, chipModifier = track("input-profile")) { id -> + if (gameScope && game != null) update { it.withGameProfile(game.first, game.second, id.takeUnless { it == InputProfiles.AUTO }) } + else update { it.selectProfile(a.desktop, id) } + } + if (game != null) ChoiceRow(host, "input-scope", stringResource(R.string.flow_save_for), stringResource(R.string.flow_save_for_hint), + listOf(false to game.second, true to stringResource(R.string.flow_all_games)), forAll, chipModifier = track("input-scope")) { + forAll = it; SessionPrefs.setInputForAllGames(context, it) + } + val physical = if (gameKey != null && own?.parts?.containsKey(InputRole.PHYSICAL) == true) + stringResource(R.string.flow_game_changes, game.second, library.gameChanges(a.desktop, gameKey, InputRole.PHYSICAL)) + else active.name + ActionRow(stringResource(R.string.flow_buttons), physical, stringResource(R.string.ctrl_edit), a.onEditButtons, + modifier = track("input-buttons").testTag("input-edit-buttons")) + a.onEditLayout?.let { edit -> + val layoutName = if (a.oscMode == SessionPrefs.OSC_STEAM_TOUCH && a.steam) stringResource(R.string.osc_steam_layout) + else library.activeLayout(a.desktop, InputRole.PRIMARY, gameKey)?.name + ActionRow(stringResource(R.string.flow_layout), layoutName, stringResource(R.string.ctrl_edit), edit, + modifier = track("input-layout").testTag("input-edit-layout")) + } + if (gameKey != null && own != null) ActionRow(stringResource(R.string.flow_use_profile), stringResource(R.string.flow_use_profile_hint, game.second), + stringResource(R.string.ctrl_reset), { update { it.resetGame(gameKey) } }, modifier = track("input-game-reset").testTag("input-game-reset")) + ActionRow(stringResource(R.string.flow_all_settings), null, stringResource(R.string.ctrl_edit), a.onInputSettings, + modifier = track("input-settings").testTag("input-profile-edit")) + } + failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) }, + text = { Text(message) }, confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputActionEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputActionEditor.kt index 01464cef3b..c4bd965a9f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputActionEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputActionEditor.kt @@ -12,6 +12,32 @@ import androidx.compose.ui.unit.dp import com.droiddeck.launcher.R import com.droiddeck.launcher.input.* +/** The action being edited, with what each kind of action was set to so switching kinds and back loses nothing. */ +internal class InputActionDraft(initial: InputAction) { + var action by mutableStateOf(initial) + private val drafts = mutableMapOf() + var localType by mutableStateOf(typeOf(initial).takeUnless { it == "native" || it == "disabled" } ?: "keys") + private set + + fun switch(type: String, initial: () -> InputAction) { + drafts[typeOf(action)] = action + action = drafts[type] ?: initial() + if (type != "native" && type != "disabled") localType = type + } + + companion object { + fun typeOf(action: InputAction): String = when (action) { + is InputAction.Native -> "native"; InputAction.Disabled -> "disabled" + is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command" + is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll" + is InputAction.Directions -> "directions"; is InputAction.Keys -> "keys" + } + } +} + +internal fun InputAction.validAs(control: InputControl, element: InputSurfaceElement?, click: Boolean) = + if (click) validForClick() else if (element != null) validFor(element) else validFor(control) + @Composable internal fun InputActionEditor( control: InputControl, current: InputAction, title: String, onBack: () -> Unit, onSave: (InputAction) -> Unit, @@ -19,118 +45,114 @@ internal fun InputActionEditor( properties: (@Composable ColumnScope.(InputAction) -> Unit)? = null, click: Boolean = false, ) { - val context = LocalContext.current val host = rememberMenuHost() - var draft by remember(current, title) { mutableStateOf(current) } - val drafts = remember(current, title) { mutableMapOf() } - fun typeOf(action: InputAction): String = when (action) { - is InputAction.Native -> "native"; InputAction.Disabled -> "disabled" - is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command" - is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll" - is InputAction.Directions -> "directions"; is InputAction.Keys -> "keys" - } - var localType by remember(current, title) { mutableStateOf(typeOf(current).takeUnless { it == "native" || it == "disabled" } ?: "keys") } - fun switch(type: String, initial: () -> InputAction) { - drafts[typeOf(draft)] = draft - draft = drafts[type] ?: initial() - if (type != "native" && type != "disabled") localType = type - } - var keys by remember { mutableStateOf(false) } - var direction by remember { mutableStateOf(null) } - fun valid(action: InputAction) = if (click) action.validForClick() else if (element != null) action.validFor(element) else action.validFor(control) - val nativeOptions = remember(control, element, nativeTargets, click) { - (listOf(InputAction.Native()) + if (nativeTargets) InputControl.entries.map { InputAction.Native(it) } else emptyList()).filter(::valid) - } - val route = when (draft) { is InputAction.Native -> 0; InputAction.Disabled -> 2; else -> 1 } + val draft = remember(current, title) { InputActionDraft(current) } BackHandler(onBack = onBack) SettingsPage(host, title, onBack, eyebrow = stringResource(R.string.input_properties), lede = detail, - action = { PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = valid(draft), - modifier = Modifier.testTag("input-action-save")) { onSave(draft) } }) { - properties?.invoke(this, draft) + action = { PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = draft.action.validAs(control, element, click), + modifier = Modifier.testTag("input-action-save")) { onSave(draft.action) } }) { + properties?.invoke(this, draft.action) Spacer(Modifier.height(12.dp)) - SheetChips(listOf(stringResource(R.string.input_route_controller), stringResource(R.string.input_route_local), stringResource(R.string.input_disabled)), route) { - when (it) { - 0 -> switch("native") { nativeOptions.firstOrNull() ?: InputAction.Disabled } - 2 -> switch("disabled") { InputAction.Disabled } - else -> switch(localType) { InputAction.Keys(listOf(28)) } - } + InputActionFields(host, control, draft, element, nativeTargets, click) + } +} + +/** Where an action goes (the controller, DroidDeck's own input, or nowhere) and its settings. Edits [draft] in place. */ +@Composable +internal fun InputActionFields( + host: MenuHost, control: InputControl, draft: InputActionDraft, + element: InputSurfaceElement? = null, nativeTargets: Boolean = true, click: Boolean = false, +) { + val context = LocalContext.current + var keys by remember { mutableStateOf(false) } + var direction by remember { mutableStateOf(null) } + val nativeOptions = remember(control, element, nativeTargets, click) { + (listOf(InputAction.Native()) + if (nativeTargets) InputControl.entries.map { InputAction.Native(it) } else emptyList()) + .filter { it.validAs(control, element, click) } + } + val route = when (draft.action) { is InputAction.Native -> 0; InputAction.Disabled -> 2; else -> 1 } + SheetChips(listOf(stringResource(R.string.input_route_controller), stringResource(R.string.input_route_local), stringResource(R.string.input_disabled)), route) { + when (it) { + 0 -> draft.switch("native") { nativeOptions.firstOrNull() ?: InputAction.Disabled } + 2 -> draft.switch("disabled") { InputAction.Disabled } + else -> draft.switch(draft.localType) { InputAction.Keys(listOf(28)) } } - Spacer(Modifier.height(16.dp)) - when (route) { - 0 -> SettingsGroup(stringResource(R.string.input_route_controller)) { - ChoiceRow(host, "native-target", stringResource(R.string.input_remap_native), stringResource(R.string.input_controller_route_hint), - nativeOptions.map { it to (it.target?.label ?: stringResource(if (nativeTargets) R.string.input_native else R.string.input_normal_binding)) }, - draft as InputAction.Native) { draft = it } - } - 2 -> Text(stringResource(R.string.input_disabled_hint), Modifier.padding(16.dp)) - else -> { - val types = listOf("keys" to stringResource(R.string.input_keys), "mouse" to stringResource(R.string.input_mouse_click), - "command" to stringResource(R.string.input_command)) + if (control.dimensions == 2) listOf( - "pointer" to stringResource(R.string.input_pointer), "scroll" to stringResource(R.string.input_scroll), - "directions" to stringResource(R.string.input_direction_keys)) else emptyList() - val type = when (draft) { is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command"; - is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"; is InputAction.Directions -> "directions"; else -> "keys" } - SettingsGroup(stringResource(R.string.input_action)) { - ChoiceRow(host, "action-type", stringResource(R.string.input_action), null, types, type) { - switch(it) { when (it) { "mouse" -> InputAction.MouseButton(272); "command" -> InputAction.Command(InputCommand.MENU); - "pointer" -> InputAction.Pointer(); "scroll" -> InputAction.Scroll(); - "directions" -> InputAction.Directions(103, 106, 108, 105); else -> InputAction.Keys(listOf(28)) } } + } + Spacer(Modifier.height(16.dp)) + when (route) { + 0 -> SettingsGroup(stringResource(R.string.input_route_controller)) { + ChoiceRow(host, "native-target", stringResource(R.string.input_remap_native), stringResource(R.string.input_controller_route_hint), + nativeOptions.map { it to (it.target?.label ?: stringResource(if (nativeTargets) R.string.input_native else R.string.input_normal_binding)) }, + draft.action as InputAction.Native) { draft.action = it } + } + 2 -> Text(stringResource(R.string.input_disabled_hint), Modifier.padding(16.dp)) + else -> { + val types = listOf("keys" to stringResource(R.string.input_keys), "mouse" to stringResource(R.string.input_mouse_click), + "command" to stringResource(R.string.input_command)) + if (control.dimensions == 2) listOf( + "pointer" to stringResource(R.string.input_pointer), "scroll" to stringResource(R.string.input_scroll), + "directions" to stringResource(R.string.input_direction_keys)) else emptyList() + val type = when (draft.action) { is InputAction.MouseButton -> "mouse"; is InputAction.Command -> "command"; + is InputAction.Pointer -> "pointer"; is InputAction.Scroll -> "scroll"; is InputAction.Directions -> "directions"; else -> "keys" } + SettingsGroup(stringResource(R.string.input_action)) { + ChoiceRow(host, "action-type", stringResource(R.string.input_action), null, types, type) { + draft.switch(it) { when (it) { "mouse" -> InputAction.MouseButton(272); "command" -> InputAction.Command(InputCommand.MENU); + "pointer" -> InputAction.Pointer(); "scroll" -> InputAction.Scroll(); + "directions" -> InputAction.Directions(103, 106, 108, 105); else -> InputAction.Keys(listOf(28)) } } + } + if (!click && draft.action !is InputAction.Pointer && draft.action !is InputAction.Scroll && draft.action !is InputAction.Directions) { + val hint = when { + control.isTrackpad -> R.string.input_contact_action_hint + control.dimensions == 2 -> R.string.input_axis_action_hint + control == InputControl.LT || control == InputControl.RT -> R.string.input_trigger_action_hint + else -> null } - if (!click && draft !is InputAction.Pointer && draft !is InputAction.Scroll && draft !is InputAction.Directions) { - val hint = when { - control.isTrackpad -> R.string.input_contact_action_hint - control.dimensions == 2 -> R.string.input_axis_action_hint - control == InputControl.LT || control == InputControl.RT -> R.string.input_trigger_action_hint - else -> null - } - hint?.let { Text(stringResource(it), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), - style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } + hint?.let { Text(stringResource(it), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } + } + when (val action = draft.action) { + is InputAction.Keys -> ActionRow(stringResource(R.string.input_keys), actionLabel(action), stringResource(R.string.ctrl_edit), { keys = true }) + is InputAction.MouseButton -> ChoiceRow(host, "mouse-button", stringResource(R.string.input_mouse_click), null, + (272..274).map { it to actionLabel(InputAction.MouseButton(it)) }, action.code) { draft.action = InputAction.MouseButton(it) } + is InputAction.Command -> ChoiceRow(host, "command", stringResource(R.string.input_command), null, + InputCommand.entries.map { it to commandLabel(it) }, action.command) { draft.action = InputAction.Command(it) } + is InputAction.Pointer -> { + Text(stringResource(R.string.input_pointer_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface) + Slider(action.speed, { draft.action = action.copy(speed = it) }, valueRange = 100f..3000f, modifier = Modifier.padding(horizontal = 16.dp)) } - when (val action = draft) { - is InputAction.Keys -> ActionRow(stringResource(R.string.input_keys), actionLabel(action), stringResource(R.string.ctrl_edit), { keys = true }) - is InputAction.MouseButton -> ChoiceRow(host, "mouse-button", stringResource(R.string.input_mouse_click), null, - (272..274).map { it to actionLabel(InputAction.MouseButton(it)) }, action.code) { draft = InputAction.MouseButton(it) } - is InputAction.Command -> ChoiceRow(host, "command", stringResource(R.string.input_command), null, - InputCommand.entries.map { it to commandLabel(it) }, action.command) { draft = InputAction.Command(it) } - is InputAction.Pointer -> { - Text(stringResource(R.string.input_pointer_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface) - Slider(action.speed, { draft = action.copy(speed = it) }, valueRange = 100f..3000f, modifier = Modifier.padding(horizontal = 16.dp)) + is InputAction.Scroll -> { + ChoiceRow(host, "scroll-axis", stringResource(R.string.input_scroll_axis), null, + listOf(false to stringResource(R.string.input_vertical), true to stringResource(R.string.input_horizontal)), action.horizontal) { + draft.action = action.copy(horizontal = it) } - is InputAction.Scroll -> { - ChoiceRow(host, "scroll-axis", stringResource(R.string.input_scroll_axis), null, - listOf(false to stringResource(R.string.input_vertical), true to stringResource(R.string.input_horizontal)), action.horizontal) { - draft = action.copy(horizontal = it) - } - Text(stringResource(R.string.input_scroll_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface) - Slider(action.speed, { draft = action.copy(speed = it) }, valueRange = 1f..60f, modifier = Modifier.padding(horizontal = 16.dp)) - } - is InputAction.Directions -> { - ToggleRow(host, "direction-diagonals", stringResource(R.string.input_diagonal_keys), stringResource(R.string.input_diagonal_keys_hint), action.diagonals != null) { - draft = action.copy(diagonals = if (it) action.diagonals ?: listOf(0, 0, 0, 0) else null) - } - val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty() - val arrows = listOf("↑", "→", "↓", "←", "↗", "↘", "↙", "↖") - codes.forEachIndexed { i, code -> - ActionRow(arrows[i], if (code == 0) stringResource(if (i < 4) R.string.input_disabled else R.string.input_diagonal_neighbors) else pcKeyLabel(context, code), stringResource(R.string.ctrl_edit), { direction = i }) - } - } - else -> Unit + Text(stringResource(R.string.input_scroll_speed, action.speed.toInt()), Modifier.padding(horizontal = 16.dp, vertical = 8.dp), color = MaterialTheme.colorScheme.onSurface) + Slider(action.speed, { draft.action = action.copy(speed = it) }, valueRange = 1f..60f, modifier = Modifier.padding(horizontal = 16.dp)) } + is InputAction.Directions -> { + ToggleRow(host, "direction-diagonals", stringResource(R.string.input_diagonal_keys), stringResource(R.string.input_diagonal_keys_hint), action.diagonals != null) { + draft.action = action.copy(diagonals = if (it) action.diagonals ?: listOf(0, 0, 0, 0) else null) + } + val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty() + val arrows = listOf("↑", "→", "↓", "←", "↗", "↘", "↙", "↖") + codes.forEachIndexed { i, code -> + ActionRow(arrows[i], if (code == 0) stringResource(if (i < 4) R.string.input_disabled else R.string.input_diagonal_neighbors) else pcKeyLabel(context, code), stringResource(R.string.ctrl_edit), { direction = i }) + } + } + else -> Unit } } } } - if (keys) KeyCombinationPicker(onDismiss = { keys = false }, initial = (draft as? InputAction.Keys)?.codes.orEmpty(), + if (keys) KeyCombinationPicker(onDismiss = { keys = false }, initial = (draft.action as? InputAction.Keys)?.codes.orEmpty(), sequence = true, sequenceLimit = 8, title = stringResource(R.string.input_keys), confirm = stringResource(R.string.gesture_save_changes), onAdd = { - draft = InputAction.Keys(it.sortedBy { code -> if (code in PC_MODIFIERS) 0 else 1 }); keys = false + draft.action = InputAction.Keys(it.sortedBy { code -> if (code in PC_MODIFIERS) 0 else 1 }); keys = false }) direction?.let { at -> - val action = draft as? InputAction.Directions ?: return@let + val action = draft.action as? InputAction.Directions ?: return@let val codes = listOf(action.up, action.right, action.down, action.left) + action.diagonals.orEmpty() KeyCombinationPicker(onDismiss = { direction = null }, initial = listOf(codes[at]).filter { it != 0 }, sequence = true, sequenceLimit = 1, allowEmpty = true, title = stringResource(R.string.input_direction_keys), confirm = stringResource(R.string.gesture_save_changes), onAdd = { val next = codes.toMutableList().also { values -> values[at] = it.firstOrNull() ?: 0 } - draft = InputAction.Directions(next[0], next[1], next[2], next[3], if (action.diagonals != null) next.drop(4) else null); direction = null + draft.action = InputAction.Directions(next[0], next[1], next[2], next[3], if (action.diagonals != null) next.drop(4) else null); direction = null }) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputButtonsEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputButtonsEditor.kt new file mode 100644 index 0000000000..ac08e0875a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputButtonsEditor.kt @@ -0,0 +1,193 @@ +package com.droiddeck.launcher.ui + +import android.view.KeyEvent +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.* + +/** + * What an in-game editor works on: the bindings (and layout) one role uses now, already copied for the game when changes + * are for it alone. [scope] names whose controls these are; [game] is set when the copy was made just for this edit. + */ +internal data class InputEditorTarget( + val role: InputRole, val profile: String, val bindings: String, val layout: String?, + val scope: String, val game: String? = null, val desktop: Boolean = false, +) + +@Composable +internal fun InputEditorWindow(target: InputEditorTarget, onDismiss: () -> Unit, onChanged: () -> Unit) { + if (target.role == InputRole.PHYSICAL) Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Surface(Modifier.fillMaxSize().systemBarsPadding().padding(8.dp), color = MaterialTheme.colorScheme.surface, shape = RoundedCornerShape(18.dp)) { + val library by rememberInputLibrary() + val base = library.profiles.firstOrNull { it.id == target.profile }?.binding(InputRole.PHYSICAL)?.takeIf { it != target.bindings } + InputButtonsPane(target.bindings, target.scope, base, onDismiss, onChanged) + } + } else InputSurfaceDialog(target.profile, onDismiss, onChanged, role = target.role, layoutId = target.layout, bindingsId = target.bindings) +} + +private val controllerKeys = mapOf( + KeyEvent.KEYCODE_BUTTON_A to InputControl.A, KeyEvent.KEYCODE_BUTTON_B to InputControl.B, + KeyEvent.KEYCODE_BUTTON_X to InputControl.X, KeyEvent.KEYCODE_BUTTON_Y to InputControl.Y, + KeyEvent.KEYCODE_BUTTON_L1 to InputControl.LB, KeyEvent.KEYCODE_BUTTON_R1 to InputControl.RB, + KeyEvent.KEYCODE_BUTTON_L2 to InputControl.LT, KeyEvent.KEYCODE_BUTTON_R2 to InputControl.RT, + KeyEvent.KEYCODE_BUTTON_THUMBL to InputControl.L3, KeyEvent.KEYCODE_BUTTON_THUMBR to InputControl.R3, + KeyEvent.KEYCODE_BUTTON_SELECT to InputControl.SELECT, KeyEvent.KEYCODE_BUTTON_START to InputControl.START, + KeyEvent.KEYCODE_BUTTON_MODE to InputControl.GUIDE, + KeyEvent.KEYCODE_DPAD_UP to InputControl.UP, KeyEvent.KEYCODE_DPAD_RIGHT to InputControl.RIGHT, + KeyEvent.KEYCODE_DPAD_DOWN to InputControl.DOWN, KeyEvent.KEYCODE_DPAD_LEFT to InputControl.LEFT, +) + +/** The control a controller key press stands for, when it is one of the standard gamepad keys. */ +internal fun controlForKey(keyCode: Int): InputControl? = controllerKeys[keyCode] + +/** + * Buttons and sticks: tap a control on a drawing of the controller, or press it, then set what it does. Saves into the + * bindings [bindingsId]; [baseId] is the profile's own bindings when these are a game's copy, so a control can go back. + */ +@Composable +internal fun InputButtonsPane(bindingsId: String, scope: String, baseId: String?, onBack: () -> Unit, onChanged: () -> Unit, + onMore: (() -> Unit)? = null) { + val context = LocalContext.current + val host = rememberMenuHost() + val library by rememberInputLibrary() + val preset = library.bindings.firstOrNull { it.id == bindingsId } ?: return + val base = baseId?.let { id -> library.bindings.firstOrNull { it.id == id } } + var selected by remember { mutableStateOf(InputControl.A) } + var capturing by remember { mutableStateOf(false) } + var failure by remember { mutableStateOf(null) } + val current = preset.controls[selected] ?: InputAction.Native() + val draft = remember(selected, current) { InputActionDraft(current) } + fun save(action: InputAction) { + runCatching { InputLibraries.update(context) { l -> l.withPreset(l.preset(bindingsId).let { it.copy(controls = it.controls + (selected to action)) }) } } + .onSuccess { onChanged() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } + } + val changed = InputControl.padControls.filter { c -> + (preset.controls[c] ?: InputAction.Native()) != (base?.controls?.get(c) ?: InputAction.Native()) + } + BackHandlerCompat(onBack) + BoxWithConstraints(Modifier.fillMaxSize().padding(16.dp).onPreviewKeyEvent { event -> + val control = controlForKey(event.nativeKeyEvent.keyCode) + if (!capturing || control == null) return@onPreviewKeyEvent false + if (event.nativeKeyEvent.action == KeyEvent.ACTION_UP) { selected = control; capturing = false } + true + }.testTag("input-buttons")) { + val wide = maxWidth > 700.dp + val boxWidth = maxWidth + val pad: @Composable (Modifier) -> Unit = { modifier -> + Column(modifier, verticalArrangement = Arrangement.spacedBy(10.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(stringResource(R.string.flow_buttons), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f, fill = false)) + ScopePill(stringResource(R.string.flow_saving_for, scope)) + } + Text(stringResource(if (capturing) R.string.flow_press_now else R.string.flow_buttons_hint), fontSize = 13.sp, + color = if (capturing) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant) + Box((if (wide) Modifier.fillMaxWidth().weight(1f) else Modifier.fillMaxWidth().height(boxWidth * .6f)).clip(RoundedCornerShape(14.dp)).background(MaterialTheme.colorScheme.background) + .border(1.dp, MaterialTheme.colorScheme.outlineVariant, RoundedCornerShape(14.dp))) { + ControllerDrawing(selected, Modifier.fillMaxSize()) { selected = it } + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + SecondaryButton(stringResource(if (capturing) R.string.common_cancel else R.string.flow_press), compact = true, + modifier = Modifier.testTag("input-buttons-press")) { capturing = !capturing } + onMore?.let { SecondaryButton(stringResource(R.string.flow_more_buttons), compact = true, onClick = it) } + } + OtherControls(selected) { selected = it } + val summaries = mutableListOf() + for (c in changed) summaries += "${c.label} → ${actionLabel(preset.controls[c] ?: InputAction.Native())}" + if (summaries.isNotEmpty()) Text(summaries.joinToString(" · "), + fontSize = 13.sp, color = MaterialTheme.colorScheme.primary, modifier = Modifier.testTag("input-buttons-changed")) + } + } + val panel: @Composable (Modifier) -> Unit = { modifier -> + Column(if (wide) modifier.verticalScroll(rememberScrollState()) else modifier) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(selected.label, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onBack) + } + Spacer(Modifier.height(12.dp)) + InputActionFields(host, selected, draft) + Spacer(Modifier.height(12.dp)) + Actions { + PrimaryButton(stringResource(R.string.gesture_save_changes), enabled = draft.action != current && draft.action.validFor(selected), + modifier = Modifier.testTag("input-buttons-save")) { save(draft.action) } + val profileAction = base?.controls?.get(selected) ?: InputAction.Native() + if (base != null && current != profileAction) SecondaryButton(stringResource(R.string.flow_profile_binding, actionLabel(profileAction)), + modifier = Modifier.testTag("input-buttons-reset")) { save(profileAction) } + } + } + } + if (wide) Row(horizontalArrangement = Arrangement.spacedBy(20.dp)) { pad(Modifier.weight(1.2f).fillMaxHeight()); panel(Modifier.weight(1f)) } + else Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp)) { + pad(Modifier.fillMaxWidth()); panel(Modifier.fillMaxWidth()) + } + } + failure?.let { message -> androidx.compose.material3.AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) }, + text = { Text(message) }, confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) } +} + +@Composable +private fun BackHandlerCompat(onBack: () -> Unit) = androidx.activity.compose.BackHandler(onBack = onBack) + +@Composable +internal fun ScopePill(text: String) { + Text(text, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.primary, + modifier = Modifier.clip(RoundedCornerShape(8.dp)).background(MaterialTheme.colorScheme.primary.copy(alpha = .14f)).padding(horizontal = 8.dp, vertical = 4.dp)) +} + +/** The standard pad, drawn with the selected virtual controller's art; tapping a control picks it. */ +@Composable +private fun ControllerDrawing(selected: InputControl, modifier: Modifier, onPick: (InputControl) -> Unit) { + val context = LocalContext.current + val pick by rememberUpdatedState(onPick) + AndroidView(factory = { InputSurfaceEditorView(it).apply { selectOnly = true; setBackgroundColor(android.graphics.Color.TRANSPARENT) } }, + modifier = modifier.testTag("input-buttons-pad"), update = { view -> + view.onSelect = { id -> id?.removePrefix("legacy:")?.let(InputControl::fromId)?.let(pick) } + view.onResize = { _, _ -> } + fun place() { + if (view.width <= 0 || view.height <= 0) return + val stock = LegacyGamepadLayout(context, view.width, view.height).elements().filter { it.id.startsWith("legacy:") } + val layout = SavedInputLayout(InputLibraries.OVERLAY, "", stock) + view.sourceLayout = layout + view.aspect = view.width.toFloat() / view.height + view.elements = OnScreenLayout.editorElements(context, layout, view.width, view.height).filter { it.id.startsWith("legacy:") } + } + view.selected = "legacy:${selected.id}" + if (view.elements.isEmpty()) view.post { place() } + }) +} + +/** Controls the drawing doesn't show: back buttons, Steam and Quick Access, stick clicks and trackpads. */ +@Composable +private fun OtherControls(selected: InputControl, onPick: (InputControl) -> Unit) { + val others = listOf(InputControl.L3, InputControl.R3, InputControl.L4, InputControl.R4, InputControl.L5, InputControl.R5, + InputControl.GUIDE, InputControl.QAM, InputControl.LEFT_PAD, InputControl.RIGHT_PAD, InputControl.LEFT_CLICK, InputControl.RIGHT_CLICK) + Text(stringResource(R.string.flow_other_controls), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) + @OptIn(ExperimentalLayoutApi::class) + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + for (control in others) { + if (control == selected) PrimaryButton(control.label, compact = true, modifier = Modifier.testTag("input-other-${control.id}")) { onPick(control) } + else SecondaryButton(control.label, compact = true, modifier = Modifier.testTag("input-other-${control.id}")) { onPick(control) } + } + } +} 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 1274945a3b..3d30b603cd 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -65,7 +65,7 @@ private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) { } } -private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE } +private enum class InputPage { HOME, PROFILE, BUTTONS, SOURCE, LAYOUTS, REUSE } private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false) private data class InputNameRequest(val title: Int, val initial: String, val sources: List> = emptyList(), val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit) @@ -101,7 +101,6 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe var error by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() val controller = rememberControllerSettings() - var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) } fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) } .onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess fun go(next: InputPage) { page = next; host.open = null } @@ -110,7 +109,8 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe edit != null -> edit = null page == InputPage.HOME -> onBack() page == InputPage.PROFILE -> go(InputPage.HOME) - page == InputPage.SOURCE -> go(InputPage.PROFILE) + page == InputPage.SOURCE && role == InputRole.PHYSICAL -> go(InputPage.BUTTONS) + page == InputPage.SOURCE || page == InputPage.BUTTONS -> go(InputPage.PROFILE) else -> go(InputPage.SOURCE) } } @@ -124,9 +124,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe scope.launch { val raw = withContext(Dispatchers.IO) { readLayoutFile(context, uri) } val metrics = inputDisplayMetrics(context, target) - val imported = raw?.let { InputLayoutFile.import(context, it, layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout), - if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, layout?.style ?: InputSurfaceStyle(), - metrics.widthPixels, metrics.heightPixels, metrics.density) } + val screen = if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY + val name = layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout) + val imported = raw?.let { + if (WinlatorLayouts.isIcp(it)) WinlatorLayouts.import(it, name, screen, metrics.widthPixels, metrics.heightPixels) + else InputLayoutFile.import(context, it, name, screen, layout?.style ?: InputSurfaceStyle(), metrics.widthPixels, metrics.heightPixels, metrics.density) + } if (imported == null) error = context.getString(R.string.input_layout_import_failed) else if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, target, imported.first.id) }) go(InputPage.SOURCE) } @@ -185,10 +188,14 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe else -> currentPreset.copy(controls = currentPreset.controls + (editing.control to action)) }) }) edit = null }) + } else if (!surface && page == InputPage.BUTTONS) { + InputButtonsPane(profile.binding(InputRole.PHYSICAL), profile.name, null, onBack = ::back, onChanged = { library = InputLibraries.read(context); onChanged() }, + onMore = { role = InputRole.PHYSICAL; bindingsTab = 2; go(InputPage.SOURCE) }) } else if (!surface) key(page, profileId, role) { SettingsPage(host, title = when (page) { InputPage.HOME -> if (embedded) null else stringResource(R.string.setup_controller) InputPage.PROFILE -> profile.name + InputPage.BUTTONS -> stringResource(R.string.flow_buttons) InputPage.SOURCE -> roleLabel(role) InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts) InputPage.REUSE -> stringResource(R.string.input_use_settings_from) @@ -200,30 +207,45 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) { when (page) { InputPage.HOME -> { - SettingsGroup(stringResource(R.string.input_default_profiles)) { - ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null, - library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } } - ChoiceRow(host, "auto-game", stringResource(R.string.input_game_mode), null, - library.profiles.map { it.id to it.name }, library.steam) { id -> update { it.copy(steam = id) } } - for (desktop in listOf(true, false)) { - val selection = library.selection(desktop) - if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint, - stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode))) - } - } if (InputLibraries.hasPendingScreenKeyMigration(context)) InputHint(stringResource(R.string.input_import_failed)) if (InputLibraries.hasLibraryRecovery(context)) InputHint(stringResource(R.string.input_library_recovered)) if (library.profiles.any { it.id.startsWith("migrated.screenkeys.") }) Text(stringResource(R.string.input_imported_keys_hint), Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) SettingsGroup(stringResource(R.string.input_profiles)) { - for (p in library.profiles) InputNavigationRow(p.name, when { - p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both) - p.id == library.steam -> stringResource(R.string.input_default_game) - p.id == library.desktop -> stringResource(R.string.input_default_desktop) - else -> null - }, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) } + for (p in library.profiles) { + val pinned = library.games.values.count { it.profile == p.id } + val uses = listOfNotNull(when { + p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both) + p.id == library.steam -> stringResource(R.string.input_default_game) + p.id == library.desktop -> stringResource(R.string.input_default_desktop) + else -> null + }, if (pinned > 0) stringResource(R.string.flow_used_games, pinned) else null) + InputNavigationRow(p.name, uses.joinToString(" · ").ifEmpty { null }, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) } + } + for (desktop in listOf(true, false)) { + val selection = library.selection(desktop) + if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint, + stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode))) + } PadTextButton(onClick = { newProfile(false) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_profile)) } } + if (library.games.isNotEmpty()) SettingsGroup(stringResource(R.string.flow_games)) { + InputHint(stringResource(R.string.flow_games_hint)) + for ((key, game) in library.games.entries.sortedBy { it.value.name.lowercase() }) { + val pinned = game.profile?.let { id -> library.profiles.firstOrNull { it.id == id }?.name } + val changes = library.gameChanges(false, key) + ActionRow(game.name, listOfNotNull(pinned, if (changes > 0) stringResource(R.string.flow_game_changes, game.name, changes) else null) + .joinToString(" · ").ifEmpty { null }, stringResource(R.string.ctrl_reset), { update { it.resetGame(key) } }, + modifier = Modifier.testTag("input-game-$key")) + } + } + SettingsGroup(stringResource(R.string.flow_touch_controls)) { + var touch by remember { mutableStateOf(ControllerPrefs.read(context)) } + SliderRow(stringResource(R.string.ctrl_size), null, touch.size, ControllerPrefs.sizes.first()..ControllerPrefs.sizes.last(), step = 5, + format = { "$it%" }) { ControllerPrefs.setSize(context, it); touch = ControllerPrefs.read(context); onChanged() } + SliderRow(stringResource(R.string.ctrl_opacity), null, touch.onScreenOpacity, ControllerPrefs.onScreenOpacityRange, step = 5, + format = { "$it%" }) { ControllerPrefs.setOnScreenOpacity(context, it); touch = ControllerPrefs.read(context); onChanged() } + } SettingsGroup(stringResource(R.string.input_device_settings)) { ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, controller.rumble) { ControllerPrefs.setRumble(context, it); onChanged() } ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, controller.deadZone) { ControllerPrefs.setDeadZone(context, it); onChanged() } @@ -246,12 +268,32 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } } InputPage.PROFILE -> { + val uses = when { + library.steam == profileId && library.desktop == profileId -> "both" + library.steam == profileId -> "game" + library.desktop == profileId -> "desktop" + else -> "none" + } + val builtIn = profileId == InputProfile.GAME || profileId == InputProfile.DESKTOP + SettingsGroup(stringResource(R.string.flow_default_for)) { + ChoiceRow(host, "profile-default", stringResource(R.string.flow_default_for), null, listOfNotNull( + "game" to stringResource(R.string.input_game_mode), "desktop" to stringResource(R.string.input_desktop_mode), + "both" to stringResource(R.string.flow_both_modes), if (builtIn) null else "none" to stringResource(R.string.flow_no_mode)), uses) { pick -> + update { l -> + l.copy(steam = if (pick == "game" || pick == "both") profileId else if (l.steam == profileId) InputProfile.GAME else l.steam, + desktop = if (pick == "desktop" || pick == "both") profileId else if (l.desktop == profileId) InputProfile.DESKTOP else l.desktop) + } + } + } SettingsGroup(stringResource(R.string.input_profile_controls)) { - for (r in InputRole.entries) InputNavigationRow(roleLabel(r), - if (r == InputRole.PHYSICAL) stringResource(R.string.input_physical_hint) else library.layout(profileId, r)?.name, - Modifier.testTag("input-part-${r.name.lowercase()}"), leading = { - library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) } - }) { editPart(r) } + InputNavigationRow(stringResource(R.string.flow_buttons), stringResource(R.string.input_physical_hint), + Modifier.testTag("input-part-physical")) { role = InputRole.PHYSICAL; go(InputPage.BUTTONS) } + for (r in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) { + InputNavigationRow(if (r == InputRole.PRIMARY) stringResource(R.string.flow_layout) else roleLabel(r), library.layout(profileId, r)?.name, + Modifier.testTag("input-part-${r.name.lowercase()}"), leading = { + library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) } + }) { editPart(r) } + } } Spacer(Modifier.height(16.dp)) Actions { @@ -276,19 +318,9 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) { InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } } } - SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1, - format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } } - for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null, - button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } } } if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable)) } - if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) { - ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared), - listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), - SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), - oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() } - } SettingsGroup(stringResource(R.string.input_assign_actions)) { val users = library.usersOfBindings(preset.id) if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name })) @@ -324,8 +356,15 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } } InputPage.LAYOUTS -> { - InputHint(stringResource(R.string.input_layout_geometry_hint)) - SettingsGroup(stringResource(R.string.input_saved_layouts)) { + var community by remember { mutableStateOf(false) } + Box(Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) { + SheetChips(listOf(stringResource(R.string.flow_mine), stringResource(R.string.flow_community)), if (community) 1 else 0) { community = it == 1 } + } + if (community) CommunityLayouts(role) { imported -> + if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, role, imported.first.id) }) go(InputPage.SOURCE) + } + else InputHint(stringResource(R.string.input_layout_geometry_hint)) + if (!community) SettingsGroup(stringResource(R.string.input_saved_layouts)) { var showOther by remember { mutableStateOf(false) } val available = library.layouts.filter { it.supports(role) } val other = available.filter { saved -> !saved.id.startsWith("builtin.") && saved.id != layout?.id && @@ -350,6 +389,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } } + InputPage.BUTTONS -> Unit InputPage.REUSE -> { InputHint(stringResource(R.string.input_reuse_explanation, roleLabel(role))) SettingsGroup(stringResource(R.string.input_profiles)) { 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 8f8e592cd2..f2f5cdde66 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -88,6 +88,8 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB var toolsX by mutableFloatStateOf(-1f) var toolsY by mutableFloatStateOf(.02f) var snap by mutableStateOf(snap) + var grid by mutableIntStateOf(0) + var hidden by mutableStateOf(layout.style.hidden) var adding by mutableStateOf(false) var properties by mutableStateOf(false) var clickProperties by mutableStateOf(false) @@ -117,9 +119,11 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) } val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected } - val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect - fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) } - fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } } + val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || + aspect != layout.aspect || hidden != layout.style.hidden + private var lastAssigned: String? = null + fun checkpoint() { lastAssigned = null; history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) } + fun undo() { lastAssigned = null; history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } } private fun adoptDisplayedFrame(context: android.content.Context): Boolean { if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false val open = toolsExpanded @@ -203,6 +207,34 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB elements = elements.map { if (it.id == element.id) element else it } } + /** A D-pad arm is part of one control and can't be copied on its own. */ + fun canDuplicate(e: InputSurfaceElement) = !e.dpadPiece && elements.size < 64 + + /** Adds a copy of [id] next to it, doing what the original does, and selects it. */ + fun duplicate(id: String) { + val original = (elements.firstOrNull { it.id == id } ?: shown.firstOrNull { it.id == id })?.takeIf(::canDuplicate) ?: return + if (elements.any { it.id == id }) checkpoint() else stored(id) + val copy = original.copy(id = newInputId(), control = original.kind.control, + x = original.x + .03f, y = original.y + .03f).bounded() + fun resolved(action: InputAction) = if (action is InputAction.Native && action.target == null && original.kind != InputElementKind.DPAD) + InputAction.Native(original.control) else action + val action = resolved(action(original)).takeIf { it.validFor(copy) } ?: InputAction.Disabled + elements = elements + copy + actions = actions + (copy.id to action) + if (copy.hasClick) clickAction(original).takeIf { it.validForClick() }?.let { clicks = clicks + (copy.id to it) } + selected = copy.id + } + + /** Sets what [id] does (or, with [click], what clicking it does), keeping one undo step per control. */ + fun assign(id: String, action: InputAction, click: Boolean) { + val e = elements.firstOrNull { it.id == id } ?: shown.firstOrNull { it.id == id } ?: return + if (if (click) clickAction(e) == action else action(e) == action) return + val key = "$id/$click" + if (lastAssigned != key) { checkpoint(); lastAssigned = key } + stored(id) + if (click) clicks = clicks + (id to action) else actions = actions + (id to action) + } + fun resetPositions(context: android.content.Context) { val adopted = adoptDisplayedFrame(context) positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f } @@ -229,6 +261,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> } val defaults = InputLibraries.defaultPositions(context, library, savedLayout) SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context)) + .also { it.grid = ControllerPrefs.editorGrid(context) } } val manager = remember { context.getSystemService(DisplayManager::class.java) } var revision by remember { mutableIntStateOf(0) } @@ -249,7 +282,8 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> InputLibraries.update(context) { latest -> val l = latest.layouts.first { it.id == savedLayout.id } val p = latest.preset(savedBindings.id) - latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, + latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale) + .let { it.copy(style = it.style.copy(hidden = draft.hidden)) }).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } })) } }.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } @@ -323,7 +357,9 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> } else -> Box(Modifier.fillMaxSize()) { SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY) - FloatingSurfaceTools(draft, ::save, ::leave) + val selected = draft.element + if (selected != null) DockedElementPanel(draft, selected, ::save) + else FloatingSurfaceTools(draft, ::save, ::leave) } } } @@ -356,6 +392,7 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) { view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13)) view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap view.isEnabled = !draft.properties && !draft.adding + view.grid = if (draft.grid > 0) 1f / draft.grid else 0f view.onSelect = { if (!draft.properties) draft.selected = it } view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) } view.onResize = { w, h -> draft.canvas = IntSize(w, h) } @@ -415,10 +452,55 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav } } +/** The selected control's settings, docked on the side of the screen away from it so it never covers what is being edited. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun DockedElementPanel(draft: SurfaceDraft, element: InputSurfaceElement, onSave: () -> Unit) { + val context = LocalContext.current + val host = rememberMenuHost() + val onRight = element.x + element.width / 2 < .5f + var click by remember(element.id) { mutableStateOf(false) } + val clicking = click && element.hasClick + val current = if (clicking) draft.clickAction(element) else draft.action(element) + val actionDraft = remember(element.id, clicking) { InputActionDraft(current) } + val control = if (clicking) InputControl.A else element.control + LaunchedEffect(actionDraft.action) { + if (actionDraft.action.validAs(control, element.takeUnless { clicking }, clicking)) draft.assign(element.id, actionDraft.action, clicking) + } + BoxWithConstraints(Modifier.fillMaxSize()) { + Surface(Modifier.align(if (onRight) Alignment.CenterEnd else Alignment.CenterStart).padding(8.dp) + .width(minOf(380.dp, maxWidth * .48f)).fillMaxHeight().testTag("input-editor-panel"), + shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface, tonalElevation = 6.dp, shadowElevation = 10.dp) { + Column { + Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(element.name, style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() } + PrimaryButton(stringResource(R.string.input_editor_done), compact = true, modifier = Modifier.testTag("input-editor-done"), onClick = onSave) + } + Column(Modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, bottom = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (element.hasClick) SheetChips(listOf(stringResource(R.string.input_action), stringResource(R.string.input_click_name, element.name)), + if (clicking) 1 else 0) { click = it == 1 } + InputActionFields(host, control, actionDraft, element.takeUnless { clicking }, click = clicking) + if (!clicking) InputElementProperties(element, actionDraft.action) { draft.update(it) } + SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5, + format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleSelected(context, it) } + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + SecondaryButton(stringResource(R.string.flow_duplicate), enabled = draft.canDuplicate(element), compact = true, + modifier = Modifier.testTag("input-editor-duplicate")) { draft.duplicate(element.id) } + SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(element.id) } + SecondaryButton(stringResource(R.string.common_close), compact = true) { draft.selected = null } + } + } + } + } + } +} + @OptIn(ExperimentalLayoutApi::class) @Composable private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) { val context = LocalContext.current + val host = rememberMenuHost() FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave) SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true } @@ -432,6 +514,14 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () } if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, draft.scaleRange, step = 5, format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { if (draft.element != null) draft.scaleSelected(context, it) else draft.scaleAll(context, it) } + ChoiceRow(host, "editor-grid", stringResource(R.string.flow_grid), null, + ControllerPrefs.editorGrids.map { it to stringResource(when (it) { 0 -> R.string.widgets_off; 50 -> R.string.flow_grid_fine; else -> R.string.flow_grid_coarse }) }, + draft.grid) { draft.grid = it; ControllerPrefs.setEditorGrid(context, it) } + for (button in QUICK_BUTTONS.filter { b -> draft.elements.any { it.quickButton == b } }) { + ToggleRow(host, "editor-quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null, button !in draft.hidden) { shown -> + draft.hidden = if (shown) draft.hidden - button else draft.hidden + button + } + } } @OptIn(ExperimentalLayoutApi::class) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index 301747dc18..72a43ac506 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -38,6 +38,12 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { set(value) { field = value; updatePreviewStyle() } var snap = true set(value) { field = value; if (!value) clearGuides() } + /** Grid spacing as a fraction of the width; 0 for no grid. */ + var grid = 0f + set(value) { field = value; invalidate() } + /** Taps select a control; nothing moves. */ + var selectOnly = false + private val gridPaint = Paint().apply { color = Color.argb(40, 255, 255, 255); strokeWidth = 1f } private var guideX: Float? = null private var guideY: Float? = null var selected: String? = null @@ -99,6 +105,13 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { } override fun dispatchDraw(canvas: Canvas) { + if (grid > 0f && !selectOnly && width > 0) { + val step = grid * width + var x = step + while (x < width) { canvas.drawLine(x, 0f, x, height.toFloat(), gridPaint); x += step } + var y = step + while (y < height) { canvas.drawLine(0f, y, width.toFloat(), y, gridPaint); y += step } + } super.dispatchDraw(canvas) paint.style = Paint.Style.STROKE guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) } @@ -114,6 +127,18 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { private fun clearGuides() { guideX = null; guideY = null; invalidate() } + private fun onGrid(e: InputSurfaceElement, corner: Int): InputSurfaceElement { + val sx = grid + val sy = grid * width / height.coerceAtLeast(1) + fun round(value: Float, step: Float) = (Math.round(value / step) * step) + if (corner == 0) return e.copy(x = round(e.x, sx).coerceIn(0f, 1f - e.width), y = round(e.y, sy).coerceIn(0f, 1f - e.height)) + val right = if (corner and 2 != 0) round(e.x + e.width, sx).coerceIn(e.x + .03f, 1f) else e.x + e.width + val bottom = if (corner and 8 != 0) round(e.y + e.height, sy).coerceIn(e.y + .03f, 1f) else e.y + e.height + val left = if (corner and 1 != 0) round(e.x, sx).coerceIn(0f, right - .03f) else e.x + val top = if (corner and 4 != 0) round(e.y, sy).coerceIn(0f, bottom - .03f) else e.y + return e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded() + } + override fun onInterceptTouchEvent(event: MotionEvent) = true @SuppressLint("ClickableViewAccessibility") @@ -124,7 +149,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { clearGuides() downX = event.x; downY = event.y; dragging = false; corner = 0 val current = visibleElements.firstOrNull { it.id == selected }?.let { visibleElements.groupOf(it).frame() } - if (current != null) { + if (current != null && !selectOnly) { val left = width * current.x; val top = height * current.y val right = left + width * current.width; val bottom = top + height * current.height val horizontal = if (abs(downX - left) < radius) 1 else if (abs(downX - right) < radius) 2 else 0 @@ -139,7 +164,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { selected = touched?.id; onSelect(selected) } MotionEvent.ACTION_MOVE -> { - if (original.isEmpty()) return true + if (original.isEmpty() || selectOnly) return true val e = original.frame() if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) { dragging = true; onBeginEdit(visibleElements, width, height) @@ -160,7 +185,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { 9 * resources.displayMetrics.density / height, corner) else null if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) guideX = aligned?.x; guideY = aligned?.y - val f = aligned?.element ?: next + val f = aligned?.element ?: next.takeIf { grid > 0f }?.let { onGrid(it, corner) } ?: next val sx = f.width / e.width; val sy = f.height / e.height onChange(original.map { it.copy(x = f.x + (it.x - e.x) * sx, y = f.y + (it.y - e.y) * sy, width = it.width * sx, height = it.height * sy) }) invalidate() diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 2f0cc48a1f..651e973c19 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -336,17 +336,20 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: note = stringResource(R.string.mode_touch_note), onPick = a.onTouch, ) - if (steam && s.oscMode != null) ChoiceRow( - host, "osc", stringResource(R.string.mode_osc), null, - listOf( - SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), - SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), - SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), - SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), - SessionPrefs.OSC_NEVER to stringResource(R.string.common_never), - ), s.oscMode, - note = stringResource(R.string.mode_osc_note), onPick = a.onOsc, - ) + if (steam && s.oscMode != null) { + val source = touchSource(s.oscMode) + ChoiceRow( + host, "osc", stringResource(R.string.flow_touch_controls), null, + listOf(TOUCH_STEAM to stringResource(R.string.osc_steam_touch), TOUCH_DROIDDECK to stringResource(R.string.flow_touch_droiddeck), + TOUCH_OFF to stringResource(R.string.widgets_off)), source, + note = stringResource(R.string.mode_osc_note), + ) { a.onOsc(touchMode(it)) } + if (source == TOUCH_DROIDDECK) ChoiceRow( + host, "osc-show", stringResource(R.string.flow_show), null, + listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), + SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam)), s.oscMode, onPick = a.onOsc, + ) + } if (steam && s.steamController != null) ChoiceRow( host, "controller", stringResource(R.string.mode_controller), stringResource(R.string.mode_controller_hint), listOf( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 508c0f4ea9..4b5365bac2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -415,7 +415,7 @@ class SecondScreenPresentation( } private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context) - .panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context)) + .panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context), SessionState.inputGame) private fun bar(mode: SecondScreenMode) { val first = barModel(mode) ?: return diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 26524d326e..65b6b1cf1c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -335,7 +335,6 @@ class DrawerActions( val achievementsTitle: String? = null, val achievementsProgress: Pair? = null, val onOsc: (String) -> Unit, - val onEditSteamTouch: (() -> Unit)? = null, val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null, val onControllerSize: (Int) -> Unit = {}, val onControllerOpacity: (Int) -> Unit = {}, @@ -354,6 +353,10 @@ class DrawerActions( val onTouch: (String) -> Unit, val onInputSettings: () -> Unit = {}, val onInputSelection: (com.droiddeck.launcher.input.InputRole?) -> Unit = {}, + /** The game in front, as its key and name, when its controls can differ from the profile's. */ + val inputGame: Pair? = null, + val onEditButtons: () -> Unit = {}, + val onEditLayout: (() -> Unit)? = null, val onGestureSettings: () -> Unit = {}, val touchActive: String = "", val directHoldBehavior: String = MOUSE_BEHAVIOR_CLICK, @@ -731,9 +734,7 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: val off = stringResource(R.string.widgets_off) val padTag = if (padConnected) stringResource(R.string.drawer_tag_controller) else null val noPadTag = if (padConnected) null else stringResource(R.string.drawer_tag_no_controller) - SettingsGroup(stringResource(R.string.drawer_section_input), key = "controller-input") { - InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings, track = track) - } + DrawerControlsGroup(host, a, track) val c = a.controller val padTypes = listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck), SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam), @@ -753,12 +754,19 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: ToggleRow(host, "rumble", rumbleLabel, null, it.rumble, chipModifier = track("rumble"), onChange = a.onRumble) } } - val oscChoices = if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) - else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) val oscValue = if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode - SettingsGroup(stringResource(R.string.input_screen_visibility), key = "controller-osc", tag = noPadTag, - detail = summary(oscChoices.labelOf(oscValue), c?.let { "${it.size}%" })) { - ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, oscChoices, oscValue, chipModifier = track("osc"), onPick = a.onOsc) + val source = touchSource(oscValue) + val sources = listOfNotNull(if (a.steam) TOUCH_STEAM to stringResource(R.string.osc_steam_touch) else null, + TOUCH_DROIDDECK to stringResource(R.string.flow_touch_droiddeck), TOUCH_OFF to stringResource(R.string.widgets_off)) + val shows = listOfNotNull(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), + if (a.steam) SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam) else null) + SettingsGroup(stringResource(R.string.flow_touch_controls), key = "controller-osc", tag = noPadTag, + detail = summary(sources.labelOf(source), if (source == TOUCH_DROIDDECK) shows.labelOf(oscValue) else null, c?.let { "${it.size}%" }, c?.let { "${it.onScreenOpacity}%" })) { + ChoiceRow(host, "osc", stringResource(R.string.flow_touch_type), null, sources, source, chipModifier = track("osc")) { picked -> + a.onOsc(touchMode(picked)) + } + if (source == TOUCH_DROIDDECK) ChoiceRow(host, "osc-show", stringResource(R.string.flow_show), null, shows, oscValue, + chipModifier = track("osc-show"), onPick = a.onOsc) c?.let { SliderRow(stringResource(R.string.ctrl_size), null, it.size, 80..125, step = 5, format = { v -> "$v%" }, modifier = track("controller-size"), onChange = a.onControllerSize) @@ -781,10 +789,6 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown, chipModifier = track(key)) { a.onQuickButton(button, it) } } - a.onEditSteamTouch?.let { edit -> - ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit, - modifier = track("steam-touch-layout")) - } if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, chipModifier = track("unfolded-controls"), onChange = a.onUnfoldedControls) @@ -1155,6 +1159,23 @@ private fun List>.labelOf(value: T): String? = firstOrNull { private fun summary(vararg parts: String?): String = parts.filterNot { it.isNullOrEmpty() }.joinToString(" · ") +internal const val TOUCH_STEAM = "steam" +internal const val TOUCH_DROIDDECK = "droiddeck" +internal const val TOUCH_OFF = "off" + +/** Which touch controls a stored mode draws: Steam's, DroidDeck's, or none. How DroidDeck's show is the rest of the mode. */ +internal fun touchSource(mode: String) = when (mode) { + SessionPrefs.OSC_STEAM_TOUCH -> TOUCH_STEAM + SessionPrefs.OSC_NEVER -> TOUCH_OFF + else -> TOUCH_DROIDDECK +} + +internal fun touchMode(source: String) = when (source) { + TOUCH_STEAM -> SessionPrefs.OSC_STEAM_TOUCH + TOUCH_OFF -> SessionPrefs.OSC_NEVER + else -> SessionPrefs.OSC_AUTO +} + @Composable private fun DrawerActionButton(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector, modifier: Modifier = Modifier, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt index 5983063e1e..26985370a5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -139,8 +139,9 @@ internal object SettingsIndex { d(R.string.drawer_hud, R.string.drawer_hud, "fps", "counter", "overlay", "performance"), d(R.string.drawer_hud, R.string.perf_gpuclock, "gpu", "clock", "max"), d(R.string.drawer_page_controller, R.string.input_touchscreen, "touch", "mouse", "direct", "touchpad", "click"), - d(R.string.drawer_page_controller, R.string.mode_osc, "on-screen", "controls", "touch controls", "buttons"), - d(R.string.drawer_page_controller, R.string.osc_steam_layout, "touch layout", "edit layout", "on-screen"), + d(R.string.drawer_page_controller, R.string.flow_touch_controls, "on-screen", "controls", "steam touch", "visibility", "opacity", "size"), + d(R.string.drawer_page_controller, R.string.flow_layout, "touch layout", "edit layout", "on-screen", "osc"), + d(R.string.drawer_page_controller, R.string.flow_buttons, "remap", "mapping", "bindings", "buttons", "per game", "profile"), d(R.string.drawer_page_controller, R.string.drawer_pc_keyboard, "keyboard", "typing"), d(R.string.mode_session, R.string.report_problem, "logs", "log", "bug", "crash", "share", "zip"), d(R.string.mode_session, R.string.mode_suspend, "sleep", "background", "native", "resume"), diff --git a/app/src/main/res/values-ar/input_flow_strings.xml b/app/src/main/res/values-ar/input_flow_strings.xml new file mode 100644 index 0000000000..567ea3f824 --- /dev/null +++ b/app/src/main/res/values-ar/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + عناصر التحكم + الافتراضي (%1$s) + %1$s: تم تغيير %2$d + حفظ التغييرات لـ + تغييرات اللعبة الواحدة تُضاف فوق ملفها الشخصي. + كل الألعاب + الأزرار وعصا التحكم + تخطيط الشاشة + استخدام عناصر تحكم الملف الشخصي + يزيل ما غيّرته %1$s + كل إعدادات وحدة التحكم + عناصر التحكم باللمس + النوع + الإظهار + الحفظ لـ %1$s + المس عنصر تحكم أو اضغطه على وحدة التحكم. + اضغط زرًا + اضغط زرًا على وحدة التحكم… + أزرار الجهاز والمفاتيح الإضافية + عناصر تحكم أخرى + العودة إلى الملف الشخصي: %1$s + تكرار + الشبكة + دقيقة + واسعة + ألعاب لها عناصر تحكم خاصة + غيّر عناصر تحكم اللعبة من القائمة أثناء تشغيلها. + الافتراضي لـ + كلا الوضعين + لا شيء + مثبّت في %1$d ألعاب + الخاصة بي + المجتمع + تخطيطات شاركها لاعبو Winlator. ترسل أزرارها مفاتيح لوحة المفاتيح والماوس. + تعذّر تحميل التخطيطات المشتركة. تحقق من الاتصال وحاول مرة أخرى. + معاينة + استخدام + جارٍ التحميل… + diff --git a/app/src/main/res/values-b+es+419/input_flow_strings.xml b/app/src/main/res/values-b+es+419/input_flow_strings.xml new file mode 100644 index 0000000000..3efc80660f --- /dev/null +++ b/app/src/main/res/values-b+es+419/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Controles + Predeterminado (%1$s) + %1$s: %2$d cambiados + Guardar cambios para + Los cambios de un juego se aplican sobre su perfil. + Todos los juegos + Botones y sticks + Diseño en pantalla + Usar los controles del perfil + Descarta lo que cambió %1$s + Todos los ajustes del control + Controles táctiles + Tipo + Mostrar + Guardando para %1$s + Toca un control o presiónalo en tu control. + Presionar un botón + Presiona un botón de tu control… + Botones del dispositivo y teclas extra + Otros controles + Volver al perfil: %1$s + Duplicar + Cuadrícula + Fina + Gruesa + Juegos con controles propios + Cambia los controles de un juego desde el menú mientras se ejecuta. + Predeterminado para + Ambos modos + Ninguno + Fijado por %1$d juegos + Míos + Comunidad + Diseños compartidos por jugadores de Winlator. Sus botones envían teclas de teclado y mouse. + No se pudieron cargar los diseños compartidos. Revisa la conexión e inténtalo de nuevo. + Vista previa + Usar + Cargando… + diff --git a/app/src/main/res/values-bg/input_flow_strings.xml b/app/src/main/res/values-bg/input_flow_strings.xml new file mode 100644 index 0000000000..effa82fc34 --- /dev/null +++ b/app/src/main/res/values-bg/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Управление + По подразбиране (%1$s) + %1$s: променени %2$d + Запазване на промените за + Промените за една игра се добавят върху профила ѝ. + Всички игри + Бутони и стикове + Екранна подредба + Използване на управлението от профила + Премахва промененото за %1$s + Всички настройки на контролера + Сензорно управление + Тип + Показване + Запазване за %1$s + Докоснете контрола или го натиснете на контролера. + Натиснете бутон + Натиснете бутон на контролера… + Бутони на устройството и допълнителни клавиши + Други контроли + Обратно към профила: %1$s + Дублиране + Мрежа + Фина + Едра + Игри със собствено управление + Променете управлението на игра от менюто, докато тя работи. + По подразбиране за + И двата режима + Нито един + Закачен от %1$d игри + Мои + Общност + Подредби, споделени от играчи на Winlator. Бутоните им изпращат клавиши от клавиатура и мишка. + Споделените подредби не можаха да се заредят. Проверете връзката и опитайте отново. + Преглед + Използване + Зарежда се… + diff --git a/app/src/main/res/values-cs/input_flow_strings.xml b/app/src/main/res/values-cs/input_flow_strings.xml new file mode 100644 index 0000000000..583ab6660b --- /dev/null +++ b/app/src/main/res/values-cs/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Ovládání + Výchozí (%1$s) + %1$s: změněno %2$d + Ukládat změny pro + Změny pro jednu hru se přidávají k jejímu profilu. + Všechny hry + Tlačítka a páčky + Rozložení na obrazovce + Použít ovládání z profilu + Zahodí, co se pro %1$s změnilo + Všechna nastavení ovladače + Dotykové ovládání + Typ + Zobrazit + Ukládání pro %1$s + Klepněte na ovládací prvek nebo ho stiskněte na ovladači. + Stisknout tlačítko + Stiskněte tlačítko na ovladači… + Tlačítka zařízení a další klávesy + Další ovládací prvky + Zpět na profil: %1$s + Duplikovat + Mřížka + Jemná + Hrubá + Hry s vlastním ovládáním + Ovládání hry změníte v nabídce, když hra běží. + Výchozí pro + Oba režimy + Žádný + Připnuto hrami: %1$d + Moje + Komunita + Rozložení sdílená hráči Winlatoru. Jejich tlačítka posílají klávesy klávesnice a myši. + Sdílená rozložení se nepodařilo načíst. Zkontrolujte připojení a zkuste to znovu. + Náhled + Použít + Načítání… + diff --git a/app/src/main/res/values-da/input_flow_strings.xml b/app/src/main/res/values-da/input_flow_strings.xml new file mode 100644 index 0000000000..701a0ba0cc --- /dev/null +++ b/app/src/main/res/values-da/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Styring + Standard (%1$s) + %1$s: %2$d ændret + Gem ændringer for + Ændringer for ét spil lægges oven på dets profil. + Alle spil + Knapper og pinde + Skærmlayout + Brug profilens styring + Fjerner det, %1$s har ændret + Alle controllerindstillinger + Touchstyring + Type + Vis + Gemmer for %1$s + Tryk på en kontrol, eller tryk på den på din controller. + Tryk på en knap + Tryk på en knap på din controller… + Enhedsknapper og ekstra taster + Andre kontroller + Tilbage til profil: %1$s + Dupliker + Gitter + Fint + Groft + Spil med egen styring + Skift et spils styring i menuen, mens det kører. + Standard for + Begge tilstande + Ingen + Fastgjort af %1$d spil + Mine + Fællesskab + Layouts delt af Winlator-spillere. Deres knapper sender tastatur- og musetaster. + Kunne ikke indlæse de delte layouts. Tjek forbindelsen, og prøv igen. + Forhåndsvis + Brug + Indlæser… + diff --git a/app/src/main/res/values-de/input_flow_strings.xml b/app/src/main/res/values-de/input_flow_strings.xml new file mode 100644 index 0000000000..f673017d61 --- /dev/null +++ b/app/src/main/res/values-de/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Steuerung + Standard (%1$s) + %1$s: %2$d geändert + Änderungen speichern für + Änderungen für ein Spiel liegen über seinem Profil. + Alle Spiele + Tasten und Sticks + Bildschirm-Layout + Steuerung des Profils verwenden + Verwirft, was %1$s geändert hat + Alle Controller-Einstellungen + Touch-Steuerung + Art + Anzeigen + Speichern für %1$s + Tippe auf ein Steuerelement oder drücke es auf deinem Controller. + Taste drücken + Drücke eine Taste auf deinem Controller… + Gerätetasten und Zusatztasten + Weitere Steuerelemente + Zurück zum Profil: %1$s + Duplizieren + Raster + Fein + Grob + Spiele mit eigener Steuerung + Ändere die Steuerung eines Spiels im Menü, während es läuft. + Standard für + Beide Modi + Keiner + Von %1$d Spielen festgelegt + Meine + Community + Von Winlator-Spielern geteilte Layouts. Ihre Tasten senden Tastatur- und Maustasten. + Die geteilten Layouts konnten nicht geladen werden. Prüfe die Verbindung und versuche es erneut. + Vorschau + Verwenden + Wird geladen… + diff --git a/app/src/main/res/values-el/input_flow_strings.xml b/app/src/main/res/values-el/input_flow_strings.xml new file mode 100644 index 0000000000..d28898847f --- /dev/null +++ b/app/src/main/res/values-el/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Χειριστήρια + Προεπιλογή (%1$s) + %1$s: %2$d αλλαγές + Αποθήκευση αλλαγών για + Οι αλλαγές για ένα παιχνίδι μπαίνουν πάνω από το προφίλ του. + Όλα τα παιχνίδια + Κουμπιά και μοχλοί + Διάταξη στην οθόνη + Χρήση των χειριστηρίων του προφίλ + Καταργεί ό,τι άλλαξε το %1$s + Όλες οι ρυθμίσεις χειριστηρίου + Χειριστήρια αφής + Τύπος + Εμφάνιση + Αποθήκευση για %1$s + Πατήστε ένα στοιχείο ή πατήστε το στο χειριστήριό σας. + Πατήστε ένα κουμπί + Πατήστε ένα κουμπί στο χειριστήριό σας… + Κουμπιά συσκευής και επιπλέον πλήκτρα + Άλλα στοιχεία + Πίσω στο προφίλ: %1$s + Αντίγραφο + Πλέγμα + Πυκνό + Αραιό + Παιχνίδια με δικά τους χειριστήρια + Αλλάξτε τα χειριστήρια ενός παιχνιδιού από το μενού όσο τρέχει. + Προεπιλογή για + Και τις δύο λειτουργίες + Καμία + Καρφιτσωμένο από %1$d παιχνίδια + Δικές μου + Κοινότητα + Διατάξεις που μοιράστηκαν παίκτες του Winlator. Τα κουμπιά τους στέλνουν πλήκτρα πληκτρολογίου και ποντικιού. + Δεν ήταν δυνατή η φόρτωση των κοινόχρηστων διατάξεων. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά. + Προεπισκόπηση + Χρήση + Φόρτωση… + diff --git a/app/src/main/res/values-es/input_flow_strings.xml b/app/src/main/res/values-es/input_flow_strings.xml new file mode 100644 index 0000000000..d241831f8b --- /dev/null +++ b/app/src/main/res/values-es/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Controles + Predeterminado (%1$s) + %1$s: %2$d cambiados + Guardar cambios para + Los cambios de un juego se aplican sobre su perfil. + Todos los juegos + Botones y sticks + Diseño en pantalla + Usar los controles del perfil + Descarta lo que cambió %1$s + Todos los ajustes del mando + Controles táctiles + Tipo + Mostrar + Guardando para %1$s + Toca un control o púlsalo en tu mando. + Pulsar un botón + Pulsa un botón de tu mando… + Botones del dispositivo y teclas extra + Otros controles + Volver al perfil: %1$s + Duplicar + Cuadrícula + Fina + Gruesa + Juegos con controles propios + Cambia los controles de un juego desde el menú mientras se ejecuta. + Predeterminado para + Ambos modos + Ninguno + Fijado por %1$d juegos + Míos + Comunidad + Diseños compartidos por jugadores de Winlator. Sus botones envían teclas de teclado y ratón. + No se pudieron cargar los diseños compartidos. Comprueba la conexión e inténtalo de nuevo. + Vista previa + Usar + Cargando… + diff --git a/app/src/main/res/values-fi/input_flow_strings.xml b/app/src/main/res/values-fi/input_flow_strings.xml new file mode 100644 index 0000000000..04f0b66885 --- /dev/null +++ b/app/src/main/res/values-fi/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Ohjaimet + Oletus (%1$s) + %1$s: %2$d muutettu + Tallenna muutokset + Yhden pelin muutokset lisätään sen profiilin päälle. + Kaikki pelit + Painikkeet ja tikut + Näytön asettelu + Käytä profiilin ohjaimia + Poistaa pelin %1$s muutokset + Kaikki ohjainasetukset + Kosketusohjaimet + Tyyppi + Näytä + Tallennetaan: %1$s + Napauta ohjainta tai paina sitä ohjaimessasi. + Paina painiketta + Paina ohjaimesi painiketta… + Laitteen painikkeet ja lisänäppäimet + Muut ohjaimet + Takaisin profiiliin: %1$s + Monista + Ruudukko + Tiheä + Harva + Pelit omilla ohjaimilla + Muuta pelin ohjaimia valikosta pelin ollessa käynnissä. + Oletus tilalle + Molemmat tilat + Ei mikään + Kiinnittänyt %1$d peliä + Omat + Yhteisö + Winlator-pelaajien jakamat asettelut. Niiden painikkeet lähettävät näppäimistön ja hiiren painalluksia. + Jaettuja asetteluja ei voitu ladata. Tarkista yhteys ja yritä uudelleen. + Esikatselu + Käytä + Ladataan… + diff --git a/app/src/main/res/values-fr/input_flow_strings.xml b/app/src/main/res/values-fr/input_flow_strings.xml new file mode 100644 index 0000000000..4c5d7172c0 --- /dev/null +++ b/app/src/main/res/values-fr/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Commandes + Par défaut (%1$s) + %1$s : %2$d modifiés + Enregistrer les changements pour + Les changements pour un jeu s\'ajoutent à son profil. + Tous les jeux + Boutons et sticks + Disposition à l\'écran + Utiliser les commandes du profil + Annule ce que %1$s a modifié + Tous les réglages de la manette + Commandes tactiles + Type + Afficher + Enregistrement pour %1$s + Touchez une commande ou appuyez dessus sur votre manette. + Appuyer sur un bouton + Appuyez sur un bouton de votre manette… + Boutons de l\'appareil et touches supplémentaires + Autres commandes + Revenir au profil : %1$s + Dupliquer + Grille + Fine + Large + Jeux avec leurs propres commandes + Modifiez les commandes d\'un jeu depuis le menu pendant qu\'il tourne. + Par défaut pour + Les deux modes + Aucun + Épinglé par %1$d jeux + Les miennes + Communauté + Dispositions partagées par des joueurs de Winlator. Leurs boutons envoient des touches de clavier et de souris. + Impossible de charger les dispositions partagées. Vérifiez la connexion et réessayez. + Aperçu + Utiliser + Chargement… + diff --git a/app/src/main/res/values-hi/input_flow_strings.xml b/app/src/main/res/values-hi/input_flow_strings.xml new file mode 100644 index 0000000000..d85be9d102 --- /dev/null +++ b/app/src/main/res/values-hi/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + कंट्रोल + डिफ़ॉल्ट (%1$s) + %1$s: %2$d बदले गए + बदलाव इसके लिए सहेजें + किसी एक गेम के बदलाव उसकी प्रोफ़ाइल के ऊपर लागू होते हैं। + सभी गेम + बटन और स्टिक + स्क्रीन लेआउट + प्रोफ़ाइल के कंट्रोल इस्तेमाल करें + %1$s में किए बदलाव हटाता है + कंट्रोलर की सभी सेटिंग + टच कंट्रोल + प्रकार + दिखाएँ + %1$s के लिए सहेजा जा रहा है + किसी कंट्रोल पर टैप करें या उसे अपने कंट्रोलर पर दबाएँ। + बटन दबाएँ + अपने कंट्रोलर पर कोई बटन दबाएँ… + डिवाइस बटन और अतिरिक्त कुंजियाँ + अन्य कंट्रोल + प्रोफ़ाइल पर वापस: %1$s + डुप्लिकेट + ग्रिड + बारीक + मोटा + अपने कंट्रोल वाले गेम + गेम चलते समय मेन्यू से उसके कंट्रोल बदलें। + इसके लिए डिफ़ॉल्ट + दोनों मोड + कोई नहीं + %1$d गेम में पिन + मेरे + कम्युनिटी + Winlator खिलाड़ियों के साझा किए लेआउट। इनके बटन कीबोर्ड और माउस कुंजियाँ भेजते हैं। + साझा लेआउट लोड नहीं हो सके। कनेक्शन जाँचें और फिर से कोशिश करें। + प्रीव्यू + इस्तेमाल करें + लोड हो रहा है… + diff --git a/app/src/main/res/values-hu/input_flow_strings.xml b/app/src/main/res/values-hu/input_flow_strings.xml new file mode 100644 index 0000000000..125edf1337 --- /dev/null +++ b/app/src/main/res/values-hu/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Irányítás + Alapértelmezett (%1$s) + %1$s: %2$d módosítva + Változások mentése ehhez: + Egy játék változásai a profilja fölé kerülnek. + Összes játék + Gombok és karok + Képernyős elrendezés + A profil irányításának használata + Elveti, amit a(z) %1$s módosított + Minden kontrollerbeállítás + Érintéses irányítás + Típus + Megjelenítés + Mentés ehhez: %1$s + Koppints egy vezérlőre, vagy nyomd meg a kontrolleren. + Gomb lenyomása + Nyomj meg egy gombot a kontrolleren… + Eszközgombok és extra billentyűk + Egyéb vezérlők + Vissza a profilhoz: %1$s + Duplikálás + Rács + Sűrű + Ritka + Saját irányítású játékok + A játék irányítását futás közben a menüben módosíthatod. + Alapértelmezett ehhez + Mindkét mód + Egyik sem + %1$d játék rögzítette + Sajátok + Közösség + Winlator-játékosok által megosztott elrendezések. A gombjaik billentyűzet- és egérgombokat küldenek. + Nem sikerült betölteni a megosztott elrendezéseket. Ellenőrizd a kapcsolatot, és próbáld újra. + Előnézet + Használat + Betöltés… + diff --git a/app/src/main/res/values-in/input_flow_strings.xml b/app/src/main/res/values-in/input_flow_strings.xml new file mode 100644 index 0000000000..d950775b6d --- /dev/null +++ b/app/src/main/res/values-in/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Kontrol + Default (%1$s) + %1$s: %2$d diubah + Simpan perubahan untuk + Perubahan untuk satu game ditumpuk di atas profilnya. + Semua game + Tombol dan stik + Tata letak layar + Gunakan kontrol profil + Menghapus perubahan %1$s + Semua setelan controller + Kontrol sentuh + Jenis + Tampilkan + Menyimpan untuk %1$s + Ketuk kontrol, atau tekan di controller Anda. + Tekan tombol + Tekan tombol di controller Anda… + Tombol perangkat dan tombol tambahan + Kontrol lain + Kembali ke profil: %1$s + Duplikat + Kisi + Rapat + Renggang + Game dengan kontrol sendiri + Ubah kontrol game dari menu saat game berjalan. + Default untuk + Kedua mode + Tidak ada + Disematkan oleh %1$d game + Milik saya + Komunitas + Tata letak yang dibagikan pemain Winlator. Tombolnya mengirim tombol keyboard dan mouse. + Tidak dapat memuat tata letak bersama. Periksa koneksi lalu coba lagi. + Pratinjau + Gunakan + Memuat… + diff --git a/app/src/main/res/values-it/input_flow_strings.xml b/app/src/main/res/values-it/input_flow_strings.xml new file mode 100644 index 0000000000..a4e4e9ae90 --- /dev/null +++ b/app/src/main/res/values-it/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Controlli + Predefinito (%1$s) + %1$s: %2$d modificati + Salva le modifiche per + Le modifiche per un gioco si aggiungono al suo profilo. + Tutti i giochi + Pulsanti e levette + Layout su schermo + Usa i controlli del profilo + Annulla ciò che %1$s ha modificato + Tutte le impostazioni del controller + Controlli touch + Tipo + Mostra + Salvataggio per %1$s + Tocca un controllo o premilo sul controller. + Premi un pulsante + Premi un pulsante sul controller… + Pulsanti del dispositivo e tasti extra + Altri controlli + Torna al profilo: %1$s + Duplica + Griglia + Fine + Larga + Giochi con controlli propri + Cambia i controlli di un gioco dal menu mentre è in esecuzione. + Predefinito per + Entrambe le modalità + Nessuna + Fissato da %1$d giochi + Miei + Community + Layout condivisi dai giocatori di Winlator. I loro pulsanti inviano tasti di tastiera e mouse. + Impossibile caricare i layout condivisi. Controlla la connessione e riprova. + Anteprima + Usa + Caricamento… + diff --git a/app/src/main/res/values-ja/input_flow_strings.xml b/app/src/main/res/values-ja/input_flow_strings.xml new file mode 100644 index 0000000000..ff8c3fd0cb --- /dev/null +++ b/app/src/main/res/values-ja/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + 操作 + デフォルト (%1$s) + %1$s: %2$d 件変更 + 変更の保存先 + ゲームごとの変更はそのプロファイルの上に重ねて適用されます。 + すべてのゲーム + ボタンとスティック + 画面上のレイアウト + プロファイルの操作を使う + %1$s の変更を取り消します + すべてのコントローラー設定 + タッチ操作 + 種類 + 表示 + %1$s に保存中 + 操作をタップするか、コントローラーで押してください。 + ボタンを押す + コントローラーのボタンを押してください… + デバイスのボタンと追加キー + その他の操作 + プロファイルに戻す: %1$s + 複製 + グリッド + 細かい + 粗い + 専用の操作があるゲーム + ゲームの実行中にメニューから操作を変更できます。 + デフォルトにするモード + 両方のモード + なし + %1$d 本のゲームで固定 + 自分 + コミュニティ + Winlator プレイヤーが共有したレイアウトです。ボタンはキーボードとマウスのキーを送ります。 + 共有レイアウトを読み込めませんでした。接続を確認してもう一度お試しください。 + プレビュー + 使う + 読み込み中… + diff --git a/app/src/main/res/values-ko/input_flow_strings.xml b/app/src/main/res/values-ko/input_flow_strings.xml new file mode 100644 index 0000000000..de9c998b5b --- /dev/null +++ b/app/src/main/res/values-ko/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + 컨트롤 + 기본값 (%1$s) + %1$s: %2$d개 변경됨 + 변경 사항 저장 대상 + 한 게임의 변경 사항은 해당 프로필 위에 적용됩니다. + 모든 게임 + 버튼 및 스틱 + 화면 레이아웃 + 프로필의 컨트롤 사용 + %1$s에서 변경한 내용을 지웁니다 + 모든 컨트롤러 설정 + 터치 컨트롤 + 유형 + 표시 + %1$s에 저장 중 + 컨트롤을 탭하거나 컨트롤러에서 누르세요. + 버튼 누르기 + 컨트롤러의 버튼을 누르세요… + 기기 버튼 및 추가 키 + 기타 컨트롤 + 프로필로 되돌리기: %1$s + 복제 + 격자 + 촘촘하게 + 넓게 + 자체 컨트롤이 있는 게임 + 게임 실행 중에 메뉴에서 게임의 컨트롤을 바꾸세요. + 기본값 모드 + 두 모드 모두 + 없음 + 게임 %1$d개에 고정됨 + 내 레이아웃 + 커뮤니티 + Winlator 플레이어들이 공유한 레이아웃입니다. 버튼은 키보드와 마우스 키를 보냅니다. + 공유 레이아웃을 불러올 수 없습니다. 연결을 확인하고 다시 시도하세요. + 미리 보기 + 사용 + 불러오는 중… + diff --git a/app/src/main/res/values-ms/input_flow_strings.xml b/app/src/main/res/values-ms/input_flow_strings.xml new file mode 100644 index 0000000000..3aeec92f7e --- /dev/null +++ b/app/src/main/res/values-ms/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Kawalan + Lalai (%1$s) + %1$s: %2$d diubah + Simpan perubahan untuk + Perubahan untuk satu permainan ditambah di atas profilnya. + Semua permainan + Butang dan kayu bedik + Susun atur skrin + Guna kawalan profil + Membuang perubahan %1$s + Semua tetapan pengawal + Kawalan sentuh + Jenis + Tunjukkan + Menyimpan untuk %1$s + Ketik kawalan, atau tekan pada pengawal anda. + Tekan butang + Tekan butang pada pengawal anda… + Butang peranti dan kekunci tambahan + Kawalan lain + Kembali ke profil: %1$s + Pendua + Grid + Halus + Kasar + Permainan dengan kawalan sendiri + Tukar kawalan permainan dari menu semasa ia berjalan. + Lalai untuk + Kedua-dua mod + Tiada + Dipin oleh %1$d permainan + Saya + Komuniti + Susun atur yang dikongsi pemain Winlator. Butangnya menghantar kekunci papan kekunci dan tetikus. + Tidak dapat memuatkan susun atur yang dikongsi. Semak sambungan dan cuba lagi. + Pratonton + Guna + Memuatkan… + diff --git a/app/src/main/res/values-nb/input_flow_strings.xml b/app/src/main/res/values-nb/input_flow_strings.xml new file mode 100644 index 0000000000..dae30d4dd8 --- /dev/null +++ b/app/src/main/res/values-nb/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Kontroller + Standard (%1$s) + %1$s: %2$d endret + Lagre endringer for + Endringer for ett spill legges oppå profilen til spillet. + Alle spill + Knapper og stikker + Skjermoppsett + Bruk profilens kontroller + Fjerner det %1$s har endret + Alle kontrollerinnstillinger + Berøringskontroller + Type + Vis + Lagrer for %1$s + Trykk på en kontroll, eller trykk den på kontrolleren. + Trykk på en knapp + Trykk på en knapp på kontrolleren… + Enhetsknapper og ekstra taster + Andre kontroller + Tilbake til profilen: %1$s + Dupliser + Rutenett + Fint + Grovt + Spill med egne kontroller + Endre kontrollene til et spill i menyen mens det kjører. + Standard for + Begge moduser + Ingen + Festet av %1$d spill + Mine + Fellesskap + Oppsett delt av Winlator-spillere. Knappene sender tastatur- og musetaster. + Kunne ikke laste inn de delte oppsettene. Sjekk tilkoblingen og prøv igjen. + Forhåndsvis + Bruk + Laster inn… + diff --git a/app/src/main/res/values-nl/input_flow_strings.xml b/app/src/main/res/values-nl/input_flow_strings.xml new file mode 100644 index 0000000000..f1bdd6fec8 --- /dev/null +++ b/app/src/main/res/values-nl/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Besturing + Standaard (%1$s) + %1$s: %2$d gewijzigd + Wijzigingen opslaan voor + Wijzigingen voor één game komen bovenop zijn profiel. + Alle games + Knoppen en sticks + Schermindeling + Besturing van het profiel gebruiken + Verwijdert wat %1$s heeft gewijzigd + Alle controllerinstellingen + Aanraakbesturing + Soort + Tonen + Opslaan voor %1$s + Tik op een bedieningselement of druk erop op je controller. + Druk op een knop + Druk op een knop van je controller… + Apparaatknoppen en extra toetsen + Andere bediening + Terug naar profiel: %1$s + Dupliceren + Raster + Fijn + Grof + Games met eigen besturing + Wijzig de besturing van een game via het menu terwijl hij draait. + Standaard voor + Beide modi + Geen + Vastgezet door %1$d games + Van mij + Community + Indelingen gedeeld door Winlator-spelers. Hun knoppen sturen toetsenbord- en muistoetsen. + Kan de gedeelde indelingen niet laden. Controleer de verbinding en probeer het opnieuw. + Voorbeeld + Gebruiken + Laden… + diff --git a/app/src/main/res/values-pl/input_flow_strings.xml b/app/src/main/res/values-pl/input_flow_strings.xml new file mode 100644 index 0000000000..9d7d041255 --- /dev/null +++ b/app/src/main/res/values-pl/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Sterowanie + Domyślny (%1$s) + %1$s: zmieniono %2$d + Zapisuj zmiany dla + Zmiany dla jednej gry nakładają się na jej profil. + Wszystkich gier + Przyciski i gałki + Układ na ekranie + Użyj sterowania z profilu + Odrzuca to, co zmieniono dla %1$s + Wszystkie ustawienia kontrolera + Sterowanie dotykowe + Rodzaj + Pokazuj + Zapisywanie dla %1$s + Dotknij elementu sterowania lub naciśnij go na kontrolerze. + Naciśnij przycisk + Naciśnij przycisk na kontrolerze… + Przyciski urządzenia i dodatkowe klawisze + Inne elementy sterowania + Wróć do profilu: %1$s + Duplikuj + Siatka + Drobna + Gruba + Gry z własnym sterowaniem + Zmień sterowanie gry z menu, gdy jest uruchomiona. + Domyślny dla + Obu trybów + Żadnego + Przypięty przez gry: %1$d + Moje + Społeczność + Układy udostępnione przez graczy Winlatora. Ich przyciski wysyłają klawisze klawiatury i myszy. + Nie udało się wczytać udostępnionych układów. Sprawdź połączenie i spróbuj ponownie. + Podgląd + Użyj + Wczytywanie… + diff --git a/app/src/main/res/values-pt-rPT/input_flow_strings.xml b/app/src/main/res/values-pt-rPT/input_flow_strings.xml new file mode 100644 index 0000000000..5a799d9684 --- /dev/null +++ b/app/src/main/res/values-pt-rPT/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Controlos + Predefinido (%1$s) + %1$s: %2$d alterados + Guardar alterações para + As alterações de um jogo ficam por cima do respetivo perfil. + Todos os jogos + Botões e manípulos + Disposição no ecrã + Usar os controlos do perfil + Descarta o que %1$s alterou + Todas as definições do comando + Controlos táteis + Tipo + Mostrar + A guardar para %1$s + Toque num controlo ou prima-o no seu comando. + Premir um botão + Prima um botão no seu comando… + Botões do dispositivo e teclas extra + Outros controlos + Voltar ao perfil: %1$s + Duplicar + Grelha + Fina + Larga + Jogos com controlos próprios + Altere os controlos de um jogo no menu enquanto está a correr. + Predefinido para + Ambos os modos + Nenhum + Fixado por %1$d jogos + Os meus + Comunidade + Disposições partilhadas por jogadores do Winlator. Os botões enviam teclas de teclado e rato. + Não foi possível carregar as disposições partilhadas. Verifique a ligação e tente novamente. + Pré-visualizar + Usar + A carregar… + diff --git a/app/src/main/res/values-pt/input_flow_strings.xml b/app/src/main/res/values-pt/input_flow_strings.xml new file mode 100644 index 0000000000..9d90f8c67e --- /dev/null +++ b/app/src/main/res/values-pt/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Controles + Padrão (%1$s) + %1$s: %2$d alterados + Salvar alterações para + As alterações de um jogo ficam por cima do perfil dele. + Todos os jogos + Botões e analógicos + Layout na tela + Usar os controles do perfil + Descarta o que %1$s alterou + Todas as configurações do controle + Controles por toque + Tipo + Mostrar + Salvando para %1$s + Toque em um controle ou pressione-o no seu controle. + Pressionar um botão + Pressione um botão no seu controle… + Botões do aparelho e teclas extras + Outros controles + Voltar ao perfil: %1$s + Duplicar + Grade + Fina + Larga + Jogos com controles próprios + Altere os controles de um jogo pelo menu enquanto ele roda. + Padrão para + Ambos os modos + Nenhum + Fixado por %1$d jogos + Meus + Comunidade + Layouts compartilhados por jogadores do Winlator. Os botões enviam teclas de teclado e mouse. + Não foi possível carregar os layouts compartilhados. Verifique a conexão e tente de novo. + Prévia + Usar + Carregando… + diff --git a/app/src/main/res/values-ro/input_flow_strings.xml b/app/src/main/res/values-ro/input_flow_strings.xml new file mode 100644 index 0000000000..9a9b6cbeae --- /dev/null +++ b/app/src/main/res/values-ro/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Comenzi + Implicit (%1$s) + %1$s: %2$d modificate + Salvează modificările pentru + Modificările pentru un joc se adaugă peste profilul lui. + Toate jocurile + Butoane și stick-uri + Aranjament pe ecran + Folosește comenzile profilului + Renunță la ce a modificat %1$s + Toate setările controlerului + Comenzi tactile + Tip + Afișare + Se salvează pentru %1$s + Atinge o comandă sau apas-o pe controler. + Apasă un buton + Apasă un buton de pe controler… + Butoanele dispozitivului și taste suplimentare + Alte comenzi + Înapoi la profil: %1$s + Duplică + Grilă + Fină + Rară + Jocuri cu comenzi proprii + Schimbă comenzile unui joc din meniu cât timp rulează. + Implicit pentru + Ambele moduri + Niciunul + Fixat de %1$d jocuri + Ale mele + Comunitate + Aranjamente partajate de jucătorii Winlator. Butoanele lor trimit taste de tastatură și mouse. + Aranjamentele partajate nu au putut fi încărcate. Verifică conexiunea și încearcă din nou. + Previzualizare + Folosește + Se încarcă… + diff --git a/app/src/main/res/values-ru/input_flow_strings.xml b/app/src/main/res/values-ru/input_flow_strings.xml new file mode 100644 index 0000000000..4e239a487e --- /dev/null +++ b/app/src/main/res/values-ru/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Управление + По умолчанию (%1$s) + %1$s: изменено %2$d + Сохранять изменения для + Изменения для одной игры накладываются на её профиль. + Всех игр + Кнопки и стики + Экранная раскладка + Использовать управление профиля + Сбрасывает изменения для %1$s + Все настройки контроллера + Сенсорное управление + Тип + Показывать + Сохранение для %1$s + Коснитесь элемента или нажмите его на контроллере. + Нажать кнопку + Нажмите кнопку на контроллере… + Кнопки устройства и дополнительные клавиши + Другие элементы + Вернуть как в профиле: %1$s + Дублировать + Сетка + Мелкая + Крупная + Игры со своим управлением + Меняйте управление игры через меню, пока она запущена. + По умолчанию для + Обоих режимов + Ни для какого + Закреплён в играх: %1$d + Мои + Сообщество + Раскладки от игроков Winlator. Их кнопки отправляют клавиши клавиатуры и мыши. + Не удалось загрузить общие раскладки. Проверьте подключение и повторите попытку. + Просмотр + Использовать + Загрузка… + diff --git a/app/src/main/res/values-sv/input_flow_strings.xml b/app/src/main/res/values-sv/input_flow_strings.xml new file mode 100644 index 0000000000..6a4b85f662 --- /dev/null +++ b/app/src/main/res/values-sv/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Kontroller + Standard (%1$s) + %1$s: %2$d ändrade + Spara ändringar för + Ändringar för ett spel läggs ovanpå dess profil. + Alla spel + Knappar och spakar + Skärmlayout + Använd profilens kontroller + Tar bort det som %1$s ändrat + Alla handkontrollsinställningar + Pekkontroller + Typ + Visa + Sparar för %1$s + Tryck på en kontroll eller tryck på den på handkontrollen. + Tryck på en knapp + Tryck på en knapp på handkontrollen… + Enhetsknappar och extra tangenter + Andra kontroller + Tillbaka till profilen: %1$s + Duplicera + Rutnät + Fint + Grovt + Spel med egna kontroller + Ändra ett spels kontroller i menyn medan det körs. + Standard för + Båda lägena + Inget + Fäst av %1$d spel + Mina + Gemenskap + Layouter som Winlator-spelare delat. Deras knappar skickar tangentbords- och mustangenter. + Kunde inte läsa in de delade layouterna. Kontrollera anslutningen och försök igen. + Förhandsgranska + Använd + Läser in… + diff --git a/app/src/main/res/values-th/input_flow_strings.xml b/app/src/main/res/values-th/input_flow_strings.xml new file mode 100644 index 0000000000..db27443bc6 --- /dev/null +++ b/app/src/main/res/values-th/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + การควบคุม + ค่าเริ่มต้น (%1$s) + %1$s: เปลี่ยน %2$d รายการ + บันทึกการเปลี่ยนแปลงสำหรับ + การเปลี่ยนแปลงของเกมหนึ่งจะซ้อนทับโปรไฟล์ของเกมนั้น + ทุกเกม + ปุ่มและแท่งควบคุม + เลย์เอาต์บนหน้าจอ + ใช้การควบคุมของโปรไฟล์ + ลบสิ่งที่ %1$s เปลี่ยนไว้ + การตั้งค่าคอนโทรลเลอร์ทั้งหมด + การควบคุมแบบสัมผัส + ประเภท + แสดง + กำลังบันทึกสำหรับ %1$s + แตะตัวควบคุม หรือกดบนคอนโทรลเลอร์ของคุณ + กดปุ่ม + กดปุ่มบนคอนโทรลเลอร์ของคุณ… + ปุ่มของอุปกรณ์และปุ่มเพิ่มเติม + ตัวควบคุมอื่น + กลับไปใช้โปรไฟล์: %1$s + ทำสำเนา + ตาราง + ละเอียด + หยาบ + เกมที่มีการควบคุมของตัวเอง + เปลี่ยนการควบคุมของเกมจากเมนูขณะเกมกำลังทำงาน + ค่าเริ่มต้นสำหรับ + ทั้งสองโหมด + ไม่มี + ปักหมุดโดย %1$d เกม + ของฉัน + ชุมชน + เลย์เอาต์ที่ผู้เล่น Winlator แชร์ไว้ ปุ่มจะส่งปุ่มคีย์บอร์ดและเมาส์ + โหลดเลย์เอาต์ที่แชร์ไม่ได้ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง + ดูตัวอย่าง + ใช้ + กำลังโหลด… + diff --git a/app/src/main/res/values-tr/input_flow_strings.xml b/app/src/main/res/values-tr/input_flow_strings.xml new file mode 100644 index 0000000000..9f7afcd14d --- /dev/null +++ b/app/src/main/res/values-tr/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Kontroller + Varsayılan (%1$s) + %1$s: %2$d değişti + Değişiklikleri kaydet: + Bir oyunun değişiklikleri profilinin üstüne eklenir. + Tüm oyunlar + Düğmeler ve çubuklar + Ekran düzeni + Profilin kontrollerini kullan + %1$s için yapılan değişiklikleri kaldırır + Tüm kumanda ayarları + Dokunmatik kontroller + Tür + Göster + %1$s için kaydediliyor + Bir kontrole dokunun veya kumandanızda basın. + Bir düğmeye basın + Kumandanızda bir düğmeye basın… + Cihaz düğmeleri ve ek tuşlar + Diğer kontroller + Profile dön: %1$s + Çoğalt + Izgara + Sık + Seyrek + Kendi kontrolleri olan oyunlar + Bir oyunun kontrollerini oyun çalışırken menüden değiştirin. + Varsayılan olduğu mod + İki mod da + Hiçbiri + %1$d oyun sabitledi + Benimkiler + Topluluk + Winlator oyuncularının paylaştığı düzenler. Düğmeleri klavye ve fare tuşları gönderir. + Paylaşılan düzenler yüklenemedi. Bağlantıyı kontrol edip tekrar deneyin. + Önizle + Kullan + Yükleniyor… + diff --git a/app/src/main/res/values-uk/input_flow_strings.xml b/app/src/main/res/values-uk/input_flow_strings.xml new file mode 100644 index 0000000000..631904e3be --- /dev/null +++ b/app/src/main/res/values-uk/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Керування + Типовий (%1$s) + %1$s: змінено %2$d + Зберігати зміни для + Зміни для однієї гри накладаються на її профіль. + Усіх ігор + Кнопки та стіки + Екранне розташування + Використати керування профілю + Скидає зміни для %1$s + Усі налаштування контролера + Сенсорне керування + Тип + Показувати + Збереження для %1$s + Торкніться елемента або натисніть його на контролері. + Натиснути кнопку + Натисніть кнопку на контролері… + Кнопки пристрою та додаткові клавіші + Інші елементи + Повернути як у профілі: %1$s + Дублювати + Сітка + Дрібна + Велика + Ігри з власним керуванням + Змінюйте керування гри через меню, поки вона запущена. + Типовий для + Обох режимів + Жодного + Закріплено в іграх: %1$d + Мої + Спільнота + Розташування від гравців Winlator. Їхні кнопки надсилають клавіші клавіатури та миші. + Не вдалося завантажити спільні розташування. Перевірте з\'єднання й спробуйте ще раз. + Перегляд + Використати + Завантаження… + diff --git a/app/src/main/res/values-vi/input_flow_strings.xml b/app/src/main/res/values-vi/input_flow_strings.xml new file mode 100644 index 0000000000..a10da2ca2b --- /dev/null +++ b/app/src/main/res/values-vi/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + Điều khiển + Mặc định (%1$s) + %1$s: đã đổi %2$d + Lưu thay đổi cho + Thay đổi cho một trò chơi được đặt chồng lên hồ sơ của nó. + Mọi trò chơi + Nút và cần + Bố cục trên màn hình + Dùng điều khiển của hồ sơ + Bỏ những gì %1$s đã đổi + Mọi cài đặt tay cầm + Điều khiển cảm ứng + Loại + Hiện + Đang lưu cho %1$s + Chạm vào một điều khiển hoặc nhấn nó trên tay cầm. + Nhấn một nút + Nhấn một nút trên tay cầm… + Nút thiết bị và phím bổ sung + Điều khiển khác + Trở về hồ sơ: %1$s + Nhân bản + Lưới + Mịn + Thưa + Trò chơi có điều khiển riêng + Đổi điều khiển của trò chơi từ menu khi nó đang chạy. + Mặc định cho + Cả hai chế độ + Không + Được %1$d trò chơi ghim + Của tôi + Cộng đồng + Bố cục do người chơi Winlator chia sẻ. Các nút gửi phím bàn phím và chuột. + Không tải được bố cục chia sẻ. Kiểm tra kết nối rồi thử lại. + Xem trước + Dùng + Đang tải… + diff --git a/app/src/main/res/values-zh-rCN/input_flow_strings.xml b/app/src/main/res/values-zh-rCN/input_flow_strings.xml new file mode 100644 index 0000000000..eb4ab8ad9b --- /dev/null +++ b/app/src/main/res/values-zh-rCN/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + 控制 + 默认(%1$s) + %1$s:已更改 %2$d 项 + 更改保存到 + 单个游戏的更改叠加在其配置文件之上。 + 所有游戏 + 按键和摇杆 + 屏幕布局 + 使用配置文件的控制 + 移除 %1$s 的更改 + 所有控制器设置 + 触控按键 + 类型 + 显示 + 正在为 %1$s 保存 + 点按一个控件,或在控制器上按下它。 + 按下按钮 + 请按下控制器上的按钮… + 设备按键和额外按键 + 其他控件 + 恢复为配置文件:%1$s + 复制 + 网格 + 细 + 粗 + 有自己控制的游戏 + 游戏运行时可在菜单中更改它的控制。 + 默认用于 + 两种模式 + 无 + 已被 %1$d 个游戏固定 + 我的 + 社区 + Winlator 玩家分享的布局。它们的按钮发送键盘和鼠标按键。 + 无法加载共享布局。请检查网络连接后重试。 + 预览 + 使用 + 正在加载… + diff --git a/app/src/main/res/values-zh-rHK/input_flow_strings.xml b/app/src/main/res/values-zh-rHK/input_flow_strings.xml new file mode 100644 index 0000000000..acbb209fb4 --- /dev/null +++ b/app/src/main/res/values-zh-rHK/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + 控制 + 預設(%1$s) + %1$s:已變更 %2$d 項 + 變更儲存至 + 單一遊戲的變更會疊加在其設定檔之上。 + 所有遊戲 + 按鈕及搖桿 + 螢幕佈局 + 使用設定檔的控制 + 移除 %1$s 的變更 + 所有控制器設定 + 觸控控制 + 類型 + 顯示 + 正在為 %1$s 儲存 + 輕按控制項,或在控制器上按下它。 + 按下按鈕 + 請按下控制器上的按鈕… + 裝置按鈕及額外按鍵 + 其他控制項 + 還原為設定檔:%1$s + 複製 + 格線 + 細 + 粗 + 有自己控制的遊戲 + 遊戲執行時可在選單中變更其控制。 + 預設用於 + 兩種模式 + 無 + 已被 %1$d 個遊戲固定 + 我的 + 社群 + Winlator 玩家分享的佈局。其按鈕會傳送鍵盤及滑鼠按鍵。 + 無法載入共享佈局。請檢查連線後再試。 + 預覽 + 使用 + 載入中… + diff --git a/app/src/main/res/values-zh-rTW/input_flow_strings.xml b/app/src/main/res/values-zh-rTW/input_flow_strings.xml new file mode 100644 index 0000000000..bbe4de2e26 --- /dev/null +++ b/app/src/main/res/values-zh-rTW/input_flow_strings.xml @@ -0,0 +1,41 @@ + + + 控制 + 預設(%1$s) + %1$s:已變更 %2$d 項 + 變更儲存至 + 單一遊戲的變更會疊加在其設定檔之上。 + 所有遊戲 + 按鈕和搖桿 + 螢幕版面配置 + 使用設定檔的控制 + 移除 %1$s 的變更 + 所有控制器設定 + 觸控控制 + 類型 + 顯示 + 正在為 %1$s 儲存 + 輕觸控制項,或在控制器上按下它。 + 按下按鈕 + 請按下控制器上的按鈕… + 裝置按鈕和額外按鍵 + 其他控制項 + 還原為設定檔:%1$s + 複製 + 格線 + 細 + 粗 + 有自己控制的遊戲 + 遊戲執行時可在選單中變更其控制。 + 預設用於 + 兩種模式 + 無 + 已被 %1$d 個遊戲固定 + 我的 + 社群 + Winlator 玩家分享的版面配置。其按鈕會傳送鍵盤和滑鼠按鍵。 + 無法載入共享版面配置。請檢查連線後再試一次。 + 預覽 + 使用 + 載入中… + diff --git a/app/src/main/res/values/input_flow_strings.xml b/app/src/main/res/values/input_flow_strings.xml new file mode 100644 index 0000000000..1ec72b9fe5 --- /dev/null +++ b/app/src/main/res/values/input_flow_strings.xml @@ -0,0 +1,42 @@ + + + Controls + Default (%1$s) + %1$s: %2$d changed + Save changes for + Changes for one game sit on top of its profile. + All games + Buttons and sticks + On-screen layout + Use the profile\'s controls + Drops what %1$s changed + All controller settings + Touch controls + Type + DroidDeck + Show + Saving for %1$s + Tap a control, or press it on your controller. + Press a button + Press a button on your controller… + Device buttons and extra keys + Other controls + Back to profile: %1$s + Duplicate + Grid + Fine + Coarse + Games with their own controls + Change a game\'s controls from the menu while it runs. + Default for + Both modes + Neither + Pinned by %1$d games + Mine + Community + Layouts shared by Winlator players. Their buttons send keyboard and mouse keys. + Could not load the shared layouts. Check the connection and try again. + Preview + Use + Loading… + diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryGamesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryGamesTest.kt new file mode 100644 index 0000000000..8039d17551 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryGamesTest.kt @@ -0,0 +1,117 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class InputLibraryGamesTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + @Before fun reset() { + for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit() + } + + private fun library() = InputLibraries.read(context) + + @Test fun aGameCopyChangesOnlyThatGame() { + val base = library() + val forked = base.withGamePart(false, "620", "Portal 2", InputRole.PHYSICAL) + val part = forked.activePart(false, InputRole.PHYSICAL, "620") + assertNotEquals(base.activePart(false, InputRole.PHYSICAL).bindings, part.bindings) + assertEquals(0, forked.gameChanges(false, "620")) + + val changed = forked.withPreset(forked.preset(part.bindings).let { it.copy(controls = it.controls + (InputControl.A to InputAction.Keys(listOf(18)))) }) + assertEquals(InputAction.Keys(listOf(18)), changed.compileActive(false, game = "620").action(InputRole.PHYSICAL, InputControl.A)) + assertEquals(InputAction.Native(), changed.compileActive(false).action(InputRole.PHYSICAL, InputControl.A)) + assertEquals(InputAction.Native(), changed.compileActive(false, game = "413150").action(InputRole.PHYSICAL, InputControl.A)) + assertEquals(1, changed.gameChanges(false, "620")) + assertEquals(1, changed.gameChanges(false, "620", InputRole.PHYSICAL)) + assertEquals(0, changed.gameChanges(false, "620", InputRole.PRIMARY)) + changed.validate() + assertEquals(changed, InputLibraries.decode(InputLibraries.encode(changed))) + + val reset = changed.resetGame("620") + assertTrue(reset.games.isEmpty()) + assertEquals(base.bindings.map { it.id }.toSet(), reset.bindings.map { it.id }.toSet()) + } + + @Test fun aGameCopyOfTheMainScreenLayoutKeepsItsGamepadOrigin() { + val base = library() + val layout = base.activeLayout(false, InputRole.PRIMARY)!! + val forked = base.withGamePart(false, "620", "Portal 2", InputRole.PRIMARY) + val copy = forked.activeLayout(false, InputRole.PRIMARY, "620")!! + if (layout.editable) { + assertNotEquals(layout.id, copy.id) + assertEquals(layout.origin ?: layout.id, copy.origin) + assertEquals(layout.elements, copy.elements) + val moved = forked.withLayout(copy.copy(elements = copy.elements.map { it.copy(x = (it.x + .01f).coerceAtMost(.9f)) })) + assertTrue(moved.gameChanges(false, "620") > 0) + assertEquals(layout, moved.activeLayout(false, InputRole.PRIMARY)) + val back = moved.resetGame("620", InputRole.PRIMARY) + assertEquals(base.layouts.map { it.id }.toSet(), back.layouts.map { it.id }.toSet()) + } else assertEquals(layout.id, copy.id) + forked.validate() + } + + @Test fun aGameCanPinAProfileUntilTheProfileIsDeleted() { + val base = library().duplicateProfile(InputProfile.GAME, "Racing", "racing") + val pinned = base.withGameProfile("1293830", "Forza Horizon 4", "racing") + assertEquals("racing", pinned.activeId(false, "1293830")) + assertEquals(InputProfile.GAME, pinned.activeId(false)) + assertEquals(pinned.profile("racing").binding(InputRole.PHYSICAL), pinned.activePart(false, InputRole.PHYSICAL, "1293830").bindings) + pinned.validate() + assertEquals(pinned, InputLibraries.decode(InputLibraries.encode(pinned))) + + val gone = pinned.removeProfile("racing") + assertFalse(gone.games.containsKey("1293830")) + assertEquals(InputProfile.GAME, gone.activeId(false, "1293830")) + assertTrue(pinned.withGameProfile("1293830", "Forza Horizon 4", null).games.isEmpty()) + } + + @Test fun aGamesOwnPartWinsOverItsPinnedProfile() { + val base = library().duplicateProfile(InputProfile.GAME, "Racing", "racing") + val both = base.withGameProfile("620", "Portal 2", "racing").withGamePart(false, "620", "Portal 2", InputRole.PHYSICAL) + val own = both.games.getValue("620").parts.getValue(InputRole.PHYSICAL) + assertEquals(own, both.activePart(false, InputRole.PHYSICAL, "620")) + assertEquals(both.profile("racing").parts.getValue(InputRole.PRIMARY), both.activePart(false, InputRole.PRIMARY, "620")) + val cleared = both.resetGame("620", InputRole.PHYSICAL) + assertEquals("racing", cleared.games.getValue("620").profile) + assertTrue(cleared.games.getValue("620").parts.isEmpty()) + } + + @Test fun aGamesCopiesCantBeDeletedFromUnderIt() { + val forked = library().withGamePart(false, "620", "Portal 2", InputRole.PHYSICAL) + val id = forked.activePart(false, InputRole.PHYSICAL, "620").bindings + assertTrue(forked.selectedBindings(id)) + assertTrue(runCatching { forked.removeBindings(id) }.isFailure) + } + + @Test fun theOldPerLayoutOpacityFoldsIntoTheGlobalOneOnce() { + val base = library() + val main = base.activeLayout(false, InputRole.PRIMARY)!! + val faded = base.copy(layouts = base.layouts.map { if (it.id == main.id) it.copy(style = it.style.copy(opacity = 50)) else it }) + ControllerPrefs.setOnScreenOpacity(context, 80) + val folded = InputLibraries.singleOpacity(context, faded) + assertTrue(folded.layouts.all { it.style.opacity == 100 }) + assertEquals(40, ControllerPrefs.onScreenOpacity(context)) + InputLibraries.singleOpacity(context, faded) + assertEquals(40, ControllerPrefs.onScreenOpacity(context)) + } + + @Test fun steamSessionsUseSteamTouchUntilTheyPick() { + assertFalse(SessionPrefs.oscChosen(context)) + assertEquals(SessionPrefs.OSC_STEAM_TOUCH, SessionPrefs.oscMode(context, steamSession = true)) + assertEquals(SessionPrefs.OSC_AUTO, SessionPrefs.oscMode(context, steamSession = false)) + SessionPrefs.setOscMode(context, SessionPrefs.OSC_ALWAYS) + assertTrue(SessionPrefs.oscChosen(context)) + assertEquals(SessionPrefs.OSC_ALWAYS, SessionPrefs.oscMode(context, steamSession = true)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 0b8d28a23b..e36c3c8819 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -90,7 +90,7 @@ class InputLibraryTest { assertEquals("previous backup", prefs.getString(backup, null)) assertEquals(original, InputLibraries.read(context)) - assertEquals(14, JSONObject(prefs.getString("library", null)!!).getInt("version")) + assertEquals(17, JSONObject(prefs.getString("library", null)!!).getInt("version")) assertEquals(raw, prefs.getString(backup, null)) } @@ -447,10 +447,11 @@ class InputLibraryTest { assertEquals(true, overlay.adaptiveSticks) } - @Test fun onScreenOpacityDefaultsToFullAndClampsWithoutChangingLayoutStyle() { + @Test fun theOldGamepadOpacityBecomesTheOneOnScreenOpacityAndClamps() { ControllerPrefs.setOpacity(context, 60) val layout = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!! - assertEquals(100, ControllerPrefs.read(context).onScreenOpacity) + assertEquals(100, layout.style.opacity) + assertEquals(60, ControllerPrefs.read(context).onScreenOpacity) for ((requested, expected) in listOf(0 to 10, 45 to 45, 101 to 100)) { ControllerPrefs.setOnScreenOpacity(context, requested) assertEquals(expected, ControllerPrefs.read(context).onScreenOpacity) diff --git a/app/src/test/java/com/droiddeck/launcher/input/WinlatorLayoutsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/WinlatorLayoutsTest.kt new file mode 100644 index 0000000000..6c3d48e27d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/WinlatorLayoutsTest.kt @@ -0,0 +1,81 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE) +class WinlatorLayoutsTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + + private val profile = """ + {"id":3,"name":"Shooter","cursorSpeed":1,"elements":[ + {"type":"D_PAD","shape":"CIRCLE","bindings":["KEY_W","KEY_D","KEY_S","KEY_A"],"scale":1,"x":0.1,"y":0.7,"toggleSwitch":false,"text":"","iconId":0}, + {"type":"BUTTON","shape":"CIRCLE","bindings":["MOUSE_LEFT_BUTTON","NONE","NONE","NONE"],"scale":1,"x":0.85,"y":0.75,"toggleSwitch":false,"text":"","iconId":0}, + {"type":"BUTTON","shape":"RECT","bindings":["KEY_SPACE","NONE","NONE","NONE"],"scale":1.2,"x":0.9,"y":0.5,"toggleSwitch":true,"text":"Jump","iconId":0}, + {"type":"BUTTON","shape":"ROUND_RECT","bindings":["GAMEPAD_BUTTON_L2","NONE","NONE","NONE"],"scale":1,"x":0.1,"y":0.1,"toggleSwitch":false,"text":"","iconId":0}, + {"type":"STICK","shape":"CIRCLE","bindings":["GAMEPAD_RIGHT_THUMB_UP","GAMEPAD_RIGHT_THUMB_RIGHT","GAMEPAD_RIGHT_THUMB_DOWN","GAMEPAD_RIGHT_THUMB_LEFT"],"scale":1,"x":0.7,"y":0.7,"toggleSwitch":false,"text":"","iconId":0}, + {"type":"TRACKPAD","shape":"CIRCLE","bindings":["MOUSE_MOVE_UP","MOUSE_MOVE_RIGHT","MOUSE_MOVE_DOWN","MOUSE_MOVE_LEFT"],"scale":1,"x":0.5,"y":0.5,"toggleSwitch":false,"text":"","iconId":0}, + {"type":"RANGE_BUTTON","shape":"CIRCLE","bindings":["NONE","NONE","NONE","NONE"],"scale":0.85,"x":0.5,"y":0.07,"toggleSwitch":false,"text":"","iconId":0,"range":"FROM_F1_TO_F12"}, + {"type":"BUTTON","shape":"CIRCLE","bindings":["NONE","NONE","NONE","NONE"],"scale":1,"x":0.3,"y":0.3,"toggleSwitch":false,"text":"","iconId":0} + ]} + """.trimIndent() + + @Test fun recognisesWinlatorFilesOnly() { + assertTrue(WinlatorLayouts.isIcp(profile)) + assertFalse(WinlatorLayouts.isIcp("""{"version":1,"keys":[]}""")) + assertFalse(WinlatorLayouts.isIcp("not json")) + } + + @Test fun convertsEachKindOfControl() { + val (layout, bindings) = WinlatorLayouts.import(profile, "fallback", InputLayoutScreen.MAIN, 2400, 1080)!! + assertEquals("Shooter", layout.name) + assertEquals(10, layout.elements.size) + assertTrue(layout.elements.all { it.x in 0f..1f && it.y in 0f..1f && it.x + it.width <= 1.001f && it.y + it.height <= 1.001f }) + fun action(name: String) = bindings.elements.getValue(layout.elements.first { it.name == name }.id) + + val dpad = layout.elements.single { it.kind == InputElementKind.DPAD } + assertEquals(InputAction.Directions(17, 32, 31, 30), bindings.elements[dpad.id]) + assertEquals(InputAction.MouseButton(272), action("Left")) + val jump = layout.elements.single { it.name == "Jump" } + assertTrue(jump.toggle) + assertEquals(InputButtonShape.RECTANGLE, jump.buttonShape) + assertEquals(InputAction.Keys(listOf(57)), bindings.elements[jump.id]) + val trigger = layout.elements.single { it.kind == InputElementKind.TRIGGER } + assertEquals(InputAction.Native(InputControl.LT), bindings.elements[trigger.id]) + val stick = layout.elements.single { it.kind == InputElementKind.STICK } + assertEquals(InputAction.Native(InputControl.RS), bindings.elements[stick.id]) + val pad = layout.elements.single { it.kind == InputElementKind.TRACKPAD } + assertEquals(InputAction.Pointer(), bindings.elements[pad.id]) + assertEquals(listOf("F1", "F2", "F3", "F4"), layout.elements.filter { it.name.matches(Regex("F[0-9]+")) }.map { it.name }) + assertEquals(InputAction.Keys(listOf(59)), action("F1")) + + val dpadWide = dpad.width * 2400 + val dpadTall = dpad.height * 1080 + assertEquals(dpadWide, dpadTall, 2f) + } + + @Test fun theImportedLayoutJoinsTheLibrary() { + val (layout, bindings) = WinlatorLayouts.import(profile, "fallback", InputLayoutScreen.MAIN, 2400, 1080)!! + val library = InputLibraries.read(context) + val updated = library.withLayout(layout).withPreset(bindings).chooseLayout(InputProfile.GAME, InputRole.PRIMARY, layout.id).validate() + assertEquals(layout.id, updated.activeLayout(false, InputRole.PRIMARY)?.id) + assertEquals(updated, InputLibraries.decode(InputLibraries.encode(updated))) + } + + @Test fun readsTheCommunityIndex() { + assertEquals(listOf("Bioshock.icp", "Dark Souls 2.icp"), + WinlatorLayouts.parseIndex("Bioshock.icp\n\nDark Souls 2.icp\r\nREADME.md\n../evil.icp\nBioshock.icp\n")) + assertEquals("https://raw.githubusercontent.com/brunodev85/winlator/main/input_controls/Dark%20Souls%202.icp", + WinlatorLayouts.fileUrl("Dark Souls 2.icp")) + } + + @Test fun rejectsAFileWithNothingToPlace() { + assertNull(WinlatorLayouts.import("""{"cursorSpeed":1,"elements":[]}""", "x", InputLayoutScreen.MAIN, 100, 100)) + } +} 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 ac643381a5..8abf475578 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -116,10 +116,10 @@ class InputSettingsTest { compose.setContent { DroidDeckTheme { InputSettingsPage({}, { changed = true }) } } compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() compose.onNodeWithTag("input-part-physical").performScrollTo().performClick() - compose.onNodeWithTag("input-binding-a").performScrollTo().performClick() + compose.onNodeWithTag("input-buttons-pad").assertExists() compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() compose.runOnIdle { assertFalse(changed) } - compose.onNodeWithTag("input-action-save").performClick() + compose.onNodeWithTag("input-buttons-save").performScrollTo().performClick() compose.runOnIdle { assertTrue(changed) val profile = InputProfiles.read(context, InputProfile.GAME) @@ -137,9 +137,8 @@ class InputSettingsTest { compose.onNodeWithTag("input-editor-tools").performClick() compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick() compose.onNodeWithText(context.getString(R.string.input_element_button), substring = false).performClick() - compose.onNodeWithTag("input-editor-tools").performClick() - compose.onNodeWithText(context.getString(R.string.input_properties)).assertExists() - compose.onNodeWithText(context.getString(R.string.input_editor_done)).performClick() + compose.onNodeWithTag("input-editor-panel").assertExists() + compose.onNodeWithTag("input-editor-done").performClick() compose.runOnIdle { assertTrue(changed) val updated = InputLibraries.read(context) @@ -167,10 +166,10 @@ class InputSettingsTest { 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() - compose.onNodeWithTag("input-binding-a").assertExists() - compose.onNodeWithText(context.getString(R.string.mode_back)).performClick() + compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick() + compose.onNodeWithTag("input-buttons-save").performScrollTo().performClick() + compose.onNodeWithTag("input-buttons-pad").assertExists() + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() compose.onNodeWithTag("input-part-secondary").assertExists() compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) } } @@ -198,6 +197,7 @@ class InputSettingsTest { compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick() compose.onNodeWithText(context.getString(R.string.input_element_button)).performClick() compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(center) } + compose.onNodeWithText(context.getString(R.string.common_close)).performScrollTo().performClick() compose.onNodeWithTag("input-editor-tools").performClick() compose.onNodeWithText(context.getString(R.string.input_hide_tools)).performClick() compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertDoesNotExist() @@ -462,21 +462,79 @@ class InputSettingsTest { com.droiddeck.launcher.input.ControllerPrefs.setSnap(context, true) } - @Test fun quickButtonTogglesHideBuiltInButtonsWithoutDeletingThem() { - compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } - compose.onNodeWithTag("input-profile-game").performScrollTo().performClick() - compose.onNodeWithTag("input-part-primary").performScrollTo().performClick() - val before = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! - compose.onNodeWithTag("setting-quick-keyboard").performScrollTo().performClick() + @Test fun quickButtonTogglesInTheEditorHideBuiltInButtonsWithoutDeletingThem() { + val library = InputLibraries.read(context) + val before = library.layout("game", InputRole.PRIMARY)!! + val round = mutableStateOf(0) + compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = before.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("setting-editor-quick-keyboard").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() compose.runOnIdle { val after = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!! - assertEquals(before.elements, after.elements) + assertEquals(before.elements.map { it.id }, after.elements.map { it.id }) assertEquals(setOf(InputCommand.KEYBOARD), after.style.hidden) + round.value = 1 } - compose.onNodeWithTag("setting-quick-keyboard").performScrollTo().performClick() + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithTag("setting-editor-quick-keyboard").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick() compose.runOnIdle { assertTrue(InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!.style.hidden.isEmpty()) } } + @Test fun duplicatingACustomButtonCopiesWhatItDoes() { + val library = InputLibraries.read(context) + val layout = library.layout("game", InputRole.SECONDARY)!! + compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY, + layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.SECONDARY)) } } + compose.onNodeWithTag("input-editor-tools").performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick() + compose.onNodeWithText(context.getString(R.string.input_element_button), substring = false).performClick() + compose.onNodeWithText(context.getString(R.string.input_route_local), substring = false).performScrollTo().performClick() + compose.onNodeWithTag("input-editor-duplicate").performScrollTo().performClick() + compose.onNodeWithTag("input-editor-done").performClick() + compose.runOnIdle { + val updated = InputLibraries.read(context) + val added = updated.layout("game", InputRole.SECONDARY)!!.elements.filter { e -> layout.elements.none { it.id == e.id } } + assertEquals(2, added.size) + val profile = updated.compile("game") + assertEquals(InputAction.Keys(listOf(28)), profile.elementAction(InputRole.SECONDARY, added[0].id, added[0].control)) + assertEquals(InputAction.Keys(listOf(28)), profile.elementAction(InputRole.SECONDARY, added[1].id, added[1].control)) + assertEquals(added[0].x + .03f, added[1].x, .001f) + } + } + + @Test fun theProfilePageSetsWhatItIsTheDefaultFor() { + InputLibraries.update(context) { it.duplicateProfile(InputProfile.GAME, "Racing", "racing") } + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-profile-racing").performScrollTo().performClick() + compose.onNodeWithTag("setting-profile-default").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.flow_both_modes)).performClick() + compose.runOnIdle { + val library = InputLibraries.read(context) + assertEquals("racing", library.steam); assertEquals("racing", library.desktop) + } + compose.onNodeWithTag("setting-profile-default").performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.flow_no_mode)).performClick() + compose.runOnIdle { + val library = InputLibraries.read(context) + assertEquals(InputProfile.GAME, library.steam); assertEquals(InputProfile.DESKTOP, library.desktop) + } + } + + @Test fun gamesWithTheirOwnControlsAreListedAndCanBeReset() { + InputLibraries.update(context) { l -> l.withGamePart(false, "620", "Portal 2", InputRole.PHYSICAL).let { forked -> + val id = forked.activePart(false, InputRole.PHYSICAL, "620").bindings + forked.withPreset(forked.preset(id).let { it.copy(controls = it.controls + (InputControl.A to InputAction.Disabled)) }) + } } + compose.setContent { DroidDeckTheme { InputSettingsPage({}) } } + compose.onNodeWithTag("input-game-620").performScrollTo().assertExists() + compose.onAllNodesWithText("Portal 2", substring = true).onFirst().assertExists() + compose.onNodeWithText(context.getString(R.string.ctrl_reset)).performScrollTo().performClick() + compose.runOnIdle { assertTrue(InputLibraries.read(context).games.isEmpty()) } + } + @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"}]}""") @@ -587,11 +645,10 @@ class InputSettingsTest { } val moved = compose.runOnIdle { editor().rendered().associateBy { it.id } } assertEquals(resized.getValue("legacy:b").x - .1f, moved.getValue("legacy:b").x, .002f) - compose.onNodeWithTag("input-editor-tools").performClick() compose.runOnIdle { editor().onSelect("legacy:a") } slider().assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%")) slider().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(120f) } - compose.onNodeWithText(context.getString(R.string.input_editor_undo)).performScrollTo().performClick() + compose.onNodeWithText(context.getString(R.string.input_editor_undo)).performClick() val undone = compose.runOnIdle { editor().rendered().associateBy { it.id } } assertEquals(moved.getValue("legacy:b").x, undone.getValue("legacy:b").x, .0001f) assertEquals(resized.getValue("legacy:a").width, undone.getValue("legacy:a").width, .0001f) 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 7adbbfacc4..b60e50deef 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputUiLayoutTest.kt @@ -61,8 +61,8 @@ class InputUiLayoutTest { } } } } compose.onNodeWithTag("input-profile-desktop").performScrollTo().assertIsDisplayed().performClick() compose.onNodeWithTag("input-part-physical").performScrollTo().assertIsDisplayed().performClick() - compose.onNodeWithTag("input-binding-a").performScrollTo().assertIsDisplayed().performClick() - compose.onNodeWithTag("input-action-save").assertIsDisplayed() + compose.onNodeWithTag("input-buttons-pad").assertIsDisplayed() + compose.onNodeWithTag("input-buttons-save").performScrollTo().assertIsDisplayed() screenshot("phone-properties") } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt index da99b2f8a9..b8d1ff276e 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionSecondScreenTest.kt @@ -26,6 +26,7 @@ import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState import org.junit.After import com.droiddeck.launcher.input.InputLibraries +import com.droiddeck.launcher.input.InputProfile import com.droiddeck.launcher.input.InputRole import com.droiddeck.launcher.input.InputElementKind import com.droiddeck.launcher.input.InputSurfaceElement @@ -395,7 +396,10 @@ class SessionSecondScreenTest { private fun checkQuickSelection(steam: Boolean, desktop: Boolean, direct: Boolean) { SessionState.mode = if (desktop) SessionService.MODE_DESKTOP else if (steam) SessionService.MODE_STEAM else SessionService.MODE_RUN - val original = InputLibraries.update(context) { it.chooseLayout("desktop", InputRole.SECONDARY, InputLibraries.DECK) } + SessionState.inputGame = null + val original = InputLibraries.read(context) + val target = if (desktop) InputProfile.GAME else InputProfile.DESKTOP + val expected = if (desktop) InputLibraries.DECK else InputLibraries.TRACKPAD val activity = Robolectric.buildActivity(SessionActivity::class.java).get() val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY) val panel = SecondScreenPresentation(activity, display, {}, {}, {}) @@ -412,21 +416,18 @@ class SessionSecondScreenTest { } compose.openSection("controller-input") compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick() - compose.onNodeWithText("Desktop").performScrollTo().performClick() - compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick() - compose.onNodeWithTag("setting-input-part-SECONDARY").performScrollTo().performClick() - compose.onNodeWithText("Trackpad + keyboard").performScrollTo().performClick() + compose.onNodeWithText(original.profile(target).name).performScrollTo().performClick() compose.onNode(hasContentDescription(context.getString(R.string.common_close)) and SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.Role, androidx.compose.ui.semantics.Role.Button)).performClick() compose.runOnIdle { val updated = InputLibraries.read(context) - assertEquals("desktop", updated.selection(desktop).profile) - assertEquals(InputLibraries.TRACKPAD, updated.activeLayout(desktop, InputRole.SECONDARY)?.id) + assertEquals(target, updated.selection(desktop).profile) + assertEquals(expected, updated.activeLayout(desktop, InputRole.SECONDARY)?.id) assertEquals(original.selection(!desktop), updated.selection(!desktop)) assertEquals(original.profiles, updated.profiles) val controls = descendants(panel.window!!.decorView).filterIsInstance().single() val pads = descendants(controls).mapNotNull { it.tag as? InputSurfaceElement }.filter { it.kind == InputElementKind.TRACKPAD }.toList() - assertEquals(1, pads.size) + assertEquals(if (desktop) 2 else 1, pads.size) } } finally { panel.closeControls() } } diff --git a/docs/compose-previews.md b/docs/compose-previews.md index a91a35d37f..f18efc2c29 100644 --- a/docs/compose-previews.md +++ b/docs/compose-previews.md @@ -24,9 +24,9 @@ ways: | `app/src/testDebug/.../ui/PreviewRenderTest.kt` | The render test | Previews cover the launcher on each tab (Steam, Library, Library with no games, Stores, Downloads, Settings, Settings with -no runtime), the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu), and the frosted -background: the Steam and Library tabs, Settings with frosted cards and with both transparencies at 100 %, and a -settings step opened over frosted page text. +no runtime), the in-game menu's pages (Controller, Display, HUD, Session, and the Desktop menu), Controller settings and +its Buttons and sticks page, and the frosted background: the Steam and Library tabs, Settings with frosted cards and with +both transparencies at 100 %, and a settings step opened over frosted page text. ## Adding one diff --git a/docs/settings-map.md b/docs/settings-map.md index aface4f407..cf373a9e23 100644 --- a/docs/settings-map.md +++ b/docs/settings-map.md @@ -84,8 +84,9 @@ Links of the form `droiddeck://settings/
` open a Settings section direc | Performance HUD | In-game menu › Performance HUD | fps, counter, overlay, performance | | Hold the GPU at its top clock | In-game menu › Performance HUD | gpu, clock, max | | Touchscreen | In-game menu › Controller | touch, mouse, direct, touchpad, click | -| On-screen controls | In-game menu › Controller | on-screen, controls, touch controls, buttons | -| Steam touch layout | In-game menu › Controller | touch layout, edit layout, on-screen | +| Touch controls | In-game menu › Controller | on-screen, controls, steam touch, visibility, opacity, size | +| On-screen layout | In-game menu › Controller | touch layout, edit layout, on-screen, osc | +| Buttons and sticks | In-game menu › Controller | remap, mapping, bindings, buttons, per game, profile | | PC keyboard | In-game menu › Controller | keyboard, typing | | Report a problem | In-game menu › Session | logs, log, bug, crash, share, zip | | Background behavior | In-game menu › Session | sleep, background, native, resume |