diff --git a/README.md b/README.md index 86ba1d832a..d50b79a9ff 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,14 @@ Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Adre On Android 14 and newer, before Steam launches, you must turn on **Disable child process restrictions** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process. +## Physical button shortcuts + +Open the launcher's **Controls** settings, **Setup → Controller → Button mapping**, or the session drawer's **Controller** page. Each menu action has one row showing **Custom** or **Default**. Select the current value beside **Steam menu**, **Open Quick Access Menu**, or **DroidDeck menu**, then press and release a physical button. The assignment saves automatically on release; confirmation is only required if the button already opens another menu. Assignments are stored per controller; each action has one assigned button per controller. A mapped button performs the shortcut instead of sending its normal input to the game. Steam shortcuts only apply in Steam sessions, and shortcuts are inactive while loading, suspended, or using the on-screen keyboard or other input dialogs. + +Unassigned buttons keep their existing behavior, including the Back button's single/double-press setting and Select-to-Steam option. While the session drawer is open, A selects the focused item even if it has a shortcut assignment. Select an action's current value and use **Reset** beside an assignment to restore that behavior without changing touch layouts or other controller settings. **Close** exits capture without changing an assignment; it does not undo an assignment already applied. The touchscreen remains available for configuration and recovery. + +Extra buttons such as M1/M2 work only if Android exposes distinct key events to the app. Android Home, volume and other reserved system keys cannot be assigned; making DroidDeck the default launcher retains its existing Home-to-Steam behavior. Firmware that intercepts a button or makes it duplicate another button cannot be overridden here. During capture, the detected device and button name are shown. If a controller disconnects before release, use **Try another button** to restart capture; **Reset** remains available for existing assignments. Capture and shortcut-action diagnostics, including key and scan codes, are included in session logs when capture runs inside a session. If a button is not detected, record its physical label, firmware/controller mode, and whether it leaves the app, then share the session logs. + ## Smart glasses Use **Setup → Smart glasses** for app-wide virtual-screen settings across DroidDeck menus, launchers, desktop sessions, and games. Supported VITURE, RayNeo, XREAL, and Rokid connections provide 3DoF; Luma Ultra adds optional experimental 6DoF and stereo-assisted hand/Joy-Con tracking. Model support and SDK requirements differ: see the [smart-glasses support matrix](docs/smart-glasses-support.md) for supported devices, controls, setup, and limitations. diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 5bd783ce4b..5ef660a76d 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -75,6 +75,8 @@ import com.droiddeck.launcher.input.ControllerPrefs import com.droiddeck.launcher.input.SessionClipboard import com.droiddeck.launcher.input.OnScreenControls import com.droiddeck.launcher.input.PadBridge +import com.droiddeck.launcher.input.PhysicalShortcuts +import com.droiddeck.launcher.input.PhysicalShortcutRouter import com.droiddeck.launcher.input.PadMouse import com.droiddeck.launcher.input.PadState import com.droiddeck.launcher.input.ScreenKeys @@ -162,6 +164,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var hud: FusionHudHost private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud private var padBridge: PadBridge? = null + private val physicalShortcuts = PhysicalShortcutRouter() private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null private var padMotion: com.droiddeck.launcher.input.PadMotion? = null @@ -433,6 +436,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private val cardboardPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == SessionPrefs.CARDBOARD_KEY) uiHandler.post { applyCardboard(SessionPrefs.cardboard(this)) } } + private val shortcutPrefListener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key -> + if (key == null || key == PhysicalShortcuts.KEY) { + physicalShortcuts.bindings = PhysicalShortcuts.read(this) + } + } private var textureAnisotropy by mutableStateOf(0) private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF) private var drawerTextureAnisotropy by mutableStateOf(null) @@ -519,6 +527,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { updateHandCamera() } override fun onInputDeviceRemoved(deviceId: Int) { + physicalShortcuts.onDeviceRemoved(deviceId) Log.i(TAG, "input device $deviceId disconnected") backQamInput.onDeviceRemoved(deviceId) joyConVr?.refresh() @@ -1828,6 +1837,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) oscMode = SessionPrefs.oscMode(this) backActionsInverted = SessionPrefs.backActionsInverted(this) + physicalShortcuts.bindings = PhysicalShortcuts.read(this) backDoubleTapMs = SessionPrefs.backDoubleTapMs(this) lowLatency = SessionPrefs.lowLatency(this) evdevMouseOn = SessionPrefs.evdevMouse(this) @@ -2456,6 +2466,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } if (pipUi) return true if (screenKeyTextFocus) return super.dispatchKeyEvent(event) + if (physicalShortcuts.onKey( + event, + enabled = SessionState.running && !SessionState.suspended && + !(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) && + !(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) && + (event.deviceId to event.keyCode) !in resumeKeysDown && + !(::loading.isInitialized && (loading.visible || loading.ended)) && + !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen, + steam = SessionState.mode == SessionService.MODE_STEAM, + ) { action -> + pendingBackAction?.let(uiHandler::removeCallbacks) + pendingBackAction = null + drawerControllerActive = true + Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}") + when (action) { + PhysicalShortcuts.Action.STEAM -> sendSteamGuide() + PhysicalShortcuts.Action.QAM -> triggerSteamQam() + PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen + } + }) return true val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) if (pad !== event) return dispatchKeyEvent(pad) val fromController = PadBridge.isControllerKeyEvent(event) @@ -3892,6 +3922,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { updatePointerCapture() if (!pipUi) sessionClipboard.start() updatePadMotion() + ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener) readPrefs() refreshControls() if (::pip.isInitialized) pip.resumed() @@ -3902,6 +3933,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPause() { com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) if (runtimeRemovalBlocked) { super.onPause(); return } + physicalShortcuts.clear() backQamInput.cancel() capturePausedFrame() sessionClipboard.stop() @@ -3925,6 +3957,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { updatePadMotion() keyboard?.takeIf { it.shown }?.hide() SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener) + ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener) updateHeadTracker() super.onPause() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PhysicalShortcuts.kt b/app/src/main/java/com/droiddeck/launcher/input/PhysicalShortcuts.kt new file mode 100644 index 0000000000..a79fa8c706 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/PhysicalShortcuts.kt @@ -0,0 +1,145 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.util.Log +import android.view.InputDevice +import android.view.KeyEvent +import androidx.annotation.StringRes +import com.droiddeck.launcher.R +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +object PhysicalShortcuts { + internal const val KEY = "physicalShortcuts" + private const val TAG = "PhysicalShortcuts" + + enum class Action(@StringRes val label: Int) { + STEAM(R.string.drawer_steam_menu), + QAM(R.string.drawer_open_qam), + DROIDDECK(R.string.shortcuts_dd_menu), + } + + data class Button( + val device: String, + val name: String, + val keyCode: Int, + val scanCode: Int, + ) { + fun matches(event: KeyEvent): Boolean = + event.device?.let { device == identity(it) } == true && + keyCode == event.keyCode && scanCode == event.scanCode + + fun sameInput(other: Button): Boolean = + device == other.device && keyCode == other.keyCode && scanCode == other.scanCode + + val label: String + get() = KeyEvent.keyCodeToString(keyCode).removePrefix("KEYCODE_").removePrefix("BUTTON_") + + } + + data class Binding(val button: Button, val action: Action) + + private fun identity(device: InputDevice): String = + "${device.vendorId}:${device.productId}:${device.descriptor.ifBlank { device.name }}" + + fun isVolumeKey(event: KeyEvent): Boolean = when (event.keyCode) { + KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> true + else -> false + } + + fun isDrawerNavigationKey(event: KeyEvent): Boolean = when (event.keyCode) { + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> true + else -> false + } + + fun button(event: KeyEvent): Button? { + val device = event.device ?: return null + if (device.isVirtual || isVolumeKey(event)) return null + when (event.keyCode) { + KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_SLEEP, + KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_APP_SWITCH -> return null + } + if (event.keyCode == KeyEvent.KEYCODE_UNKNOWN && event.scanCode <= 0) return null + return Button(identity(device), device.name, event.keyCode, event.scanCode) + } + + fun read(context: Context): List { + val raw = ControllerPrefs.prefs(context).getString(KEY, null) ?: return emptyList() + return try { + val array = JSONArray(raw) + buildList { + for (i in 0 until array.length()) { + try { + val entry = array.getJSONObject(i) + val action = Action.entries.firstOrNull { it.name == entry.getString("action") } + val code = entry.getInt("keyCode") + val scan = entry.getInt("scanCode") + val device = entry.getString("device") + if (action == null || device.isBlank() || code < 0 || scan < 0) { + Log.w(TAG, "Ignoring invalid shortcut at index $i") + continue + } + val binding = Binding(Button(device, entry.getString("name"), code, scan), action) + if (none { it.button.sameInput(binding.button) }) add(binding) + } catch (e: JSONException) { + Log.w(TAG, "Ignoring malformed shortcut at index $i", e) + } + } + } + } catch (e: JSONException) { + Log.w(TAG, "Could not read physical shortcuts; reset shortcuts to restore defaults", e) + emptyList() + } + } + + fun assign(context: Context, button: Button, action: Action) { + val bindings = read(context).filterNot { + it.button.sameInput(button) || (it.button.device == button.device && it.action == action) + } + Binding(button, action) + write(context, bindings) + } + + fun remove(context: Context, binding: Binding) { + write(context, read(context).filterNot { it == binding }) + } + + private fun write(context: Context, bindings: List) { + val array = JSONArray() + bindings.forEach { + array.put(JSONObject().put("device", it.button.device).put("name", it.button.name) + .put("keyCode", it.button.keyCode).put("scanCode", it.button.scanCode).put("action", it.action.name)) + } + ControllerPrefs.prefs(context).edit().putString(KEY, array.toString()).apply() + } + +} + +class PhysicalShortcutRouter { + var bindings: List = emptyList() + private data class Press(val device: Int, val keyCode: Int, val scanCode: Int) + private val held = mutableSetOf() + + fun onKey(event: KeyEvent, enabled: Boolean, steam: Boolean, perform: (PhysicalShortcuts.Action) -> Unit): Boolean { + val press = Press(event.deviceId, event.keyCode, event.scanCode) + if (event.action == KeyEvent.ACTION_UP) return held.remove(press) + if (event.action != KeyEvent.ACTION_DOWN) return false + if (press in held) return true + if (!enabled || bindings.isEmpty()) return false + val button = PhysicalShortcuts.button(event) ?: return false + val binding = bindings.firstOrNull { it.button.sameInput(button) } ?: return false + if (!steam && binding.action != PhysicalShortcuts.Action.DROIDDECK) return false + held.add(press) + if (event.repeatCount == 0) perform(binding.action) + return true + } + + fun onDeviceRemoved(deviceId: Int) { + held.removeAll { it.device == deviceId } + } + + fun clear() { + held.clear() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt index ff39fb00f3..0fab267984 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ControllerSettings.kt @@ -93,6 +93,9 @@ fun ControllerMappingPage(mapping: Map, onPick: (String, String) lede = stringResource(R.string.ctrl_mapping_lede), onBack = onBack, ) { + SettingsGroup(stringResource(R.string.shortcuts_title)) { + PhysicalShortcutRows() + } SettingsGroup(stringResource(R.string.ctrl_onscreen_buttons)) { val targets = ControllerPrefs.targets.map { (id, label) -> id to stringResource(label) } for ((id, name) in ControllerPrefs.mappable) { 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 9c24f551cb..d81015d610 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -306,6 +306,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: if (steam && s.steamController in listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM)) { Note(stringResource(R.string.back_native_qam_hint)) } + PhysicalShortcutRows() } } if (tab == SheetTab.AUDIO && steam) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt new file mode 100644 index 0000000000..3ad5cea7a5 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt @@ -0,0 +1,189 @@ +package com.droiddeck.launcher.ui + +import android.util.Log +import android.view.KeyEvent +import android.view.Window +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.width +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.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.compose.ui.window.DialogWindowProvider +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.PhysicalShortcuts + +@Composable +internal fun PhysicalShortcutRows( + onChanged: () -> Unit = {}, + modifierFor: (PhysicalShortcuts.Action) -> Modifier = { Modifier }, +) { + val context = LocalContext.current + var bindings by remember { mutableStateOf(PhysicalShortcuts.read(context)) } + var editing by remember { mutableStateOf(null) } + Column { + for (action in PhysicalShortcuts.Action.entries) { + val assigned = bindings.filter { it.action == action } + SettingsRow( + stringResource(action.label), + assigned.joinToString { "${it.button.label} · ${it.button.name}" }.ifEmpty { null }, + ) { + SecondaryButton( + stringResource(if (assigned.isEmpty()) R.string.game_settings_default else R.string.ctrl_custom), + compact = true, + modifier = modifierFor(action).width(LocalChipMinWidth.current) + .testTag("shortcuts-assign-${action.name}"), + ) { editing = action } + } + } + } + editing?.let { action -> + PhysicalShortcutsDialog(action, onDismiss = { editing = null }, onChanged = { + bindings = PhysicalShortcuts.read(context) + onChanged() + }) + } +} + +@Composable +internal fun PhysicalShortcutsDialog( + action: PhysicalShortcuts.Action, + onDismiss: () -> Unit, + onChanged: () -> Unit = {}, +) { + val context = LocalContext.current + val bindings = remember { PhysicalShortcuts.read(context) } + var candidate by remember { mutableStateOf(null) } + var listening by remember { mutableStateOf(true) } + var capturedDevice by remember { mutableStateOf(-1) } + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(dismissOnBackPress = !listening, usePlatformDefaultWidth = false), + ) { + CaptureShortcutKeys { event -> + if (listening && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0 && + (event.keyCode == KeyEvent.KEYCODE_BACK || event.keyCode == KeyEvent.KEYCODE_BUTTON_B)) { + listening = false + onDismiss() + true + } else if (!listening || PhysicalShortcuts.isVolumeKey(event)) { + false + } else { + if (candidate == null && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + PhysicalShortcuts.button(event)?.let { button -> + candidate = button + capturedDevice = event.deviceId + Log.i("PhysicalShortcuts", "capture device=${button.name} key=${event.keyCode} " + + "scan=${event.scanCode} source=0x${event.source.toString(16)}") + } + } else if (event.action == KeyEvent.ACTION_UP && event.deviceId == capturedDevice && + candidate?.matches(event) == true) { + listening = false + candidate?.let { button -> + if (bindings.none { it.button.sameInput(button) && it.action != action }) { + PhysicalShortcuts.assign(context, button, action) + onChanged() + onDismiss() + } + } + } + true + } + } + CompositionLocalProvider(LocalFrontFocus provides null) { + Surface( + shape = RoundedCornerShape(16.dp), + modifier = Modifier.padding(12.dp).widthIn(max = 560.dp).fillMaxWidth() + .heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp), + ) { + Column( + Modifier.verticalScroll(rememberScrollState()).padding(18.dp).controllerBack(onDismiss), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text(stringResource(R.string.shortcuts_capture, stringResource(action.label)), + style = MaterialTheme.typography.titleLarge) + val button = candidate + if (button == null) { + Text(stringResource(R.string.shortcuts_press)) + } else { + Text(stringResource(R.string.shortcuts_detected, button.name, button.label)) + if (listening) { + Text(stringResource(R.string.shortcuts_release)) + } else { + val replacements = bindings.filter { + it.button.sameInput(button) || (it.button.device == button.device && it.action == action) + } + for (conflict in replacements) { + Text("${conflict.button.label} · ${conflict.button.name}") + Text(stringResource(R.string.shortcuts_conflict, stringResource(conflict.action.label))) + } + SecondaryButton(stringResource(R.string.shortcuts_save), modifier = Modifier.testTag("shortcuts-save")) { + PhysicalShortcuts.assign(context, button, action) + onChanged() + onDismiss() + } + } + SecondaryButton(stringResource(R.string.shortcuts_retry), modifier = Modifier.testTag("shortcuts-retry")) { + candidate = null + capturedDevice = -1 + listening = true + } + } + Text(stringResource(R.string.shortcuts_limitations), style = MaterialTheme.typography.bodySmall) + for (binding in bindings.filter { it.action == action }) { + ActionRow( + stringResource(R.string.shortcuts_detected, binding.button.name, binding.button.label), + null, stringResource(R.string.ctrl_reset), { + PhysicalShortcuts.remove(context, binding) + onChanged() + onDismiss() + }, + modifier = Modifier.testTag("shortcuts-remove"), + ) + } + SecondaryButton(stringResource(R.string.common_close), modifier = Modifier.testTag("shortcuts-cancel"), + onClick = onDismiss) + } + } + } + } +} + +@Composable +private fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) { + val currentOnKey by rememberUpdatedState(onKey) + val window = (LocalView.current.parent as DialogWindowProvider).window + DisposableEffect(window) { + val previous = window.callback + // Capture before dialog navigation so Back and gamepad buttons can be assigned. + window.callback = object : Window.Callback by previous { + override fun dispatchKeyEvent(event: KeyEvent): Boolean = + currentOnKey(event) || previous.dispatchKeyEvent(event) + } + onDispose { window.callback = previous } + } +} 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 5f165eeb01..57949a2f20 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -635,6 +635,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null, SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs) + PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") }) if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), stringResource(R.string.unfolded_controls_hint), a.unfoldedControls, chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls) diff --git a/app/src/main/res/values-ar/shortcuts.xml b/app/src/main/res/values-ar/shortcuts.xml new file mode 100644 index 0000000000..cc08ebc31b --- /dev/null +++ b/app/src/main/res/values-ar/shortcuts.xml @@ -0,0 +1,13 @@ + + + اختصارات الأزرار الفعلية + قائمة DroidDeck + تعيين: %1$s + اضغط على زر ثم حرره. يُحفظ التعيين تلقائيًا. + أفلت الزر للمتابعة. + %1$s: %2$s + هذا الزر معيّن بالفعل إلى: %1$s + إعادة تعيين + تجربة زر آخر + قد لا يتوفر زر الشاشة الرئيسية وبعض الأزرار الإضافية. + diff --git a/app/src/main/res/values-b+es+419/shortcuts.xml b/app/src/main/res/values-b+es+419/shortcuts.xml new file mode 100644 index 0000000000..7b643864a9 --- /dev/null +++ b/app/src/main/res/values-b+es+419/shortcuts.xml @@ -0,0 +1,13 @@ + + + Atajos de botones físicos + Menú de DroidDeck + Asignar: %1$s + Presiona y suelta un botón. La asignación se guarda automáticamente. + Suelta el botón para continuar. + %1$s: %2$s + Este botón ya está asignado a: %1$s + Reasignar + Probar otro botón + El botón Inicio y algunos botones adicionales pueden no estar disponibles. + diff --git a/app/src/main/res/values-bg/shortcuts.xml b/app/src/main/res/values-bg/shortcuts.xml new file mode 100644 index 0000000000..076068c113 --- /dev/null +++ b/app/src/main/res/values-bg/shortcuts.xml @@ -0,0 +1,13 @@ + + + Преки пътища с физически бутони + Меню на DroidDeck + Задаване: %1$s + Натиснете и отпуснете бутон. Назначението се запазва автоматично. + Отпуснете бутона, за да продължите. + %1$s: %2$s + Този бутон вече е зададен за: %1$s + Преназначаване + Опитайте друг бутон + Бутонът Начало и някои допълнителни бутони може да не са налични. + diff --git a/app/src/main/res/values-cs/shortcuts.xml b/app/src/main/res/values-cs/shortcuts.xml new file mode 100644 index 0000000000..fdc7e7877f --- /dev/null +++ b/app/src/main/res/values-cs/shortcuts.xml @@ -0,0 +1,13 @@ + + + Zkratky fyzických tlačítek + Nabídka DroidDeck + Přiřadit: %1$s + Stiskněte a uvolněte tlačítko. Přiřazení se uloží automaticky. + Pokračujte uvolněním tlačítka. + %1$s: %2$s + Toto tlačítko je již přiřazeno k: %1$s + Přeřadit + Zkusit jiné tlačítko + Tlačítko Domů a některá další tlačítka nemusí být dostupná. + diff --git a/app/src/main/res/values-da/shortcuts.xml b/app/src/main/res/values-da/shortcuts.xml new file mode 100644 index 0000000000..d95cac5a56 --- /dev/null +++ b/app/src/main/res/values-da/shortcuts.xml @@ -0,0 +1,13 @@ + + + Genveje til fysiske knapper + DroidDeck-menu + Tildel: %1$s + Tryk på en knap, og slip den. Tildelingen gemmes automatisk. + Slip knappen for at fortsætte. + %1$s: %2$s + Denne knap er allerede tildelt: %1$s + Tildel igen + Prøv en anden knap + Hjem-knappen og visse ekstra knapper er muligvis ikke tilgængelige. + diff --git a/app/src/main/res/values-de/shortcuts.xml b/app/src/main/res/values-de/shortcuts.xml new file mode 100644 index 0000000000..aa4dca5530 --- /dev/null +++ b/app/src/main/res/values-de/shortcuts.xml @@ -0,0 +1,13 @@ + + + Physische Tastenkürzel + DroidDeck-Menü + Zuweisen: %1$s + Drücke eine Taste und lasse sie los. Die Zuweisung wird automatisch gespeichert. + Lasse die Taste los, um fortzufahren. + %1$s: %2$s + Diese Taste ist bereits zugewiesen: %1$s + Neu zuweisen + Andere Taste versuchen + Die Home-Taste und einige Zusatztasten sind möglicherweise nicht verfügbar. + diff --git a/app/src/main/res/values-el/shortcuts.xml b/app/src/main/res/values-el/shortcuts.xml new file mode 100644 index 0000000000..a09be7c537 --- /dev/null +++ b/app/src/main/res/values-el/shortcuts.xml @@ -0,0 +1,13 @@ + + + Συντομεύσεις φυσικών κουμπιών + Μενού DroidDeck + Αντιστοίχιση: %1$s + Πατήστε και αφήστε ένα κουμπί. Η αντιστοίχιση αποθηκεύεται αυτόματα. + Αφήστε το κουμπί για συνέχεια. + %1$s: %2$s + Αυτό το κουμπί έχει ήδη αντιστοιχιστεί σε: %1$s + Επαναντιστοίχιση + Δοκιμή άλλου κουμπιού + Το κουμπί Αρχική και ορισμένα επιπλέον κουμπιά ενδέχεται να μην είναι διαθέσιμα. + diff --git a/app/src/main/res/values-es/shortcuts.xml b/app/src/main/res/values-es/shortcuts.xml new file mode 100644 index 0000000000..7db4cf53fa --- /dev/null +++ b/app/src/main/res/values-es/shortcuts.xml @@ -0,0 +1,13 @@ + + + Atajos de botones físicos + Menú de DroidDeck + Asignar: %1$s + Pulsa y suelta un botón. La asignación se guarda automáticamente. + Suelta el botón para continuar. + %1$s: %2$s + Este botón ya está asignado a: %1$s + Reasignar + Probar otro botón + El botón Inicio y algunos botones adicionales pueden no estar disponibles. + diff --git a/app/src/main/res/values-fi/shortcuts.xml b/app/src/main/res/values-fi/shortcuts.xml new file mode 100644 index 0000000000..b88d130f4b --- /dev/null +++ b/app/src/main/res/values-fi/shortcuts.xml @@ -0,0 +1,13 @@ + + + Fyysisten painikkeiden pikavalinnat + DroidDeck-valikko + Määritä: %1$s + Paina painiketta ja vapauta se. Määritys tallennetaan automaattisesti. + Jatka vapauttamalla painike. + %1$s: %2$s + Tämä painike on jo määritetty toimintoon: %1$s + Määritä uudelleen + Kokeile toista painiketta + Koti-painike ja jotkin lisäpainikkeet eivät ehkä ole käytettävissä. + diff --git a/app/src/main/res/values-fr/shortcuts.xml b/app/src/main/res/values-fr/shortcuts.xml new file mode 100644 index 0000000000..103fc2bb51 --- /dev/null +++ b/app/src/main/res/values-fr/shortcuts.xml @@ -0,0 +1,13 @@ + + + Raccourcis des boutons physiques + Menu DroidDeck + Attribuer : %1$s + Appuyez sur un bouton puis relâchez-le. L’affectation est enregistrée automatiquement. + Relâchez le bouton pour continuer. + %1$s : %2$s + Ce bouton est déjà attribué à : %1$s + Réaffecter + Essayer un autre bouton + Le bouton Accueil et certains boutons supplémentaires peuvent être indisponibles. + diff --git a/app/src/main/res/values-hi/shortcuts.xml b/app/src/main/res/values-hi/shortcuts.xml new file mode 100644 index 0000000000..70b2dcb365 --- /dev/null +++ b/app/src/main/res/values-hi/shortcuts.xml @@ -0,0 +1,13 @@ + + + भौतिक बटन शॉर्टकट + DroidDeck मेनू + असाइन करें: %1$s + कोई बटन दबाकर छोड़ें। असाइनमेंट अपने आप सहेजा जाता है। + जारी रखने के लिए बटन छोड़ें। + %1$s: %2$s + यह बटन पहले से असाइन है: %1$s + फिर से असाइन करें + दूसरा बटन आज़माएँ + होम और कुछ अतिरिक्त बटन उपलब्ध नहीं हो सकते हैं। + diff --git a/app/src/main/res/values-hu/shortcuts.xml b/app/src/main/res/values-hu/shortcuts.xml new file mode 100644 index 0000000000..8f8ee108f2 --- /dev/null +++ b/app/src/main/res/values-hu/shortcuts.xml @@ -0,0 +1,13 @@ + + + Fizikai gombok parancsikonjai + DroidDeck-menü + Hozzárendelés: %1$s + Nyomj meg és engedj fel egy gombot. A hozzárendelés automatikusan mentődik. + A folytatáshoz engedje fel a gombot. + %1$s: %2$s + Ez a gomb már ehhez van rendelve: %1$s + Új hozzárendelés + Másik gomb kipróbálása + A Kezdőlap és egyes extra gombok nem feltétlenül érhetők el. + diff --git a/app/src/main/res/values-in/shortcuts.xml b/app/src/main/res/values-in/shortcuts.xml new file mode 100644 index 0000000000..b3e99c4dec --- /dev/null +++ b/app/src/main/res/values-in/shortcuts.xml @@ -0,0 +1,13 @@ + + + Pintasan tombol fisik + Menu DroidDeck + Tetapkan: %1$s + Tekan lalu lepaskan tombol. Penetapan disimpan otomatis. + Lepaskan tombol untuk melanjutkan. + %1$s: %2$s + Tombol ini sudah ditetapkan untuk: %1$s + Tetapkan ulang + Coba tombol lain + Tombol Beranda dan beberapa tombol tambahan mungkin tidak tersedia. + diff --git a/app/src/main/res/values-it/shortcuts.xml b/app/src/main/res/values-it/shortcuts.xml new file mode 100644 index 0000000000..7b77d0e123 --- /dev/null +++ b/app/src/main/res/values-it/shortcuts.xml @@ -0,0 +1,13 @@ + + + Scorciatoie dei pulsanti fisici + Menu DroidDeck + Assegna: %1$s + Premi e rilascia un pulsante. L’assegnazione viene salvata automaticamente. + Rilascia il pulsante per continuare. + %1$s: %2$s + Questo pulsante è già assegnato a: %1$s + Riassegna + Prova un altro pulsante + Il pulsante Home e alcuni pulsanti aggiuntivi potrebbero non essere disponibili. + diff --git a/app/src/main/res/values-ja/shortcuts.xml b/app/src/main/res/values-ja/shortcuts.xml new file mode 100644 index 0000000000..6890b83d1e --- /dev/null +++ b/app/src/main/res/values-ja/shortcuts.xml @@ -0,0 +1,13 @@ + + + 物理ボタンのショートカット + DroidDeck メニュー + 割り当て:%1$s + ボタンを押して離してください。割り当ては自動的に保存されます。 + ボタンを離して続行してください。 + %1$s:%2$s + このボタンはすでに次の操作に割り当てられています:%1$s + 再割り当て + 別のボタンを試す + ホームボタンや一部の追加ボタンは使用できない場合があります。 + diff --git a/app/src/main/res/values-ko/shortcuts.xml b/app/src/main/res/values-ko/shortcuts.xml new file mode 100644 index 0000000000..dd0457f4a2 --- /dev/null +++ b/app/src/main/res/values-ko/shortcuts.xml @@ -0,0 +1,13 @@ + + + 물리 버튼 바로가기 + DroidDeck 메뉴 + 지정: %1$s + 버튼을 눌렀다 놓으세요. 할당은 자동으로 저장됩니다. + 계속하려면 버튼을 놓으세요. + %1$s: %2$s + 이 버튼은 이미 다음 동작에 지정되어 있습니다: %1$s + 다시 할당 + 다른 버튼 시도 + 홈 버튼과 일부 추가 버튼은 사용할 수 없을 수 있습니다. + diff --git a/app/src/main/res/values-ms/shortcuts.xml b/app/src/main/res/values-ms/shortcuts.xml new file mode 100644 index 0000000000..63942381b4 --- /dev/null +++ b/app/src/main/res/values-ms/shortcuts.xml @@ -0,0 +1,13 @@ + + + Pintasan butang fizikal + Menu DroidDeck + Tetapkan: %1$s + Tekan dan lepaskan butang. Penetapan disimpan secara automatik. + Lepaskan butang untuk meneruskan. + %1$s: %2$s + Butang ini sudah ditetapkan kepada: %1$s + Tukar penetapan + Cuba butang lain + Butang Utama dan sesetengah butang tambahan mungkin tidak tersedia. + diff --git a/app/src/main/res/values-nb/shortcuts.xml b/app/src/main/res/values-nb/shortcuts.xml new file mode 100644 index 0000000000..712de7c6ee --- /dev/null +++ b/app/src/main/res/values-nb/shortcuts.xml @@ -0,0 +1,13 @@ + + + Snarveier for fysiske knapper + DroidDeck-meny + Tilordne: %1$s + Trykk på en knapp og slipp den. Tilordningen lagres automatisk. + Slipp knappen for å fortsette. + %1$s: %2$s + Denne knappen er allerede tilordnet: %1$s + Tilordne på nytt + Prøv en annen knapp + Hjem-knappen og enkelte ekstraknapper er kanskje ikke tilgjengelige. + diff --git a/app/src/main/res/values-nl/shortcuts.xml b/app/src/main/res/values-nl/shortcuts.xml new file mode 100644 index 0000000000..b76f6c6cb1 --- /dev/null +++ b/app/src/main/res/values-nl/shortcuts.xml @@ -0,0 +1,13 @@ + + + Snelkoppelingen voor fysieke knoppen + DroidDeck-menu + Toewijzen: %1$s + Druk op een knop en laat deze los. De toewijzing wordt automatisch opgeslagen. + Laat de knop los om door te gaan. + %1$s: %2$s + Deze knop is al toegewezen aan: %1$s + Opnieuw toewijzen + Andere knop proberen + De Home-knop en sommige extra knoppen zijn mogelijk niet beschikbaar. + diff --git a/app/src/main/res/values-pl/shortcuts.xml b/app/src/main/res/values-pl/shortcuts.xml new file mode 100644 index 0000000000..665ec3f842 --- /dev/null +++ b/app/src/main/res/values-pl/shortcuts.xml @@ -0,0 +1,13 @@ + + + Skróty przycisków fizycznych + Menu DroidDeck + Przypisz: %1$s + Naciśnij i zwolnij przycisk. Przypisanie zostanie zapisane automatycznie. + Zwolnij przycisk, aby kontynuować. + %1$s: %2$s + Ten przycisk jest już przypisany do: %1$s + Przypisz ponownie + Wypróbuj inny przycisk + Przycisk Home i niektóre dodatkowe przyciski mogą być niedostępne. + diff --git a/app/src/main/res/values-pt-rPT/shortcuts.xml b/app/src/main/res/values-pt-rPT/shortcuts.xml new file mode 100644 index 0000000000..7e9f6cf242 --- /dev/null +++ b/app/src/main/res/values-pt-rPT/shortcuts.xml @@ -0,0 +1,13 @@ + + + Atalhos de botões físicos + Menu do DroidDeck + Atribuir: %1$s + Prima e solte um botão. A atribuição é guardada automaticamente. + Solte o botão para continuar. + %1$s: %2$s + Este botão já está atribuído a: %1$s + Reatribuir + Experimentar outro botão + O botão Início e alguns botões adicionais podem não estar disponíveis. + diff --git a/app/src/main/res/values-pt/shortcuts.xml b/app/src/main/res/values-pt/shortcuts.xml new file mode 100644 index 0000000000..cd9abed5ca --- /dev/null +++ b/app/src/main/res/values-pt/shortcuts.xml @@ -0,0 +1,13 @@ + + + Atalhos de botões físicos + Menu do DroidDeck + Atribuir: %1$s + Pressione e solte um botão. A atribuição é salva automaticamente. + Solte o botão para continuar. + %1$s: %2$s + Este botão já está atribuído a: %1$s + Reatribuir + Testar outro botão + O botão Início e alguns botões extras podem não estar disponíveis. + diff --git a/app/src/main/res/values-ro/shortcuts.xml b/app/src/main/res/values-ro/shortcuts.xml new file mode 100644 index 0000000000..7760131822 --- /dev/null +++ b/app/src/main/res/values-ro/shortcuts.xml @@ -0,0 +1,13 @@ + + + Scurtături pentru butoane fizice + Meniul DroidDeck + Atribuie: %1$s + Apasă și eliberează un buton. Atribuirea se salvează automat. + Eliberează butonul pentru a continua. + %1$s: %2$s + Acest buton este deja atribuit pentru: %1$s + Reatribuie + Încearcă alt buton + Butonul Acasă și unele butoane suplimentare pot fi indisponibile. + diff --git a/app/src/main/res/values-ru/shortcuts.xml b/app/src/main/res/values-ru/shortcuts.xml new file mode 100644 index 0000000000..783abb4bda --- /dev/null +++ b/app/src/main/res/values-ru/shortcuts.xml @@ -0,0 +1,13 @@ + + + Действия физических кнопок + Меню DroidDeck + Назначить: %1$s + Нажмите и отпустите кнопку. Назначение сохранится автоматически. + Отпустите кнопку, чтобы продолжить. + %1$s: %2$s + Эта кнопка уже назначена для: %1$s + Переназначить + Попробовать другую кнопку + Кнопка «Домой» и некоторые дополнительные кнопки могут быть недоступны. + diff --git a/app/src/main/res/values-sv/shortcuts.xml b/app/src/main/res/values-sv/shortcuts.xml new file mode 100644 index 0000000000..c74ad141d8 --- /dev/null +++ b/app/src/main/res/values-sv/shortcuts.xml @@ -0,0 +1,13 @@ + + + Genvägar för fysiska knappar + DroidDeck-meny + Tilldela: %1$s + Tryck på en knapp och släpp den. Tilldelningen sparas automatiskt. + Släpp knappen för att fortsätta. + %1$s: %2$s + Den här knappen är redan tilldelad: %1$s + Tilldela igen + Prova en annan knapp + Hemknappen och vissa extraknappar kanske inte är tillgängliga. + diff --git a/app/src/main/res/values-th/shortcuts.xml b/app/src/main/res/values-th/shortcuts.xml new file mode 100644 index 0000000000..c9c7a10779 --- /dev/null +++ b/app/src/main/res/values-th/shortcuts.xml @@ -0,0 +1,13 @@ + + + ทางลัดปุ่มจริง + เมนู DroidDeck + กำหนด: %1$s + กดปุ่มแล้วปล่อย การกำหนดปุ่มจะบันทึกโดยอัตโนมัติ + ปล่อยปุ่มเพื่อดำเนินการต่อ + %1$s: %2$s + ปุ่มนี้ถูกกำหนดไว้แล้วสำหรับ: %1$s + กำหนดใหม่ + ลองปุ่มอื่น + ปุ่มโฮมและปุ่มพิเศษบางปุ่มอาจไม่พร้อมใช้งาน + diff --git a/app/src/main/res/values-tr/shortcuts.xml b/app/src/main/res/values-tr/shortcuts.xml new file mode 100644 index 0000000000..b279d0a04f --- /dev/null +++ b/app/src/main/res/values-tr/shortcuts.xml @@ -0,0 +1,13 @@ + + + Fiziksel düğme kısayolları + DroidDeck menüsü + Ata: %1$s + Bir düğmeye basıp bırakın. Atama otomatik olarak kaydedilir. + Devam etmek için düğmeyi bırakın. + %1$s: %2$s + Bu düğme zaten şuna atanmış: %1$s + Yeniden ata + Başka düğme dene + Ana ekran düğmesi ve bazı ek düğmeler kullanılamayabilir. + diff --git a/app/src/main/res/values-uk/shortcuts.xml b/app/src/main/res/values-uk/shortcuts.xml new file mode 100644 index 0000000000..f1085d0702 --- /dev/null +++ b/app/src/main/res/values-uk/shortcuts.xml @@ -0,0 +1,13 @@ + + + Дії фізичних кнопок + Меню DroidDeck + Призначити: %1$s + Натисніть і відпустіть кнопку. Призначення збережеться автоматично. + Відпустіть кнопку, щоб продовжити. + %1$s: %2$s + Ця кнопка вже призначена для: %1$s + Перепризначити + Спробувати іншу кнопку + Кнопка «Додому» та деякі додаткові кнопки можуть бути недоступні. + diff --git a/app/src/main/res/values-vi/shortcuts.xml b/app/src/main/res/values-vi/shortcuts.xml new file mode 100644 index 0000000000..fccc48168d --- /dev/null +++ b/app/src/main/res/values-vi/shortcuts.xml @@ -0,0 +1,13 @@ + + + Phím tắt nút vật lý + Menu DroidDeck + Gán: %1$s + Nhấn và thả một nút. Gán nút được lưu tự động. + Thả nút để tiếp tục. + %1$s: %2$s + Nút này đã được gán cho: %1$s + Gán lại + Thử nút khác + Nút Home và một số nút bổ sung có thể không khả dụng. + diff --git a/app/src/main/res/values-zh-rCN/shortcuts.xml b/app/src/main/res/values-zh-rCN/shortcuts.xml new file mode 100644 index 0000000000..53fa9d7660 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/shortcuts.xml @@ -0,0 +1,13 @@ + + + 实体按键快捷操作 + DroidDeck 菜单 + 分配:%1$s + 按下并松开一个按钮,分配将自动保存。 + 松开按键以继续。 + %1$s:%2$s + 此按键已分配给:%1$s + 重新分配 + 尝试其他按键 + 主屏幕按钮和部分额外按钮可能无法使用。 + diff --git a/app/src/main/res/values-zh-rHK/shortcuts.xml b/app/src/main/res/values-zh-rHK/shortcuts.xml new file mode 100644 index 0000000000..4a4d7f1700 --- /dev/null +++ b/app/src/main/res/values-zh-rHK/shortcuts.xml @@ -0,0 +1,13 @@ + + + 實體按鍵快捷操作 + DroidDeck 選單 + 指派:%1$s + 按下並放開一個按鈕,指派會自動儲存。 + 放開按鍵以繼續。 + %1$s:%2$s + 此按鍵已指派給:%1$s + 重新指派 + 嘗試其他按鍵 + 主畫面按鈕及部分額外按鈕可能無法使用。 + diff --git a/app/src/main/res/values-zh-rTW/shortcuts.xml b/app/src/main/res/values-zh-rTW/shortcuts.xml new file mode 100644 index 0000000000..4a4d7f1700 --- /dev/null +++ b/app/src/main/res/values-zh-rTW/shortcuts.xml @@ -0,0 +1,13 @@ + + + 實體按鍵快捷操作 + DroidDeck 選單 + 指派:%1$s + 按下並放開一個按鈕,指派會自動儲存。 + 放開按鍵以繼續。 + %1$s:%2$s + 此按鍵已指派給:%1$s + 重新指派 + 嘗試其他按鍵 + 主畫面按鈕及部分額外按鈕可能無法使用。 + diff --git a/app/src/main/res/values/shortcuts.xml b/app/src/main/res/values/shortcuts.xml new file mode 100644 index 0000000000..d7e7a26d54 --- /dev/null +++ b/app/src/main/res/values/shortcuts.xml @@ -0,0 +1,13 @@ + + + Physical button shortcuts + DroidDeck menu + Assign: %1$s + Press and release a button. Your assignment saves automatically. + Release the button to continue. + %1$s: %2$s + This button is already assigned to: %1$s + Reassign + Try another button + Home and some extra buttons may be unavailable. + diff --git a/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt new file mode 100644 index 0000000000..d41aabbdd0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/PhysicalShortcutsTest.kt @@ -0,0 +1,254 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.hardware.input.InputManager +import android.view.InputDevice +import android.view.KeyCharacterMap +import android.view.KeyEvent +import com.droiddeck.launcher.input.PhysicalShortcuts.Action +import org.json.JSONArray +import org.json.JSONObject +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.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.InputDeviceBuilder + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class]) +class PhysicalShortcutsTest { + private val context: Context get() = RuntimeEnvironment.getApplication() + private val router = PhysicalShortcutRouter() + private val actions = mutableListOf() + private lateinit var pad: InputDevice + + @Before fun setUp() { + ControllerPrefs.prefs(context).edit().clear().commit() + pad = device(10, "retroid") + } + + @Test fun defaultsDoNotInterceptAnyButton() { + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + for (code in listOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_BUTTON_MODE, + KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.KEYCODE_BUTTON_1)) { + assertFalse(route(key(code))) + assertFalse(route(key(code, KeyEvent.ACTION_UP))) + } + assertTrue(actions.isEmpty()) + } + + @Test fun assignmentPersistsAndConsumesTheWholePressWithoutRepeating() { + assign(key(), Action.STEAM) + assertEquals(listOf(PhysicalShortcuts.Binding(button(key()), Action.STEAM)), PhysicalShortcuts.read(context)) + assertTrue(route(key())) + assertTrue(route(key(repeat = 1))) + assertTrue(route(key(repeat = 2))) + assertTrue(route(key(action = KeyEvent.ACTION_UP))) + assertEquals(listOf(Action.STEAM), actions) + assertFalse(route(key(action = KeyEvent.ACTION_UP))) + } + + @Test fun releaseIsConsumedEvenIfAnActionChangedTheRoutingContextOrSettings() { + assign(key(), Action.DROIDDECK) + assertTrue(route(key())) + router.bindings = emptyList() + assertTrue(route(key(action = KeyEvent.ACTION_UP), enabled = false, steam = false)) + assertEquals(listOf(Action.DROIDDECK), actions) + } + + @Test fun aRepeatedDownWithoutAnInitialPressDoesNotTriggerAnAction() { + assign(key(), Action.QAM) + assertTrue(route(key(repeat = 1))) + assertTrue(route(key(action = KeyEvent.ACTION_UP))) + assertTrue(actions.isEmpty()) + } + + @Test fun disabledMappedConfirmLeavesTheWholePressForDrawerNavigation() { + assign(key(KeyEvent.KEYCODE_BUTTON_A), Action.DROIDDECK) + assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A), enabled = false)) + assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, repeat = 1), enabled = false)) + assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false)) + assertTrue(actions.isEmpty()) + } + + @Test fun mappedConfirmOpeningTheDrawerConsumesItsReleaseWithoutStayingHeld() { + assign(key(KeyEvent.KEYCODE_BUTTON_A), Action.DROIDDECK) + assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A))) + assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, repeat = 1), enabled = false)) + assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false)) + assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A), enabled = false)) + assertFalse(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP), enabled = false)) + assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A))) + assertTrue(route(key(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP))) + assertEquals(listOf(Action.DROIDDECK, Action.DROIDDECK), actions) + } + + @Test fun aResumePressKeepsItsRepeatsAndReleaseInTheResumePath() { + assign(key(), Action.STEAM) + assertFalse(route(key(), enabled = false)) + assertFalse(route(key(repeat = 1), enabled = false)) + assertFalse(route(key(action = KeyEvent.ACTION_UP), enabled = false)) + assertTrue(actions.isEmpty()) + assertTrue(route(key())) + assertEquals(listOf(Action.STEAM), actions) + } + + @Test fun steamActionsAreInactiveOutsideSteamAndAllActionsRespectDisabledContexts() { + for (action in Action.entries) { + assign(key(), action) + assertFalse(route(key(), enabled = false)) + assertFalse(route(key(action = KeyEvent.ACTION_UP), enabled = false)) + assertEquals(action == Action.DROIDDECK, route(key(), steam = false)) + route(key(action = KeyEvent.ACTION_UP), steam = false) + } + assertEquals(listOf(Action.DROIDDECK), actions) + } + + @Test fun reassigningAButtonReplacesItsPreviousAction() { + assign(key(), Action.STEAM) + assign(key(), Action.QAM) + assertEquals(listOf(Action.QAM), PhysicalShortcuts.read(context).map { it.action }) + assertTrue(route(key())) + assertEquals(listOf(Action.QAM), actions) + } + + @Test fun reassigningAnActionOnlyReplacesThatControllersBinding() { + val second = device(11, "bluetooth") + assign(key(), Action.STEAM) + assign(key(device = second), Action.STEAM) + assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.STEAM) + val saved = PhysicalShortcuts.read(context) + assertEquals(2, saved.size) + assertTrue(saved.any { it.button.sameInput(button(key(device = second))) }) + assertTrue(saved.any { it.button.sameInput(button(key(KeyEvent.KEYCODE_BUTTON_2))) }) + assertFalse(route(key())) + } + + @Test fun deviceIdentitySurvivesReconnectionButDoesNotMatchAnUnrelatedController() { + assign(key(), Action.QAM) + assertFalse(route(key(device = device(11, "other")))) + val reconnected = device(12, "retroid") + assertTrue(route(key(device = reconnected))) + assertEquals(listOf(Action.QAM), actions) + } + + @Test fun scanCodesDistinguishButtonsSharingAnAndroidKeyCode() { + assign(key(scan = 700), Action.STEAM) + assign(key(scan = 701), Action.QAM) + assertEquals(2, PhysicalShortcuts.read(context).size) + assertTrue(route(key(scan = 700))) + assertTrue(route(key(scan = 701))) + assertFalse(route(key(scan = 702))) + assertEquals(listOf(Action.STEAM, Action.QAM), actions) + } + + @Test fun keyboardLikeExtraButtonsCanBeExplicitlyAssignedWithoutChangingKeyboardDefaults() { + val keyboard = device(11, "m1-keyboard", InputDevice.SOURCE_KEYBOARD, InputDevice.KEYBOARD_TYPE_ALPHABETIC) + val m1 = key(KeyEvent.KEYCODE_F1, device = keyboard) + assertFalse(PadBridge.isControllerKeyEvent(m1)) + assign(m1, Action.STEAM) + assertTrue(route(m1)) + assertFalse(route(key(KeyEvent.KEYCODE_F2, device = keyboard))) + assertEquals(listOf(Action.STEAM), actions) + } + + @Test fun virtualAndSystemKeysCannotBeAssigned() { + val virtual = device(-1, "virtual") + assertNull(PhysicalShortcuts.button(key(device = virtual))) + for (code in listOf(KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_APP_SWITCH, + KeyEvent.KEYCODE_SLEEP, KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_VOLUME_UP, + KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE)) { + assertNull(PhysicalShortcuts.button(key(code))) + } + assertNull(PhysicalShortcuts.button(key(KeyEvent.KEYCODE_UNKNOWN, scan = 0))) + assertNotNull(PhysicalShortcuts.button(key(KeyEvent.KEYCODE_UNKNOWN, scan = 700))) + } + + @Test fun drawerDirectionalKeysRemainAvailableForNavigation() { + for (code in listOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT)) { + assertTrue(PhysicalShortcuts.isDrawerNavigationKey(key(code))) + } + assertFalse(PhysicalShortcuts.isDrawerNavigationKey(key(KeyEvent.KEYCODE_BUTTON_A))) + } + + @Test fun resetAndRemovalPreserveOtherControllerSettings() { + ControllerPrefs.setSelectSteam(context, true) + ControllerPrefs.setTarget(context, "a", "b") + assign(key(), Action.STEAM) + assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM) + PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).first()) + assertEquals(listOf(Action.QAM), PhysicalShortcuts.read(context).map { it.action }) + PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).single()) + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + assertTrue(ControllerPrefs.read(context).selectSteam) + assertEquals("b", ControllerPrefs.target(context, "a")) + assign(key(), Action.STEAM) + ControllerPrefs.resetAll(context) + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + } + + @Test fun disconnectAndPauseClearHeldButtons() { + assign(key(), Action.QAM) + assertTrue(route(key())) + router.onDeviceRemoved(pad.id) + assertFalse(route(key(action = KeyEvent.ACTION_UP))) + assertTrue(route(key())) + router.clear() + assertFalse(route(key(action = KeyEvent.ACTION_UP))) + assertTrue(route(key())) + assertEquals(listOf(Action.QAM, Action.QAM, Action.QAM), actions) + } + + @Test fun malformedPreferencesDoNotCrashInputDispatch() { + ControllerPrefs.prefs(context).edit().putString("physicalShortcuts", "invalid").commit() + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + } + + @Test fun malformedEntriesDoNotDiscardValidAssignmentsWhenSaving() { + assign(key(), Action.STEAM) + assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM) + val entries = JSONArray(ControllerPrefs.prefs(context).getString("physicalShortcuts", null)) + val damaged = JSONArray().put(entries.getJSONObject(0)).put(JSONObject().put("action", "STEAM")) + .put("not an object").put(entries.getJSONObject(1)) + ControllerPrefs.prefs(context).edit().putString("physicalShortcuts", damaged.toString()).commit() + assertEquals(listOf(Action.STEAM, Action.QAM), PhysicalShortcuts.read(context).map { it.action }) + assign(key(KeyEvent.KEYCODE_BUTTON_3), Action.DROIDDECK) + assertEquals(listOf(Action.STEAM, Action.QAM, Action.DROIDDECK), + PhysicalShortcuts.read(context).map { it.action }) + } + + @Test fun buttonSummaryKeepsTechnicalDetailsSeparate() { + val select = button(key(KeyEvent.KEYCODE_BUTTON_SELECT, scan = 314)) + val androidName = KeyEvent.keyCodeToString(KeyEvent.KEYCODE_BUTTON_SELECT) + assertEquals(androidName.removePrefix("KEYCODE_").removePrefix("BUTTON_"), select.label) + assertFalse(select.label.contains("(314)")) + } + + private fun assign(event: KeyEvent, action: Action) { + PhysicalShortcuts.assign(context, button(event), action) + router.bindings = PhysicalShortcuts.read(context) + } + + private fun button(event: KeyEvent) = requireNotNull(PhysicalShortcuts.button(event)) + + private fun route(event: KeyEvent, enabled: Boolean = true, steam: Boolean = true) = + router.onKey(event, enabled, steam) { actions.add(it) } + + private fun key(code: Int = KeyEvent.KEYCODE_BUTTON_1, action: Int = KeyEvent.ACTION_DOWN, + repeat: Int = 0, scan: Int = 700, device: InputDevice = pad): KeyEvent = + KeyEvent(100L, 100L, action, code, repeat, 0, device.id, scan, 0, device.sources) + + private fun device(id: Int, descriptor: String, sources: Int = InputDevice.SOURCE_GAMEPAD, + type: Int = InputDevice.KEYBOARD_TYPE_NONE): InputDevice { + val device = InputDeviceBuilder.newBuilder().setId(id).setName("Test $descriptor") + .setDescriptor(descriptor).setSources(sources).setKeyboardType(type) + .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build() + shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device) + return device + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt new file mode 100644 index 0000000000..a9afe50287 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialogTest.kt @@ -0,0 +1,253 @@ +package com.droiddeck.launcher.ui + +import android.app.Application +import android.content.res.Configuration +import android.hardware.input.InputManager +import android.view.InputDevice +import android.view.KeyCharacterMap +import android.view.KeyEvent +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.* +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.width +import androidx.compose.ui.Modifier +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.ControllerPrefs +import com.droiddeck.launcher.input.PadBridgeRoutingTest +import com.droiddeck.launcher.input.PhysicalShortcuts +import org.junit.Assert.* +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.InputDeviceBuilder +import org.robolectric.shadows.ShadowDialog +import java.util.Locale + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], application = Application::class, qualifiers = "w960dp-h640dp-land", + shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class]) +class PhysicalShortcutsDialogTest { + @get:Rule val compose = createRobolectricComposeRule() + private val context get() = RuntimeEnvironment.getApplication() + private lateinit var device: InputDevice + + @Before fun setUp() { + context.getSharedPreferences("controller", 0).edit().clear().commit() + device = InputDeviceBuilder.newBuilder().setId(10).setName("Retroid extra buttons") + .setDescriptor("retroid-extra").setSources(InputDevice.SOURCE_KEYBOARD) + .setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC) + .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build() + shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device) + } + + @Test fun assignmentSavesAutomaticallyOnRelease() { + var changes = 0 + compose.setContent { DroidDeckTheme { PhysicalShortcutRows(onChanged = { changes++ }) } } + assign(PhysicalShortcuts.Action.STEAM) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN) + compose.onNodeWithText(context.getString(R.string.shortcuts_release)).assertExists() + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + compose.runOnIdle { + val binding = PhysicalShortcuts.read(context).single() + assertEquals(KeyEvent.KEYCODE_F1, binding.button.keyCode) + assertEquals(PhysicalShortcuts.Action.STEAM, binding.action) + assertEquals(1, changes) + } + } + + @Test fun buttonMappingPageOpensPhysicalShortcutAssignments() { + compose.setContent { + DroidDeckTheme { ControllerMappingPage(emptyMap(), { _, _ -> }, {}, {}) } + } + compose.onNodeWithTag("shortcuts-assign-STEAM").assertExists() + compose.onNodeWithTag("shortcuts-assign-QAM").assertExists() + compose.onNodeWithTag("shortcuts-assign-DROIDDECK").assertExists() + } + + @Test fun backCancelsCaptureWithoutSaving() { + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.QAM) + send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_DOWN) + compose.onNodeWithTag("shortcuts-cancel").assertDoesNotExist() + compose.runOnIdle { + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + } + compose.onNodeWithTag("shortcuts-assign-QAM").assertExists() + } + + @Test fun controllerBCancelsCaptureWithoutSaving() { + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.QAM) + send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN) + compose.onNodeWithTag("shortcuts-assign-QAM").assertExists() + assertTrue(PhysicalShortcuts.read(context).isEmpty()) + } + + @Test fun closingConflictKeepsBothPreviousAssignments() { + PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))), + PhysicalShortcuts.Action.STEAM) + PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))), + PhysicalShortcuts.Action.QAM) + val previous = PhysicalShortcuts.read(context) + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.QAM) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertExists() + compose.onNodeWithTag("shortcuts-cancel").performScrollTo().performClick() + assertEquals(previous, PhysicalShortcuts.read(context)) + } + + @Test fun conflictingAssignmentIsNotReplacedUntilSave() { + PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))), + PhysicalShortcuts.Action.STEAM) + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.QAM) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithText(context.getString(R.string.shortcuts_conflict, + context.getString(R.string.drawer_steam_menu))).assertExists() + val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))) + compose.onAllNodesWithText("${button.label} · ${button.name}").assertCountEquals(2) + assertEquals(PhysicalShortcuts.Action.STEAM, PhysicalShortcuts.read(context).single().action) + compose.onNodeWithTag("shortcuts-save").performScrollTo().performClick() + compose.runOnIdle { assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action) } + } + + @Test fun removalRestoresDefaultAndPreservesOtherAssignmentsAndControllerSettings() { + ControllerPrefs.setSelectSteam(context, true) + PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))), + PhysicalShortcuts.Action.STEAM) + PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))), + PhysicalShortcuts.Action.QAM) + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.STEAM) + send(KeyEvent.KEYCODE_F3, KeyEvent.ACTION_DOWN) + compose.onNodeWithTag("shortcuts-remove").performScrollTo().performClick() + compose.runOnIdle { + assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action) + assertTrue(ControllerPrefs.read(context).selectSteam) + } + compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.game_settings_default)) + } + + @Test fun retryRecoversFromAMissingReleaseWithoutSavingTheOldButton() { + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.STEAM) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN) + compose.onNodeWithTag("shortcuts-retry").performScrollTo().performClick() + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))) + compose.onNodeWithText("${button.label} · ${button.name}").assertExists() + compose.runOnIdle { assertEquals(KeyEvent.KEYCODE_F2, PhysicalShortcuts.read(context).single().button.keyCode) } + } + + @Test fun longControllerNameDoesNotSqueezeTheMenuLabelInANarrowDrawer() { + val button = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_BUTTON_SELECT, KeyEvent.ACTION_DOWN))) + .copy(name = "Xbox Wireless Controller with a long device name") + PhysicalShortcuts.assign(context, button, PhysicalShortcuts.Action.STEAM) + compose.setContent { + DroidDeckTheme { + Box(Modifier.width(360.dp)) { PhysicalShortcutRows() } + } + } + val control = compose.onNodeWithTag("shortcuts-assign-STEAM").getUnclippedBoundsInRoot() + val label = compose.onNodeWithText(context.getString(R.string.drawer_steam_menu)).getUnclippedBoundsInRoot() + assertTrue(control.right - control.left < 200.dp) + assertTrue("Menu label must not wrap vertically: $label", label.bottom - label.top <= 48.dp) + compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.ctrl_custom)) + compose.onNodeWithText("${button.label} · ${button.name}").assertExists() + } + + @Test fun replacingSameActionsButtonSavesWithoutConfirmation() { + val oldButton = requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))) + PhysicalShortcuts.assign(context, oldButton, PhysicalShortcuts.Action.STEAM) + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.STEAM) + send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN) + assertEquals(oldButton, PhysicalShortcuts.read(context).single().button) + send(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + compose.runOnIdle { assertEquals(KeyEvent.KEYCODE_F2, PhysicalShortcuts.read(context).single().button.keyCode) } + } + + @Test + @Config(qualifiers = "de-rDE-w400dp-h850dp-port") + fun narrowLargeTextKeepsTranslatedCaptureReachableAndSavesOnRelease() { + compose.setContent { + val density = LocalDensity.current + CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) { + DroidDeckTheme { PhysicalShortcutRows() } + } + } + assign(PhysicalShortcuts.Action.DROIDDECK) + compose.onNodeWithText(context.getString(R.string.shortcuts_capture, + context.getString(R.string.shortcuts_dd_menu))).assertExists() + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithTag("shortcuts-save").assertDoesNotExist() + compose.runOnIdle { assertEquals(PhysicalShortcuts.Action.DROIDDECK, PhysicalShortcuts.read(context).single().action) } + } + + @Test + @Config(qualifiers = "ar-rEG-w400dp-h850dp-port") + fun rightToLeftDialogKeepsCancelReachable() { + compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } } + assign(PhysicalShortcuts.Action.QAM) + compose.onNodeWithTag("shortcuts-cancel").performScrollTo().assertIsDisplayed().performClick() + compose.onNodeWithTag("shortcuts-assign-QAM").assertExists() + } + + @Test fun everySupportedLanguageHasALocalizedShortcutTitleAndValidFormatArguments() { + val languages = mutableListOf() + context.resources.getXml(R.xml.locales_config).use { xml -> + while (xml.next() != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) { + if (xml.eventType == org.xmlpull.v1.XmlPullParser.START_TAG && xml.name == "locale") { + languages.add(xml.getAttributeValue("http://schemas.android.com/apk/res/android", "name")) + } + } + } + val english = context.getString(R.string.shortcuts_title) + for (language in languages) { + val config = Configuration(context.resources.configuration).apply { setLocale(Locale.forLanguageTag(language)) } + val localized = context.createConfigurationContext(config) + if (language != "en") assertNotEquals(language, english, localized.getString(R.string.shortcuts_title)) + assertTrue(localized.getString(R.string.shortcuts_capture, "ACTION").contains("ACTION")) + assertTrue(localized.getString(R.string.shortcuts_conflict, "ACTION").contains("ACTION")) + val detected = localized.getString(R.string.shortcuts_detected, "DEVICE", "BUTTON") + assertTrue(detected.contains("DEVICE")) + assertTrue(detected.contains("BUTTON")) + } + } + + private fun assign(action: PhysicalShortcuts.Action) { + compose.onNodeWithTag("shortcuts-assign-${action.name}").performClick() + } + + private fun send(code: Int, action: Int) { + compose.runOnIdle { + assertTrue(ShadowDialog.getLatestDialog().window!!.callback.dispatchKeyEvent(event(code, action))) + } + compose.waitForIdle() + } + + private fun event(code: Int, action: Int) = + KeyEvent(100L, 100L, action, code, 0, 0, device.id, 700, 0, InputDevice.SOURCE_KEYBOARD) +}