From ffd51da542207f6d3b547911b3ad04193a10fe3f Mon Sep 17 00:00:00 2001 From: Dlouxgit <57781857+Dlouxgit@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:22:09 +0800 Subject: [PATCH 1/6] Add editable mobile shortcut profiles for remote OS --- .../java/app/airhand/android/AirhandApp.kt | 4 + .../app/airhand/android/data/Shortcuts.kt | 90 ++++++++++++ .../android/ui/session/GameControls.kt | 4 +- .../app/airhand/android/ui/session/GameUi.kt | 22 +-- .../android/ui/session/PhoneSession.kt | 134 ++++++++++++------ .../app/src/main/res/values-zh/strings.xml | 6 + android/app/src/main/res/values/strings.xml | 6 + .../app/airhand/android/data/ShortcutsTest.kt | 23 +++ docs/android.md | 1 + docs/android.zh-CN.md | 1 + docs/ios.md | 1 + docs/ios.zh-CN.md | 1 + ios/Airhand/Session/GameEditor.swift | 14 +- ios/Airhand/Session/SessionMenu.swift | 72 +++++++--- ios/Airhand/Session/Shortcuts.swift | 109 ++++++++++++++ ios/Shared/L10n.swift | 4 + ios/Tests/ShortcutTests.swift | 10 ++ 17 files changed, 424 insertions(+), 78 deletions(-) create mode 100644 android/app/src/main/java/app/airhand/android/data/Shortcuts.kt create mode 100644 android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt create mode 100644 ios/Airhand/Session/Shortcuts.swift create mode 100644 ios/Tests/ShortcutTests.swift diff --git a/android/app/src/main/java/app/airhand/android/AirhandApp.kt b/android/app/src/main/java/app/airhand/android/AirhandApp.kt index 34b34e1d..1ed683f0 100644 --- a/android/app/src/main/java/app/airhand/android/AirhandApp.kt +++ b/android/app/src/main/java/app/airhand/android/AirhandApp.kt @@ -21,6 +21,7 @@ import app.airhand.android.data.HostCodeStore import app.airhand.android.data.PairingStore import app.airhand.android.data.Settings import app.airhand.android.data.SettingsStore +import app.airhand.android.data.ShortcutStore import app.airhand.android.host.HostService import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -39,6 +40,8 @@ class AirhandApp : Application() { /** 游戏按键的方案(控制电脑时叠在画面上的按钮) */ lateinit var games: GameStore private set + lateinit var shortcuts: ShortcutStore + private set lateinit var controller: ControllerClient private set lateinit var clipboard: Clipboard @@ -64,6 +67,7 @@ class AirhandApp : Application() { hostCodes = HostCodeStore(this) pairing = PairingStore(this) games = GameStore(this) + shortcuts = ShortcutStore(this) controller = ControllerClient(settings) clipboard = Clipboard(this) updater = Updater(this, settings) diff --git a/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt b/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt new file mode 100644 index 00000000..20c04186 --- /dev/null +++ b/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt @@ -0,0 +1,90 @@ +package app.airhand.android.data + +import android.content.Context +import androidx.annotation.StringRes +import app.airhand.android.R +import app.airhand.android.core.OsKind +import app.airhand.android.core.optStringOrNull +import org.json.JSONArray +import org.json.JSONObject +import java.io.File +import java.util.UUID + +/** Controller-side shortcut; codes are W3C KeyboardEvent.code values sent by the existing input protocol. */ +data class SavedShortcut(val id: String, val title: String?, val codes: List) { + fun toJson(): JSONObject = JSONObject().put("id", id).put("title", title ?: JSONObject.NULL).put("codes", JSONArray(codes)) + + companion object { + fun custom() = SavedShortcut("custom:${UUID.randomUUID()}", "", emptyList()) + + fun parse(o: JSONObject): SavedShortcut? { + val id = o.optString("id").takeIf { it.isNotBlank() } ?: return null + val a = o.optJSONArray("codes") ?: return null + val codes = (0 until a.length()).map { a.optString(it) } + if (codes.isEmpty() || codes.size > 4 || codes.any { !GameBind.valid(it) || it.startsWith("mouse:") || it.startsWith("wheel:") }) return null + return SavedShortcut(id, o.optStringOrNull("title")?.takeIf { it.isNotBlank() }, codes) + } + } +} + +data class ShortcutPreset(val id: String, @StringRes val label: Int, val codes: List) { + fun saved() = SavedShortcut(id, null, codes) +} + +object ShortcutDefaults { + fun forOs(os: OsKind): List = when (os) { + OsKind.MAC -> listOf( + ShortcutPreset("combo_cmd_tab", R.string.combo_cmd_tab, listOf("MetaLeft", "Tab")), + ShortcutPreset("combo_spotlight", R.string.combo_spotlight, listOf("MetaLeft", "Space")), + ShortcutPreset("combo_mission_control", R.string.combo_mission_control, listOf("ControlLeft", "ArrowUp")), + ShortcutPreset("combo_cmd_w", R.string.combo_cmd_w, listOf("MetaLeft", "KeyW")), + ShortcutPreset("combo_cmd_q", R.string.combo_cmd_q, listOf("MetaLeft", "KeyQ")), + ShortcutPreset("combo_force_quit", R.string.combo_force_quit, listOf("MetaLeft", "AltLeft", "Escape")), + ShortcutPreset("combo_lock_mac", R.string.combo_lock_mac, listOf("ControlLeft", "MetaLeft", "KeyQ")), + ShortcutPreset("combo_screenshot_mac", R.string.combo_screenshot_mac, listOf("MetaLeft", "ShiftLeft", "Digit5")), + ShortcutPreset("combo_copy_mac", R.string.combo_copy_mac, listOf("MetaLeft", "KeyC")), + ShortcutPreset("combo_paste_mac", R.string.combo_paste_mac, listOf("MetaLeft", "KeyV")), + ShortcutPreset("combo_undo_mac", R.string.combo_undo_mac, listOf("MetaLeft", "KeyZ")), + ) + OsKind.WINDOWS -> listOf( + ShortcutPreset("combo_ctrl_alt_del", R.string.combo_ctrl_alt_del, listOf("ControlLeft", "AltLeft", "Delete")), + ShortcutPreset("combo_alt_tab", R.string.combo_alt_tab, listOf("AltLeft", "Tab")), + ShortcutPreset("combo_win", R.string.combo_win, listOf("MetaLeft")), + ShortcutPreset("combo_win_d", R.string.combo_win_d, listOf("MetaLeft", "KeyD")), + ShortcutPreset("combo_win_e", R.string.combo_win_e, listOf("MetaLeft", "KeyE")), + ShortcutPreset("combo_win_l", R.string.combo_win_l, listOf("MetaLeft", "KeyL")), + ShortcutPreset("combo_alt_f4", R.string.combo_alt_f4, listOf("AltLeft", "F4")), + ShortcutPreset("combo_task_manager", R.string.combo_task_manager, listOf("ControlLeft", "ShiftLeft", "Escape")), + ShortcutPreset("combo_copy", R.string.combo_copy, listOf("ControlLeft", "KeyC")), + ShortcutPreset("combo_paste", R.string.combo_paste, listOf("ControlLeft", "KeyV")), + ShortcutPreset("combo_undo", R.string.combo_undo, listOf("ControlLeft", "KeyZ")), + ShortcutPreset("combo_print_screen", R.string.combo_print_screen, listOf("PrintScreen")), + ) + OsKind.LINUX -> listOf( + ShortcutPreset("combo_alt_tab", R.string.combo_alt_tab, listOf("AltLeft", "Tab")), + ShortcutPreset("combo_copy", R.string.combo_copy, listOf("ControlLeft", "KeyC")), + ShortcutPreset("combo_paste", R.string.combo_paste, listOf("ControlLeft", "KeyV")), + ShortcutPreset("combo_undo", R.string.combo_undo, listOf("ControlLeft", "KeyZ")), + ) + else -> emptyList() + } +} + +/** Profiles are keyed by remote OS so editing a Mac shortcut never changes the Windows list. */ +class ShortcutStore(context: Context) { + private val file = File(context.filesDir, "shortcuts.json") + + @Synchronized + fun list(os: OsKind): List { + val saved = runCatching { JSONObject(JsonFile.read(file) ?: "{}") }.getOrDefault(JSONObject()).optJSONArray(os.wire) + return saved?.let { a -> (0 until a.length()).mapNotNull { i -> a.optJSONObject(i)?.let { SavedShortcut.parse(it) } } } + ?: ShortcutDefaults.forOs(os).map(ShortcutPreset::saved) + } + + @Synchronized + fun save(os: OsKind, items: List) { + val profiles = runCatching { JSONObject(JsonFile.read(file) ?: "{}") }.getOrDefault(JSONObject()) + profiles.put(os.wire, JSONArray(items.map(SavedShortcut::toJson))) + JsonFile.write(file, profiles.toString()) + } +} diff --git a/android/app/src/main/java/app/airhand/android/ui/session/GameControls.kt b/android/app/src/main/java/app/airhand/android/ui/session/GameControls.kt index 91203471..a7744899 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/GameControls.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/GameControls.kt @@ -356,12 +356,12 @@ object GameKeys { Group(R.string.game_group_mouse, GameBind.MOUSE_BUTTONS.map(GameBind::mouse) + listOf(GameBind.WHEEL_UP, GameBind.WHEEL_DOWN)), Group( R.string.game_group_common, - listOf("Space", "ShiftLeft", "ControlLeft", "AltLeft", "Tab", "Escape", "Enter", "Backspace", "CapsLock", "Backquote", "ShiftRight", "ControlRight", "AltRight"), + listOf("Space", "ShiftLeft", "ControlLeft", "AltLeft", "MetaLeft", "Tab", "Escape", "Enter", "Backspace", "CapsLock", "Backquote", "ShiftRight", "ControlRight", "AltRight", "MetaRight"), ), Group(R.string.game_group_letters, "QWERTYUIOPASDFGHJKLZXCVBNM".map { "Key$it" }), Group(R.string.game_group_digits, (1..9).map { "Digit$it" } + listOf("Digit0", "Minus", "Equal")), Group(R.string.game_group_function, (1..12).map { "F$it" }), - Group(R.string.game_group_nav, listOf("ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Insert", "Delete", "Home", "End", "PageUp", "PageDown")), + Group(R.string.game_group_nav, listOf("ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Insert", "Delete", "Home", "End", "PageUp", "PageDown", "PrintScreen")), Group(R.string.game_group_symbols, listOf("BracketLeft", "BracketRight", "Backslash", "Semicolon", "Quote", "Comma", "Period", "Slash")), Group( R.string.game_group_numpad, diff --git a/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt b/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt index 2bb2dc54..7881245f 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt @@ -701,15 +701,19 @@ private fun ColumnScope.LayoutPanel(ed: LayoutEditor) { */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable -private fun KeyPicker( +internal fun KeyPicker( initial: List, onStick: ((List) -> Unit)?, onPick: (List) -> Unit, onDismiss: () -> Unit, + keyboardOnly: Boolean = false, + macKeys: Boolean = false, + maxKeys: Int = GameBind.MAX_BINDS, ) { val text = strings() - var combo by remember { mutableStateOf(initial.size > 1) } - val chosen = remember { mutableStateListOf().apply { if (initial.size > 1) addAll(initial) } } + fun keyName(code: String) = if (macKeys && code in listOf("MetaLeft", "MetaRight")) "⌘" else GameKeys.label(code, text) + var combo by remember { mutableStateOf(keyboardOnly || initial.size > 1) } + val chosen = remember { mutableStateListOf().apply { if (keyboardOnly || initial.size > 1) addAll(initial) } } ModalBottomSheet( onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), @@ -727,7 +731,7 @@ private fun KeyPicker( style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f), ) - FilterChip( + if (!keyboardOnly) FilterChip( selected = combo, onClick = { combo = !combo @@ -738,13 +742,13 @@ private fun KeyPicker( } if (combo) { Text( - stringResource(R.string.game_pick_combo_desc, GameBind.MAX_BINDS), + stringResource(R.string.game_pick_combo_desc, maxKeys), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Row(Modifier.padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) { Text( - if (chosen.isEmpty()) "—" else GameKeys.label(chosen, text), + if (chosen.isEmpty()) "—" else chosen.joinToString("+") { keyName(it) }, style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f), ) @@ -759,20 +763,20 @@ private fun KeyPicker( KeyCap(stringResource(R.string.game_stick) + " · ↑←↓→") { onStick(GameBind.ARROWS) } } } - GameKeys.groups.forEach { g -> + GameKeys.groups.filter { !keyboardOnly || it.title != R.string.game_group_mouse }.forEach { g -> GroupTitle(stringResource(g.title)) FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { g.tokens.forEach { t -> val i = chosen.indexOf(t) KeyCap( - GameKeys.label(t, text), + keyName(t), selected = if (combo) i >= 0 else initial == listOf(t), badge = if (combo && i >= 0) "${i + 1}" else null, ) { when { !combo -> onPick(listOf(t)) i >= 0 -> chosen.removeAt(i) - chosen.size < GameBind.MAX_BINDS -> chosen += t + chosen.size < maxKeys -> chosen += t } } } diff --git a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt index b6acc2ab..df4936fd 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt @@ -55,6 +55,7 @@ import androidx.compose.material.icons.automirrored.outlined.VolumeOff import androidx.compose.material.icons.automirrored.outlined.VolumeUp import androidx.compose.material.icons.outlined.WarningAmber import androidx.compose.material3.Button +import androidx.compose.material3.AlertDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip import androidx.compose.material3.HorizontalDivider @@ -64,11 +65,13 @@ import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.RadioButton import androidx.compose.material3.Slider import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect @@ -112,6 +115,8 @@ import app.airhand.android.core.Preset import app.airhand.android.core.PrivacyState import app.airhand.android.core.SystemAction import app.airhand.android.data.Settings +import app.airhand.android.data.SavedShortcut +import app.airhand.android.data.ShortcutDefaults import app.airhand.android.data.TouchMode import app.airhand.android.data.WheelMode import app.airhand.android.ui.ConfirmDialog @@ -800,38 +805,6 @@ private fun SubPage(title: String, onBack: () -> Unit, content: @Composable () - content() } -private data class Combo(val label: Int, val codes: List) - -private fun combos(os: OsKind): List = when (os) { - OsKind.MAC -> listOf( - Combo(R.string.combo_cmd_tab, listOf("MetaLeft", "Tab")), - Combo(R.string.combo_spotlight, listOf("MetaLeft", "Space")), - Combo(R.string.combo_mission_control, listOf("ControlLeft", "ArrowUp")), - Combo(R.string.combo_cmd_w, listOf("MetaLeft", "KeyW")), - Combo(R.string.combo_cmd_q, listOf("MetaLeft", "KeyQ")), - Combo(R.string.combo_force_quit, listOf("MetaLeft", "AltLeft", "Escape")), - Combo(R.string.combo_lock_mac, listOf("ControlLeft", "MetaLeft", "KeyQ")), - Combo(R.string.combo_screenshot_mac, listOf("MetaLeft", "ShiftLeft", "Digit5")), - Combo(R.string.combo_copy_mac, listOf("MetaLeft", "KeyC")), - Combo(R.string.combo_paste_mac, listOf("MetaLeft", "KeyV")), - Combo(R.string.combo_undo_mac, listOf("MetaLeft", "KeyZ")), - ) - else -> listOf( - Combo(R.string.combo_ctrl_alt_del, listOf("ControlLeft", "AltLeft", "Delete")), - Combo(R.string.combo_alt_tab, listOf("AltLeft", "Tab")), - Combo(R.string.combo_win, listOf("MetaLeft")), - Combo(R.string.combo_win_d, listOf("MetaLeft", "KeyD")), - Combo(R.string.combo_win_e, listOf("MetaLeft", "KeyE")), - Combo(R.string.combo_win_l, listOf("MetaLeft", "KeyL")), - Combo(R.string.combo_alt_f4, listOf("AltLeft", "F4")), - Combo(R.string.combo_task_manager, listOf("ControlLeft", "ShiftLeft", "Escape")), - Combo(R.string.combo_copy, listOf("ControlLeft", "KeyC")), - Combo(R.string.combo_paste, listOf("ControlLeft", "KeyV")), - Combo(R.string.combo_undo, listOf("ControlLeft", "KeyZ")), - Combo(R.string.combo_print_screen, listOf("PrintScreen")), - ) -} - /** 控制 Mac 时互换外接键盘的 Ctrl 和 ⌘:只换键盘上的键,下面的快捷键和键盘上方的特殊键不变。按设备记住 */ @Composable private fun SwapCtrlCommand(session: RemoteSession) { @@ -851,16 +824,97 @@ private fun SwapCtrlCommand(session: RemoteSession) { @Composable private fun Shortcuts(os: OsKind, onSend: (List) -> Unit) { - combos(os).forEach { c -> - Text( - stringResource(c.label), - style = MaterialTheme.typography.bodyLarge, - modifier = Modifier - .fillMaxWidth() - .clickable { onSend(c.codes) } - .padding(horizontal = 24.dp, vertical = 14.dp), + if (os !in listOf(OsKind.MAC, OsKind.WINDOWS, OsKind.LINUX)) return + val store = AirhandApp.instance.shortcuts + val context = LocalContext.current + var items by remember(os) { mutableStateOf(store.list(os)) } + var editing by remember(os) { mutableStateOf(false) } + var selected by remember(os) { mutableStateOf(null) } + var picking by remember(os) { mutableStateOf(false) } + var title by remember(os) { mutableStateOf("") } + var codes by remember(os) { mutableStateOf(emptyList()) } + val labels = remember(os) { ShortcutDefaults.forOs(os).associate { it.id to it.label } } + fun persist(next: List) { + items = next + store.save(os, next) + } + fun open(item: SavedShortcut) { + selected = item + title = item.title ?: labels[item.id]?.let { context.getString(it) }.orEmpty() + codes = item.codes + } + + Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = { open(SavedShortcut.custom()) }) { Text(stringResource(R.string.shortcut_add)) } + Spacer(Modifier.weight(1f)) + TextButton(onClick = { editing = !editing }) { + Text(stringResource(if (editing) R.string.shortcut_done else R.string.shortcut_reorder)) + } + } + items.forEachIndexed { index, item -> + Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + item.title ?: labels[item.id]?.let { stringResource(it) } ?: item.id, + style = MaterialTheme.typography.bodyLarge, + modifier = Modifier.weight(1f).clickable(enabled = !editing) { onSend(item.codes) } + .padding(horizontal = 8.dp, vertical = 12.dp), + ) + if (editing) { + TextButton(onClick = { open(item) }) { Text(stringResource(R.string.shortcut_edit)) } + TextButton(onClick = { + val next = items.toMutableList() + next.add(index - 1, next.removeAt(index)) + persist(next) + }, enabled = index > 0) { Text("↑") } + TextButton(onClick = { + val next = items.toMutableList() + next.add(index + 1, next.removeAt(index)) + persist(next) + }, enabled = index < items.lastIndex) { Text("↓") } + if (item.id.startsWith("custom:")) { + IconButton(onClick = { persist(items.filterNot { it.id == item.id }) }) { + Icon(Icons.Outlined.Close, contentDescription = stringResource(R.string.delete)) + } + } + } + } + } + if (selected != null && !picking) { + AlertDialog( + onDismissRequest = { selected = null }, + title = { Text(stringResource(R.string.shortcut_edit)) }, + text = { + Column { + OutlinedTextField(value = title, onValueChange = { title = it }, label = { Text(stringResource(R.string.shortcut_name)) }) + TextButton(onClick = { picking = true }) { + Text(if (codes.isEmpty()) stringResource(R.string.shortcut_pick) else codes.joinToString("+") { + if (os == OsKind.MAC && it in listOf("MetaLeft", "MetaRight")) "⌘" else GameKeys.label(it) { id -> context.getString(id) } + }) + } + } + }, + confirmButton = { + TextButton(onClick = { + val item = selected ?: return@TextButton + val name = title.trim() + val defaultName = labels[item.id]?.let { context.getString(it) } + val changed = item.copy(title = name.takeUnless { it == defaultName }, codes = codes) + persist(if (items.any { it.id == item.id }) items.map { if (it.id == item.id) changed else it } else items + changed) + selected = null + }, enabled = title.isNotBlank() && codes.isNotEmpty()) { Text(stringResource(R.string.save)) } + }, + dismissButton = { TextButton(onClick = { selected = null }) { Text(stringResource(R.string.cancel)) } }, ) } + if (picking) KeyPicker( + initial = codes, + onStick = null, + onPick = { codes = it; picking = false }, + onDismiss = { picking = false }, + keyboardOnly = true, + macKeys = os == OsKind.MAC, + maxKeys = 4, + ) } /** 系统操作的名字 */ diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml index 80cc5366..bb6e358b 100644 --- a/android/app/src/main/res/values-zh/strings.xml +++ b/android/app/src/main/res/values-zh/strings.xml @@ -429,6 +429,12 @@ 菜单 → 游戏按键 → 编辑布局:拖动摆放、换按键、调大小,也可以自己添加。 + 添加快捷键 + 编辑 + 名称 + 选择按键 + 调整顺序 + 完成 Ctrl + Alt + Del Alt + Tab 切换窗口 Win 开始菜单 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index d42196d7..5d6ad3be 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -436,6 +436,12 @@ Menu → Game keys → Edit layout: move buttons, change keys and sizes, add your own. + Add shortcut + Edit + Name + Choose keys + Reorder + Done Ctrl + Alt + Del Alt + Tab switch windows Win Start menu diff --git a/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt b/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt new file mode 100644 index 00000000..22567a9f --- /dev/null +++ b/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt @@ -0,0 +1,23 @@ +package app.airhand.android.data + +import app.airhand.android.core.OsKind +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ShortcutsTest { + @Test fun copyUsesTheRemoteOperatingSystem() { + assertEquals(listOf("MetaLeft", "KeyC"), ShortcutDefaults.forOs(OsKind.MAC).first { it.id == "combo_copy_mac" }.codes) + assertEquals(listOf("ControlLeft", "KeyC"), ShortcutDefaults.forOs(OsKind.WINDOWS).first { it.id == "combo_copy" }.codes) + assertEquals(listOf("ControlLeft", "KeyC"), ShortcutDefaults.forOs(OsKind.LINUX).first { it.id == "combo_copy" }.codes) + } + + @Test fun savedShortcutRejectsNonKeyboardInput() { + val bad = JSONObject().put("id", "custom:bad").put("title", "Bad").put("codes", JSONArray(listOf("mouse:left"))) + assertNull(SavedShortcut.parse(bad)) + val good = JSONObject().put("id", "custom:copy").put("title", "Copy").put("codes", JSONArray(listOf("MetaLeft", "KeyC"))) + assertEquals(listOf("MetaLeft", "KeyC"), SavedShortcut.parse(good)?.codes) + } +} diff --git a/docs/android.md b/docs/android.md index 38b411d6..0c1c7a1b 100644 --- a/docs/android.md +++ b/docs/android.md @@ -51,6 +51,7 @@ After you pinch to zoom the local view, a moment after your fingers stop the app - In trackpad mode the pointer is drawn locally (with the remote shape), so it moves without lag; in touch mode a fading circle shows where you tapped - **Keyboard**: the picture doesn't shrink: when it fits above the keyboard it moves up there, otherwise (landscape, or a phone held upright on the other side) the part around the pointer moves above the keyboard and follows the pointer, and everything moves back once the keyboard is hidden; in landscape the extra keys row is shorter and the stats overlay is hidden for the time being. A row of extra keys sits on top of the keyboard: Esc, Tab, Ctrl, Alt, Shift, Win (⌘ for Macs), arrows, Home / End, PgUp / PgDn, Del, F1–F12. Modifiers are sticky: tap once for the next key only, again to lock, again to release (tap Ctrl, then type c = Ctrl+C). While an IME composes (pinyin etc.) the text shows above the extra keys and is only sent once chosen - When controlling a phone, **Back / Home / Recents** keys sit below the picture (can be turned off in Settings), and Keyboard & input in the menu holds system actions: notifications, quick settings, screenshot, lock screen, power menu, volume (whichever the phone supports). For computers it lists shortcuts for the remote OS (Windows / macOS / Linux) +- When controlling a computer, you can add or edit keyboard combinations and move them up or down in Reorder mode. The list is saved locally on this Android device, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C - A connected mouse and keyboard map directly to the remote mouse and keyboard. Over the picture the mouse shows just the remote cursor, without the system pointer on top; in Settings its wheel can be reversed, set to a speed (5%–200%) and to **Adaptive** (the default: a slow single notch moves half as far, spinning quickly speeds up to twice as far) or **Linear** (the same distance for every notch), and **Smooth mouse scrolling** splits each notch into a few small steps about 16 ms apart (the same total; closer to a trackpad on a Mac). Ctrl / ⌘ shortcuts on the keyboard go to the remote computer even while an input method is active, and keys still held are let go when the menu opens or the app goes to the background. When controlling a Mac, **Swap Ctrl and ⌘ Command** under Keyboard & input in the menu makes the keyboard's Ctrl work as ⌘ and the Win key as Control (copy with Ctrl+C on a Windows keyboard); the extra keys row and the shortcuts in the menu don't change. It's off by default and remembered per computer, as in the desktop console - **Games**: when the remote computer hides its cursor (turning the camera in a game), trackpad slides and touch drags send how far you moved instead of a position, so the camera turns smoothly and doesn't stop at the edge of the picture; a connected mouse is captured (Android 8+). **Mouse lock** under Mouse & touch in the menu does the same all the time, e.g. for Macs, which can't report a hidden cursor. For games played with the keyboard, see game keys below - **Privacy mode**: under Video & display in the menu when the remote is Windows or a Mac (with a version that supports it). It blanks all of the remote monitors and disables its keyboard and mouse, so only you can see and control it; the switch shows the current state (turning on, on, why it isn't available), and a failure also shows at the top of the picture. It turns off by itself after you disconnect and stays on while reconnecting. See [Usage → Privacy mode](usage.md#privacy-mode) diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index 08ab2730..c0efd3fa 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -51,6 +51,7 @@ - 触控板模式下指针由本机画出来(形状来自对方),移动没有延迟;触屏模式点按处有一个淡出的圆作为反馈 - **键盘**:打开后画面不缩小:键盘上面放得下就挪到键盘上面,放不下(横屏、对方是竖着的手机)就把指针所在的地方挪到键盘上面,移动指针时跟着走,收起键盘后回到原来的位置;横屏时特殊键那一排矮一些,状态信息先不显示。键盘上面多一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12。修饰键是“粘滞”的:点一下只对下一个键有效,再点一下锁定,再点取消(例如点 Ctrl 再在键盘上打 c = Ctrl+C)。拼音等输入法组字时文字显示在特殊键上方,选好字才发过去 - 控制手机时画面下方有**返回 / 主页 / 最近任务**三个键(设置里可以关掉),菜单 → 键盘与输入里是通知栏、快捷设置、截屏、锁屏、电源菜单、音量等系统操作(对方手机能执行哪些就显示哪些);控制电脑时那里是按对方系统列出的快捷键(Windows / macOS / Linux) +- 控制电脑时,可以添加、编辑组合键,在“调整顺序”模式里用上下箭头排序。列表保存在这台 Android 设备上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C - 外接鼠标、键盘直接对应远端的鼠标、键盘。鼠标在画面上时只显示对方的光标,不会再叠一个系统指针。滚轮在设置里可以改速度(5%–200%)、方向和换算方式:**自适应加速**(默认:慢慢滚一格只走半格,连着快滚加速到两倍)或**固定线性**(每格一样远);还可以打开**平滑滚动**(每一格拆成几小步、约 16 ms 一步发过去,加起来不变,控制 Mac 时更像触控板)。键盘上 Ctrl / ⌘ 的组合键不会被本机的输入法拿走;打开菜单、切到后台时按着的键都会松开。控制 Mac 时,菜单 → 键盘与输入里的**互换 Ctrl 和 ⌘ Command** 让键盘上的 Ctrl 当 ⌘ 用、Win 键当 Ctrl 用(用 Windows 键盘按 Ctrl+C 复制);键盘上方的特殊键和菜单里的快捷键不变。默认关闭,每台电脑分别记住,和桌面控制台一样 - **游戏**:对方电脑隐藏了光标时(游戏里转视角),触控板的滑动、触屏的拖动发的是“移动了多少”而不是位置,视角转得顺,拖到画面边上也不会停;外接鼠标会被抓住(Android 8+)。菜单 → 鼠标与触控里的**锁定鼠标**让它一直这样,例如对方是 Mac(检测不到光标隐藏)时。要按键盘的游戏用下面的游戏按键 - **防窥模式**:对方是 Windows、Mac(而且是支持它的版本)时菜单 → 视频与画面里有它。打开后对方所有的显示器黑屏、键盘鼠标不起作用,只有你看得到、操作得了;开关下面写着现在怎么样(正在打开、开着、开不了的原因),没能打开时画面上方也会提示。断开连接后自动恢复,断线重连时接着保持。详见[使用说明 → 防窥模式](usage.zh-CN.md#防窥模式) diff --git a/docs/ios.md b/docs/ios.md index dbfd14af..24cf162e 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -42,6 +42,7 @@ After zooming in, Airhand asks the remote for a sharper picture once your finger - **Hardware keyboard**: physical keys are sent as key down / up (hold W in a game). Shortcuts the system keeps (⌘Tab, ⌘Space, Globe) can't be passed — use the shortcuts page - **Mouse / trackpad (iPad)**: move, left / right / middle / side buttons and the wheel map to the remote; the remote's cursor shape is drawn locally. When the remote hides its cursor (games) or “Lock mouse” is on, the pointer is **locked** and raw movement is sent; hold Esc to release (iPadOS only allows pointer lock in full screen) - Phones get **Back / Home / Recents** below the picture (can be turned off) and their system actions on the shortcuts page; computers get shortcuts for their OS +- For a remote computer, the shortcuts page lets you add or edit keyboard combinations and reorder them with Edit. The list is saved locally on this iPhone or iPad, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C - **Clipboard**: text copied on the remote lands in this device's clipboard; the menu can send this device's text to the remote clipboard or type it (iOS asks once to allow pasting) - **Files**: files copied on the remote show a prompt; “Save to Files” transfers them into Files › On My iPhone › Airhand. “Send files” puts files from this device on the remote clipboard to paste there (only a list is sent until pasted) - **Sound** with adaptive jitter buffer; **A/V sync** for videos; **microphone** forwarding to Windows, macOS 14.2+ and Linux hosts, with system echo cancellation diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index e9f9fa80..047530e2 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -43,6 +43,7 @@ - **外接键盘**:按物理键发(游戏里按住 W 就是按住),系统拦下的组合键(⌘Tab、⌘空格、地球键)传不过去 - **外接鼠标 / 触控板(iPad)**:移动、左右中键、侧键、滚轮直接对应远端;本机不显示系统指针,画的是对方的光标形状。对方隐藏了光标(游戏里转视角)或者打开了“锁定鼠标”时,**锁定指针**、发原始移动量;长按 Esc 放开(iPadOS 只在 App 全屏时允许锁定指针) - 控制手机时画面下方有**返回 / 主页 / 最近任务**(设置里可以关掉),快捷键页里是对方手机支持的系统操作;控制电脑时快捷键按对方系统列出(Windows / macOS / Linux) +- 控制电脑时,快捷键页可以添加、编辑组合键,点“编辑”后拖动调整顺序。列表保存在这台 iPhone 或 iPad 上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C - **剪贴板**:对方复制的文字自动放进本机剪贴板;菜单 → 剪贴板可以把本机复制的文字发到对方的剪贴板,或者直接打进对方的输入框(读本机剪贴板时 iOS 会问一次“允许粘贴”) - **文件**:对方复制的文件会提示“对方复制了 N 项”,点“保存到‘文件’”才传,存在“文件 › 我的 iPhone › Airhand”;菜单 → 发送文件选好本机的文件,放进对方的剪贴板,到对方那里粘贴(复制时只发清单,粘贴时才传) - **声音**:对方的声音同步过来(Opus + 自适应抖动缓冲,和桌面版同一套做法);**音画同步**看视频时打开。**麦克风**:对方能接收时(Windows、macOS 14.2+、Linux 被控端),菜单里打开就把本机的麦克风转发过去,开着系统的回声消除 diff --git a/ios/Airhand/Session/GameEditor.swift b/ios/Airhand/Session/GameEditor.swift index 98d8cdb9..4e80d369 100644 --- a/ios/Airhand/Session/GameEditor.swift +++ b/ios/Airhand/Session/GameEditor.swift @@ -376,13 +376,17 @@ struct LayoutSettings: View { struct KeyPicker: View { let initial: [String] let os: OsKind + let keyboardOnly: Bool + let maxKeys: Int let picked: ([String]) -> Void @State private var keys: [String] @Environment(\.dismiss) private var dismiss - init(initial: [String], os: OsKind, picked: @escaping ([String]) -> Void) { + init(initial: [String], os: OsKind, keyboardOnly: Bool = false, maxKeys: Int = 3, picked: @escaping ([String]) -> Void) { self.initial = initial self.os = os + self.keyboardOnly = keyboardOnly + self.maxKeys = maxKeys self.picked = picked _keys = State(initialValue: initial) } @@ -393,7 +397,7 @@ struct KeyPicker: View { ("game_group_letters", (65...90).map { "Key" + String(UnicodeScalar(UInt8($0))) }), ("game_group_digits", (0...9).map { "Digit\($0)" }), ("game_group_function", (1...12).map { "F\($0)" }), - ("game_group_nav", ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Insert", "Delete"]), + ("game_group_nav", ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Insert", "Delete", "PrintScreen"]), ("game_group_symbols", ["Backquote", "Minus", "Equal", "BracketLeft", "BracketRight", "Backslash", "Semicolon", "Quote", "Comma", "Period", "Slash"]), ] @@ -401,8 +405,8 @@ struct KeyPicker: View { NavigationStack { ScrollView { VStack(alignment: .leading, spacing: 18) { - Text(L.t("game_pick_combo")).font(.footnote).foregroundStyle(Theme.sub) - ForEach(groups, id: \.0) { title, list in + Text(L.t(keyboardOnly ? "shortcut_pick_hint" : "game_pick_combo")).font(.footnote).foregroundStyle(Theme.sub) + ForEach(groups.filter { !keyboardOnly || $0.0 != "game_group_mouse" }, id: \.0) { title, list in VStack(alignment: .leading, spacing: 8) { SectionTitle(text: L.t(title)) LazyVGrid(columns: [GridItem(.adaptive(minimum: 58), spacing: 8)], spacing: 8) { @@ -433,7 +437,7 @@ struct KeyPicker: View { private func chip(_ k: String) -> some View { let i = keys.firstIndex(of: k) return Button { - if let i { keys.remove(at: i) } else if keys.count < 3 { keys.append(k) } + if let i { keys.remove(at: i) } else if keys.count < maxKeys { keys.append(k) } } label: { ZStack(alignment: .topTrailing) { Text(GameItem.keyLabel(k, os: os)).font(.system(size: 14, weight: .semibold)).foregroundStyle(.white) diff --git a/ios/Airhand/Session/SessionMenu.swift b/ios/Airhand/Session/SessionMenu.swift index 2e3a3be4..71741245 100644 --- a/ios/Airhand/Session/SessionMenu.swift +++ b/ios/Airhand/Session/SessionMenu.swift @@ -183,26 +183,17 @@ struct SessionMenu: View { struct ShortcutsPage: View { let session: RemoteSession @Environment(\.dismiss) private var dismiss + @State private var shortcuts: [SavedShortcut] + @State private var editor: SavedShortcut? + private var editable: Bool { !session.os.isPhone && session.os != .unknown } - private var combos: [(String, [String])] { - switch session.os { - case .mac: - return [("combo_cmd_tab", ["MetaLeft", "Tab"]), ("combo_spotlight", ["MetaLeft", "Space"]), - ("combo_mission_control", ["ControlLeft", "ArrowUp"]), ("combo_cmd_w", ["MetaLeft", "KeyW"]), - ("combo_cmd_q", ["MetaLeft", "KeyQ"]), ("combo_force_quit", ["MetaLeft", "AltLeft", "Escape"]), - ("combo_lock_mac", ["ControlLeft", "MetaLeft", "KeyQ"]), ("combo_screenshot_mac", ["MetaLeft", "ShiftLeft", "Digit5"]), - ("combo_copy_mac", ["MetaLeft", "KeyC"]), ("combo_paste_mac", ["MetaLeft", "KeyV"]), ("combo_undo_mac", ["MetaLeft", "KeyZ"])] - case .android, .ios: - return [] - default: - return [("combo_ctrl_alt_del", ["ControlLeft", "AltLeft", "Delete"]), ("combo_alt_tab", ["AltLeft", "Tab"]), - ("combo_win", ["MetaLeft"]), ("combo_win_d", ["MetaLeft", "KeyD"]), ("combo_win_e", ["MetaLeft", "KeyE"]), - ("combo_win_l", ["MetaLeft", "KeyL"]), ("combo_alt_f4", ["AltLeft", "F4"]), - ("combo_task_manager", ["ControlLeft", "ShiftLeft", "Escape"]), ("combo_copy", ["ControlLeft", "KeyC"]), - ("combo_paste", ["ControlLeft", "KeyV"]), ("combo_undo", ["ControlLeft", "KeyZ"]), ("combo_print_screen", ["PrintScreen"])] - } + init(session: RemoteSession) { + self.session = session + _shortcuts = State(initialValue: ShortcutProfiles.load(for: session.os)) } + private func persist() { ShortcutProfiles.save(shortcuts, for: session.os) } + var body: some View { List { if let actions = session.hello?.actions, !actions.isEmpty { @@ -215,13 +206,28 @@ struct ShortcutsPage: View { } } } - if !combos.isEmpty { + if editable { Section { - ForEach(combos, id: \.0) { key, codes in - Button(L.t(key)) { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - session.input(Input.chord(codes)) + ForEach(shortcuts) { item in + HStack { + Button(item.label()) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + session.input(Input.chord(item.codes)) + } + Spacer() + Button { editor = item } label: { Image(systemName: "pencil") } + .buttonStyle(.borderless) + .accessibilityLabel(L.t("shortcut_edit")) } + .deleteDisabled(!item.id.hasPrefix("custom:")) + } + .onMove { source, destination in + shortcuts.move(fromOffsets: source, toOffset: destination) + persist() + } + .onDelete { offsets in + shortcuts.remove(atOffsets: offsets) + persist() } } } @@ -231,6 +237,28 @@ struct ShortcutsPage: View { .navigationTitle(L.t("menu_shortcuts")) .navigationBarTitleDisplayMode(.inline) .toolbar(.visible, for: .navigationBar) + .toolbar { + ToolbarItemGroup(placement: .topBarTrailing) { + if editable { + EditButton() + Button { editor = SavedShortcut(id: "custom:\(UUID().uuidString)", title: "", codes: []) } label: { + Image(systemName: "plus") + } + .accessibilityLabel(L.t("shortcut_add")) + } + } + } + .sheet(item: $editor) { item in + ShortcutEditor(shortcut: item, os: session.os) { changed in + if let index = shortcuts.firstIndex(where: { $0.id == changed.id }) { + shortcuts[index] = changed + } else { + shortcuts.append(changed) + } + persist() + } + } + .onChange(of: session.os) { _, os in shortcuts = ShortcutProfiles.load(for: os) } } } diff --git a/ios/Airhand/Session/Shortcuts.swift b/ios/Airhand/Session/Shortcuts.swift new file mode 100644 index 00000000..0d90f3a9 --- /dev/null +++ b/ios/Airhand/Session/Shortcuts.swift @@ -0,0 +1,109 @@ +import SwiftUI + +/// A shortcut is local to the controller. The wire protocol still receives ordinary key edges. +struct SavedShortcut: Codable, Identifiable, Equatable { + var id: String + var title: String? + var codes: [String] + + func label() -> String { title ?? L.t(id) } +} + +enum ShortcutProfiles { + private static let file = "shortcuts.json" + + static func defaults(for os: OsKind) -> [SavedShortcut] { + let items: [(String, [String])] + switch os { + case .mac: + items = [("combo_cmd_tab", ["MetaLeft", "Tab"]), ("combo_spotlight", ["MetaLeft", "Space"]), + ("combo_mission_control", ["ControlLeft", "ArrowUp"]), ("combo_cmd_w", ["MetaLeft", "KeyW"]), + ("combo_cmd_q", ["MetaLeft", "KeyQ"]), ("combo_force_quit", ["MetaLeft", "AltLeft", "Escape"]), + ("combo_lock_mac", ["ControlLeft", "MetaLeft", "KeyQ"]), ("combo_screenshot_mac", ["MetaLeft", "ShiftLeft", "Digit5"]), + ("combo_copy_mac", ["MetaLeft", "KeyC"]), ("combo_paste_mac", ["MetaLeft", "KeyV"]), + ("combo_undo_mac", ["MetaLeft", "KeyZ"])] + case .windows: + items = [("combo_ctrl_alt_del", ["ControlLeft", "AltLeft", "Delete"]), ("combo_alt_tab", ["AltLeft", "Tab"]), + ("combo_win", ["MetaLeft"]), ("combo_win_d", ["MetaLeft", "KeyD"]), + ("combo_win_e", ["MetaLeft", "KeyE"]), ("combo_win_l", ["MetaLeft", "KeyL"]), + ("combo_alt_f4", ["AltLeft", "F4"]), ("combo_task_manager", ["ControlLeft", "ShiftLeft", "Escape"]), + ("combo_copy", ["ControlLeft", "KeyC"]), ("combo_paste", ["ControlLeft", "KeyV"]), + ("combo_undo", ["ControlLeft", "KeyZ"]), ("combo_print_screen", ["PrintScreen"])] + case .linux: + items = [("combo_alt_tab", ["AltLeft", "Tab"]), ("combo_copy", ["ControlLeft", "KeyC"]), + ("combo_paste", ["ControlLeft", "KeyV"]), ("combo_undo", ["ControlLeft", "KeyZ"])] + case .android, .ios, .unknown: + items = [] + } + return items.map { SavedShortcut(id: $0.0, title: nil, codes: $0.1) } + } + + static func load(for os: OsKind) -> [SavedShortcut] { + let profiles = SharedStore.read(file, as: [String: [SavedShortcut]].self) ?? [:] + return profiles[os.rawValue] ?? defaults(for: os) + } + + static func save(_ shortcuts: [SavedShortcut], for os: OsKind) { + var profiles = SharedStore.read(file, as: [String: [SavedShortcut]].self) ?? [:] + profiles[os.rawValue] = shortcuts + SharedStore.write(file, profiles) + } +} + +struct ShortcutEditor: View { + let original: SavedShortcut + let os: OsKind + let save: (SavedShortcut) -> Void + @Environment(\.dismiss) private var dismiss + @State private var title: String + @State private var codes: [String] + @State private var picking = false + + init(shortcut: SavedShortcut, os: OsKind, save: @escaping (SavedShortcut) -> Void) { + original = shortcut + self.os = os + self.save = save + _title = State(initialValue: shortcut.title ?? (shortcut.id.hasPrefix("custom:") ? "" : L.t(shortcut.id))) + _codes = State(initialValue: shortcut.codes) + } + + var body: some View { + NavigationStack { + Form { + TextField(L.t("shortcut_name"), text: $title) + Button { + picking = true + } label: { + HStack { + Text(L.t("shortcut_keys")) + Spacer() + Text(codes.isEmpty ? L.t("shortcut_pick") : codes.map { GameItem.keyLabel($0, os: os) }.joined(separator: " + ")) + .foregroundStyle(Theme.sub) + } + } + } + .scrollContentBackground(.hidden) + .background(Theme.bg) + .navigationTitle(L.t("shortcut_edit")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button(L.t("cancel")) { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button(L.t("ok")) { + var item = original + let name = title.trimmingCharacters(in: .whitespacesAndNewlines) + item.title = name == L.t(original.id) && !original.id.hasPrefix("custom:") ? nil : name + item.codes = codes + save(item) + dismiss() + } + .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || codes.isEmpty) + } + } + } + .sheet(isPresented: $picking) { + KeyPicker(initial: codes, os: os, keyboardOnly: true, maxKeys: 4) { codes = $0 } + } + .preferredColorScheme(.dark) + } +} diff --git a/ios/Shared/L10n.swift b/ios/Shared/L10n.swift index 34277e24..1cd8c417 100644 --- a/ios/Shared/L10n.swift +++ b/ios/Shared/L10n.swift @@ -158,6 +158,8 @@ enum L { "game_mouse_left": "左键", "game_mouse_right": "右键", "game_mouse_middle": "中键", "game_wheel_up": "滚轮↑", "game_wheel_down": "滚轮↓", "game_duplicate_item": "复制", "game_empty_layout_hint": "还没有按钮,点上面的 + 添加", "game_tip": "按住按钮就是按着那个键;空白处拖动在游戏隐藏光标时转视角。菜单 → 游戏按键 → 编辑布局可以自己摆。", // 快捷键 + "shortcut_add": "添加快捷键", "shortcut_edit": "编辑快捷键", "shortcut_name": "名称", "shortcut_keys": "按键", "shortcut_pick": "选择按键", + "shortcut_pick_hint": "按顺序选择最多 4 个键;先选修饰键,最后选主键", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab 切换窗口", "combo_win": "Win 开始菜单", "combo_win_d": "Win + D 显示桌面", "combo_win_e": "Win + E 文件资源管理器", "combo_win_l": "Win + L 锁屏", "combo_alt_f4": "Alt + F4 关闭窗口", "combo_task_manager": "Ctrl + Shift + Esc 任务管理器", "combo_copy": "Ctrl + C 复制", @@ -335,6 +337,8 @@ enum L { "game_group_function": "Function keys", "game_group_nav": "Navigation & editing", "game_group_symbols": "Symbols", "game_mouse_left": "Left", "game_mouse_right": "Right", "game_mouse_middle": "Middle", "game_wheel_up": "Wheel ↑", "game_wheel_down": "Wheel ↓", "game_duplicate_item": "Duplicate", "game_empty_layout_hint": "No buttons yet — tap + above to add one", "game_tip": "Hold a button to hold its key; drag on empty space to turn the view when a game hides the cursor. Menu → Game controls → Edit layout to arrange them.", + "shortcut_add": "Add shortcut", "shortcut_edit": "Edit shortcut", "shortcut_name": "Name", "shortcut_keys": "Keys", "shortcut_pick": "Choose keys", + "shortcut_pick_hint": "Choose up to 4 keys in order: modifiers first, main key last", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab switch windows", "combo_win": "Win Start menu", "combo_win_d": "Win + D show desktop", "combo_win_e": "Win + E File Explorer", "combo_win_l": "Win + L lock", "combo_alt_f4": "Alt + F4 close window", "combo_task_manager": "Ctrl + Shift + Esc Task Manager", "combo_copy": "Ctrl + C copy", diff --git a/ios/Tests/ShortcutTests.swift b/ios/Tests/ShortcutTests.swift new file mode 100644 index 00000000..50d0aa6f --- /dev/null +++ b/ios/Tests/ShortcutTests.swift @@ -0,0 +1,10 @@ +import XCTest +@testable import Airhand + +final class ShortcutTests: XCTestCase { + func testCopyUsesRemoteOperatingSystem() { + XCTAssertEqual(ShortcutProfiles.defaults(for: .mac).first { $0.id == "combo_copy_mac" }?.codes, ["MetaLeft", "KeyC"]) + XCTAssertEqual(ShortcutProfiles.defaults(for: .windows).first { $0.id == "combo_copy" }?.codes, ["ControlLeft", "KeyC"]) + XCTAssertEqual(ShortcutProfiles.defaults(for: .linux).first { $0.id == "combo_copy" }?.codes, ["ControlLeft", "KeyC"]) + } +} From 0149474e3be8b1db5e9eea99c6e404da7df24894 Mon Sep 17 00:00:00 2001 From: Dlouxgit <57781857+Dlouxgit@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:48:28 +0800 Subject: [PATCH 2/6] Add mobile keyboard and shortcuts input tabs --- .../android/ui/session/PhoneSession.kt | 169 +++++++++++++----- docs/android.md | 1 + docs/android.zh-CN.md | 1 + docs/ios.md | 1 + docs/ios.zh-CN.md | 1 + ios/Airhand/Session/SessionController.swift | 24 ++- ios/Airhand/Session/SessionViews.swift | 114 ++++++++++-- 7 files changed, 253 insertions(+), 58 deletions(-) diff --git a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt index df4936fd..52d46995 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt @@ -9,6 +9,7 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement @@ -193,6 +194,8 @@ fun PhoneSession( var mode by remember(os) { mutableStateOf(initialMode(settings.touchMode, os)) } var menu by remember { mutableStateOf(false) } + var inputTab by remember { mutableIntStateOf(0) } + LaunchedEffect(keyboardOpen.value) { if (!keyboardOpen.value) inputTab = 0 } var page by remember { mutableStateOf(Page.MAIN) } var confirmExit by remember { mutableStateOf(false) } var dismissed by remember { mutableStateOf(setOf()) } @@ -236,21 +239,33 @@ fun PhoneSession( // 键盘:按钮 / 三指点击打开;用系统的返回收起时同步状态 val imeVisible = WindowInsets.isImeVisible var imeWasVisible by remember { mutableStateOf(false) } - LaunchedEffect(keyboardOpen.value) { if (keyboardOpen.value) view.showKeyboard() else view.hideKeyboard() } + LaunchedEffect(keyboardOpen.value, inputTab) { + if (keyboardOpen.value && inputTab == 0) view.showKeyboard() else view.hideKeyboard() + } LaunchedEffect(imeVisible) { - if (imeWasVisible && !imeVisible) keyboardOpen.value = false + if (imeWasVisible && !imeVisible && inputTab == 0) keyboardOpen.value = false imeWasVisible = imeVisible } BackHandler(enabled = !menu && editor == null) { confirmExit = true } val imeBottom = WindowInsets.ime.asPaddingValues().calculateBottomPadding() - val keysBar = if (imeVisible) (if (landscape) 36.dp else 44.dp) else 0.dp + val shortcutPanel = keyboardOpen.value && inputTab == 1 && + (os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX) + BackHandler(enabled = shortcutPanel && !menu) { keyboardOpen.value = false; inputTab = 0 } + val keysBar = when { + shortcutPanel -> 272.dp + imeVisible -> (if (landscape) 36.dp else 44.dp) + + (if (os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX) 32.dp else 0.dp) + else -> 0.dp + } val navActions = listOf(SystemAction.BACK, SystemAction.HOME, SystemAction.RECENTS).filter { it in actions } - val navBar = if (navActions.isNotEmpty() && settings.navKeys && !imeVisible) 48.dp else 0.dp + val navBar = if (navActions.isNotEmpty() && settings.navKeys && !keyboardOpen.value) 48.dp else 0.dp // 画面不跟着键盘缩小:键盘和特殊键挡着多高告诉 RemoteView,它把画面(放不下时是光标所在的地方)挪到键盘上面 val density = LocalDensity.current - val imeInsetPx = if (imeVisible) with(density) { (imeBottom + keysBar).toPx() } else 0f + val imeInsetPx = if (imeVisible || shortcutPanel) with(density) { + (if (shortcutPanel) keysBar else imeBottom + keysBar).toPx() + } else 0f LaunchedEffect(imeInsetPx, landscape) { view.setKeyboardInset(imeInsetPx) } Box(Modifier.fillMaxSize().background(Color.Black)) { @@ -265,7 +280,7 @@ fun PhoneSession( // 游戏按键:连上了、没盖住、没开键盘(键盘会挡住)、没在编辑时才显示;收起、换方案都先松开按着的键 val live = phase == RemoteSession.Phase.Live && video != null - val showGame = gameOn && live && !covered && !imeVisible && editor == null + val showGame = gameOn && live && !covered && !keyboardOpen.value && editor == null LaunchedEffect(showGame, gameLayout) { view.setGame(if (showGame) gameLayout else null) } // 被控端的提示(采集失败、不能操作……)和本机的问题 @@ -306,15 +321,17 @@ fun PhoneSession( } } - if (imeVisible) { + if (imeVisible || shortcutPanel) { KeysBar( kb, os, compact = landscape, - onHide = { keyboardOpen.value = false }, + tab = inputTab, + onTab = { inputTab = it }, + onHide = { keyboardOpen.value = false; inputTab = 0 }, modifier = Modifier .align(Alignment.BottomCenter) - .padding(bottom = imeBottom) + .padding(bottom = if (shortcutPanel) 0.dp else imeBottom) .height(keysBar), ) } else if (navBar > 0.dp) { @@ -329,7 +346,7 @@ fun PhoneSession( if (!covered && editor == null) { MenuHandle( - bottomInset = imeBottom + keysBar + navBar, + bottomInset = (if (shortcutPanel) 0.dp else imeBottom) + keysBar + navBar, doubleTapKeyboard = settings.doubleTapKeyboard, onClick = { page = Page.MAIN @@ -1435,41 +1452,109 @@ private fun GestureTips(mode: Gestures.Mode, onDone: () -> Unit) { // ───────────────────────────── 键盘上方的特殊键 / 手机导航键 ───────────────────────────── +@OptIn(ExperimentalLayoutApi::class) @Composable -private fun KeysBar(kb: KeyboardController, os: OsKind, compact: Boolean = false, onHide: () -> Unit, modifier: Modifier) { +private fun KeysBar( + kb: KeyboardController, + os: OsKind, + compact: Boolean = false, + tab: Int, + onTab: (Int) -> Unit, + onHide: () -> Unit, + modifier: Modifier, +) { val meta = if (os == OsKind.MAC) "⌘" else if (os == OsKind.ANDROID) "◯" else "Win" - Row( - modifier - .fillMaxWidth() - .background(Color(0xFF1B1F2B)), - verticalAlignment = Alignment.CenterVertically, - ) { - Row( - Modifier - .weight(1f) - .horizontalScroll(rememberScrollState()) - .padding(horizontal = 4.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Key("Esc", compact) { kb.press("Escape") } - Key("Tab", compact) { kb.press("Tab") } - ModKey("Ctrl", kb, KeyboardController.Mod.CTRL, compact) - ModKey(if (os == OsKind.MAC) "⌥" else "Alt", kb, KeyboardController.Mod.ALT, compact) - ModKey("⇧", kb, KeyboardController.Mod.SHIFT, compact) - ModKey(meta, kb, KeyboardController.Mod.META, compact) - Key("←", compact) { kb.press("ArrowLeft") } - Key("↑", compact) { kb.press("ArrowUp") } - Key("↓", compact) { kb.press("ArrowDown") } - Key("→", compact) { kb.press("ArrowRight") } - Key("Del", compact) { kb.press("Delete") } - Key("Home", compact) { kb.press("Home") } - Key("End", compact) { kb.press("End") } - Key("PgUp", compact) { kb.press("PageUp") } - Key("PgDn", compact) { kb.press("PageDown") } - for (i in 1..12) Key("F$i", compact) { kb.press("F$i") } + val hasShortcuts = os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX + val context = LocalContext.current + val labels = remember(os) { ShortcutDefaults.forOs(os).associate { it.id to it.label } } + Column(modifier.fillMaxWidth().background(Color(0xFF1B1F2B))) { + if (hasShortcuts) { + var drag = 0f + Row( + Modifier.fillMaxWidth().height(32.dp) + .pointerInput(tab) { + detectHorizontalDragGestures( + onDragStart = { drag = 0f }, + onDragEnd = { + if (drag > 40f) onTab(1) + if (drag < -40f) onTab(0) + }, + onHorizontalDrag = { change, amount -> + drag += amount + change.consume() + }, + ) + } + .padding(horizontal = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + listOf(R.string.menu_keyboard, R.string.menu_shortcuts).forEachIndexed { index, title -> + Text( + stringResource(title), + color = if (tab == index) Color.White else Color.White.copy(alpha = 0.6f), + fontWeight = if (tab == index) FontWeight.Bold else FontWeight.Normal, + fontSize = 12.sp, + modifier = Modifier.clickable { onTab(index) } + .padding(horizontal = 12.dp, vertical = 6.dp), + ) + } + if (tab == 1) { + Spacer(Modifier.weight(1f)) + IconButton(onClick = onHide, modifier = Modifier.size(32.dp)) { + Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + } + } + } } - IconButton(onClick = onHide, modifier = Modifier.size(if (compact) 36.dp else 44.dp)) { - Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + if (tab == 1 && hasShortcuts) { + var drag = 0f + FlowRow( + modifier = Modifier.fillMaxWidth().weight(1f) + .verticalScroll(rememberScrollState()) + .pointerInput(tab) { + detectHorizontalDragGestures( + onDragStart = { drag = 0f }, + onDragEnd = { if (drag < -60f) onTab(0) }, + onHorizontalDrag = { change, amount -> + drag += amount + change.consume() + }, + ) + } + .padding(8.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + AirhandApp.instance.shortcuts.list(os).forEach { item -> + Key(item.title ?: labels[item.id]?.let { context.getString(it) } ?: item.id, compact) { kb.chord(item.codes) } + } + } + } else { + Row(verticalAlignment = Alignment.CenterVertically) { + Row( + Modifier.weight(1f).horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Key("Esc", compact) { kb.press("Escape") } + Key("Tab", compact) { kb.press("Tab") } + ModKey("Ctrl", kb, KeyboardController.Mod.CTRL, compact) + ModKey(if (os == OsKind.MAC) "⌥" else "Alt", kb, KeyboardController.Mod.ALT, compact) + ModKey("⇧", kb, KeyboardController.Mod.SHIFT, compact) + ModKey(meta, kb, KeyboardController.Mod.META, compact) + Key("←", compact) { kb.press("ArrowLeft") } + Key("↑", compact) { kb.press("ArrowUp") } + Key("↓", compact) { kb.press("ArrowDown") } + Key("→", compact) { kb.press("ArrowRight") } + Key("Del", compact) { kb.press("Delete") } + Key("Home", compact) { kb.press("Home") } + Key("End", compact) { kb.press("End") } + Key("PgUp", compact) { kb.press("PageUp") } + Key("PgDn", compact) { kb.press("PageDown") } + for (i in 1..12) Key("F$i", compact) { kb.press("F$i") } + } + IconButton(onClick = onHide, modifier = Modifier.size(if (compact) 36.dp else 44.dp)) { + Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + } + } } } } diff --git a/docs/android.md b/docs/android.md index 0c1c7a1b..95ae8acc 100644 --- a/docs/android.md +++ b/docs/android.md @@ -52,6 +52,7 @@ After you pinch to zoom the local view, a moment after your fingers stop the app - **Keyboard**: the picture doesn't shrink: when it fits above the keyboard it moves up there, otherwise (landscape, or a phone held upright on the other side) the part around the pointer moves above the keyboard and follows the pointer, and everything moves back once the keyboard is hidden; in landscape the extra keys row is shorter and the stats overlay is hidden for the time being. A row of extra keys sits on top of the keyboard: Esc, Tab, Ctrl, Alt, Shift, Win (⌘ for Macs), arrows, Home / End, PgUp / PgDn, Del, F1–F12. Modifiers are sticky: tap once for the next key only, again to lock, again to release (tap Ctrl, then type c = Ctrl+C). While an IME composes (pinyin etc.) the text shows above the extra keys and is only sent once chosen - When controlling a phone, **Back / Home / Recents** keys sit below the picture (can be turned off in Settings), and Keyboard & input in the menu holds system actions: notifications, quick settings, screenshot, lock screen, power menu, volume (whichever the phone supports). For computers it lists shortcuts for the remote OS (Windows / macOS / Linux) - When controlling a computer, you can add or edit keyboard combinations and move them up or down in Reorder mode. The list is saved locally on this Android device, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C +- With the keyboard open for a remote computer, tap Keyboard / Shortcuts above it or swipe right on those tabs to show the saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Use the menu's shortcuts page to edit the list - A connected mouse and keyboard map directly to the remote mouse and keyboard. Over the picture the mouse shows just the remote cursor, without the system pointer on top; in Settings its wheel can be reversed, set to a speed (5%–200%) and to **Adaptive** (the default: a slow single notch moves half as far, spinning quickly speeds up to twice as far) or **Linear** (the same distance for every notch), and **Smooth mouse scrolling** splits each notch into a few small steps about 16 ms apart (the same total; closer to a trackpad on a Mac). Ctrl / ⌘ shortcuts on the keyboard go to the remote computer even while an input method is active, and keys still held are let go when the menu opens or the app goes to the background. When controlling a Mac, **Swap Ctrl and ⌘ Command** under Keyboard & input in the menu makes the keyboard's Ctrl work as ⌘ and the Win key as Control (copy with Ctrl+C on a Windows keyboard); the extra keys row and the shortcuts in the menu don't change. It's off by default and remembered per computer, as in the desktop console - **Games**: when the remote computer hides its cursor (turning the camera in a game), trackpad slides and touch drags send how far you moved instead of a position, so the camera turns smoothly and doesn't stop at the edge of the picture; a connected mouse is captured (Android 8+). **Mouse lock** under Mouse & touch in the menu does the same all the time, e.g. for Macs, which can't report a hidden cursor. For games played with the keyboard, see game keys below - **Privacy mode**: under Video & display in the menu when the remote is Windows or a Mac (with a version that supports it). It blanks all of the remote monitors and disables its keyboard and mouse, so only you can see and control it; the switch shows the current state (turning on, on, why it isn't available), and a failure also shows at the top of the picture. It turns off by itself after you disconnect and stays on while reconnecting. See [Usage → Privacy mode](usage.md#privacy-mode) diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index c0efd3fa..5e9a0731 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -52,6 +52,7 @@ - **键盘**:打开后画面不缩小:键盘上面放得下就挪到键盘上面,放不下(横屏、对方是竖着的手机)就把指针所在的地方挪到键盘上面,移动指针时跟着走,收起键盘后回到原来的位置;横屏时特殊键那一排矮一些,状态信息先不显示。键盘上面多一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12。修饰键是“粘滞”的:点一下只对下一个键有效,再点一下锁定,再点取消(例如点 Ctrl 再在键盘上打 c = Ctrl+C)。拼音等输入法组字时文字显示在特殊键上方,选好字才发过去 - 控制手机时画面下方有**返回 / 主页 / 最近任务**三个键(设置里可以关掉),菜单 → 键盘与输入里是通知栏、快捷设置、截屏、锁屏、电源菜单、音量等系统操作(对方手机能执行哪些就显示哪些);控制电脑时那里是按对方系统列出的快捷键(Windows / macOS / Linux) - 控制电脑时,可以添加、编辑组合键,在“调整顺序”模式里用上下箭头排序。列表保存在这台 Android 设备上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C +- 控制电脑并打开键盘时,可以点键盘上方的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。编辑列表仍在菜单的快捷键页 - 外接鼠标、键盘直接对应远端的鼠标、键盘。鼠标在画面上时只显示对方的光标,不会再叠一个系统指针。滚轮在设置里可以改速度(5%–200%)、方向和换算方式:**自适应加速**(默认:慢慢滚一格只走半格,连着快滚加速到两倍)或**固定线性**(每格一样远);还可以打开**平滑滚动**(每一格拆成几小步、约 16 ms 一步发过去,加起来不变,控制 Mac 时更像触控板)。键盘上 Ctrl / ⌘ 的组合键不会被本机的输入法拿走;打开菜单、切到后台时按着的键都会松开。控制 Mac 时,菜单 → 键盘与输入里的**互换 Ctrl 和 ⌘ Command** 让键盘上的 Ctrl 当 ⌘ 用、Win 键当 Ctrl 用(用 Windows 键盘按 Ctrl+C 复制);键盘上方的特殊键和菜单里的快捷键不变。默认关闭,每台电脑分别记住,和桌面控制台一样 - **游戏**:对方电脑隐藏了光标时(游戏里转视角),触控板的滑动、触屏的拖动发的是“移动了多少”而不是位置,视角转得顺,拖到画面边上也不会停;外接鼠标会被抓住(Android 8+)。菜单 → 鼠标与触控里的**锁定鼠标**让它一直这样,例如对方是 Mac(检测不到光标隐藏)时。要按键盘的游戏用下面的游戏按键 - **防窥模式**:对方是 Windows、Mac(而且是支持它的版本)时菜单 → 视频与画面里有它。打开后对方所有的显示器黑屏、键盘鼠标不起作用,只有你看得到、操作得了;开关下面写着现在怎么样(正在打开、开着、开不了的原因),没能打开时画面上方也会提示。断开连接后自动恢复,断线重连时接着保持。详见[使用说明 → 防窥模式](usage.zh-CN.md#防窥模式) diff --git a/docs/ios.md b/docs/ios.md index 24cf162e..b14e4381 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -43,6 +43,7 @@ After zooming in, Airhand asks the remote for a sharper picture once your finger - **Mouse / trackpad (iPad)**: move, left / right / middle / side buttons and the wheel map to the remote; the remote's cursor shape is drawn locally. When the remote hides its cursor (games) or “Lock mouse” is on, the pointer is **locked** and raw movement is sent; hold Esc to release (iPadOS only allows pointer lock in full screen) - Phones get **Back / Home / Recents** below the picture (can be turned off) and their system actions on the shortcuts page; computers get shortcuts for their OS - For a remote computer, the shortcuts page lets you add or edit keyboard combinations and reorder them with Edit. The list is saved locally on this iPhone or iPad, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C +- With the keyboard open for a remote computer, tap Keyboard / Shortcuts above it or swipe right on those tabs to show the saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Use the menu's shortcuts page to edit the list - **Clipboard**: text copied on the remote lands in this device's clipboard; the menu can send this device's text to the remote clipboard or type it (iOS asks once to allow pasting) - **Files**: files copied on the remote show a prompt; “Save to Files” transfers them into Files › On My iPhone › Airhand. “Send files” puts files from this device on the remote clipboard to paste there (only a list is sent until pasted) - **Sound** with adaptive jitter buffer; **A/V sync** for videos; **microphone** forwarding to Windows, macOS 14.2+ and Linux hosts, with system echo cancellation diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index 047530e2..982551f3 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -44,6 +44,7 @@ - **外接鼠标 / 触控板(iPad)**:移动、左右中键、侧键、滚轮直接对应远端;本机不显示系统指针,画的是对方的光标形状。对方隐藏了光标(游戏里转视角)或者打开了“锁定鼠标”时,**锁定指针**、发原始移动量;长按 Esc 放开(iPadOS 只在 App 全屏时允许锁定指针) - 控制手机时画面下方有**返回 / 主页 / 最近任务**(设置里可以关掉),快捷键页里是对方手机支持的系统操作;控制电脑时快捷键按对方系统列出(Windows / macOS / Linux) - 控制电脑时,快捷键页可以添加、编辑组合键,点“编辑”后拖动调整顺序。列表保存在这台 iPhone 或 iPad 上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C +- 控制电脑并打开键盘时,可以点键盘上方的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。编辑列表仍在菜单的快捷键页 - **剪贴板**:对方复制的文字自动放进本机剪贴板;菜单 → 剪贴板可以把本机复制的文字发到对方的剪贴板,或者直接打进对方的输入框(读本机剪贴板时 iOS 会问一次“允许粘贴”) - **文件**:对方复制的文件会提示“对方复制了 N 项”,点“保存到‘文件’”才传,存在“文件 › 我的 iPhone › Airhand”;菜单 → 发送文件选好本机的文件,放进对方的剪贴板,到对方那里粘贴(复制时只发清单,粘贴时才传) - **声音**:对方的声音同步过来(Opus + 自适应抖动缓冲,和桌面版同一套做法);**音画同步**看视频时打开。**麦克风**:对方能接收时(Windows、macOS 14.2+、Linux 被控端),菜单里打开就把本机的麦克风转发过去,开着系统的回声消除 diff --git a/ios/Airhand/Session/SessionController.swift b/ios/Airhand/Session/SessionController.swift index a0f216c3..1b8e2cfa 100644 --- a/ios/Airhand/Session/SessionController.swift +++ b/ios/Airhand/Session/SessionController.swift @@ -158,12 +158,14 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private let gestures = Gestures(slop: 8) private let keyField = KeyField() private let keyboard = KeyboardState() + private let inputPage = InputPageState() private let game = GameLayerView() private let menuButton = FloatingMenuButton() private var overlayHost: UIHostingController! private var bannerHost: UIHostingController! private var navHost: UIHostingController? private var accessory: UIHostingController! + private var shortcutsInput: UIHostingController! private var zoom: CGFloat = 1 private var offset: CGPoint = .zero @@ -238,10 +240,20 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract keyField.onEnter = { [weak self] in self?.keyboard.press("Enter") } keyField.onComposing = { [weak self] s in self?.keyboard.composing = s } keyField.onPresses = { [weak self] p, down in self?.hardwareKeys(p, down) ?? false } - accessory = UIHostingController(rootView: KeyBar(state: keyboard, os: session.os, hide: { [weak self] in self?.setKeyboard(false) })) + shortcutsInput = UIHostingController(rootView: ShortcutInputPanel( + state: keyboard, os: session.os, switchPage: { [weak self] page in self?.setInputPage(page) } + )) + shortcutsInput.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 260) + shortcutsInput.view.autoresizingMask = [.flexibleWidth] + accessory = UIHostingController(rootView: KeyBar( + state: keyboard, os: session.os, page: inputPage, + switchPage: { [weak self] page in self?.setInputPage(page) }, + hide: { [weak self] in self?.setKeyboard(false) } + )) accessory.view.backgroundColor = .clear accessory.sizingOptions = [.intrinsicContentSize] - accessory.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 54) + accessory.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, + height: session.os.isPhone ? 54 : 86) accessory.view.autoresizingMask = [.flexibleWidth] keyField.inputAccessoryView = accessory.view view.addSubview(keyField) @@ -781,10 +793,18 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract keyField.becomeFirstResponder() } else { keyField.resignFirstResponder() + setInputPage(0) becomeFirstResponder() } } + private func setInputPage(_ page: Int) { + guard inputPage.selected != page else { return } + inputPage.selected = page + keyField.inputView = page == 1 ? shortcutsInput.view : nil + if keyField.isFirstResponder { keyField.reloadInputViews() } + } + @objc private func keyboardFrame(_ n: Notification) { var h: CGFloat = 0 if n.name != UIResponder.keyboardWillHideNotification, let f = n.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { diff --git a/ios/Airhand/Session/SessionViews.swift b/ios/Airhand/Session/SessionViews.swift index f3582710..cdc63d3a 100644 --- a/ios/Airhand/Session/SessionViews.swift +++ b/ios/Airhand/Session/SessionViews.swift @@ -1,5 +1,6 @@ import SwiftUI import UIKit +import Observation /// 画面还没来、断线重连、对方离线、会话结束时盖在画面上的那一层 struct SessionOverlay: View { @@ -141,11 +142,17 @@ struct NavKeysBar: View { } /// 软键盘上面的一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12 +@Observable final class InputPageState { var selected = 0 } + struct KeyBar: View { let state: KeyboardState let os: OsKind + let page: InputPageState + let switchPage: (Int) -> Void let hide: () -> Void + private var hasShortcuts: Bool { os == .mac || os == .windows || os == .linux } + private let keys: [String] = ["Escape", "Tab", "MOD:ControlLeft", "MOD:AltLeft", "MOD:ShiftLeft", "MOD:MetaLeft", "ArrowLeft", "ArrowUp", "ArrowDown", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Delete"] + (1...12).map { "F\($0)" } @@ -158,24 +165,40 @@ struct KeyBar: View { .background(Theme.c2.opacity(0.5), in: Capsule()) .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 4) } - HStack(spacing: 0) { + if hasShortcuts { + HStack(spacing: 18) { + tab(L.t("menu_keyboard"), index: 0) + tab(L.t("menu_shortcuts"), index: 1) + Spacer() + } + .padding(.horizontal, 12) + .frame(height: 32) + .contentShape(Rectangle()) + .simultaneousGesture(DragGesture(minimumDistance: 25).onEnded { value in + if value.translation.width > 40 { switchPage(1) } + if value.translation.width < -40 { switchPage(0) } + }) + .background(.ultraThinMaterial) + } + if page.selected == 0 || !hasShortcuts { + HStack(spacing: 0) { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 6) { - ForEach(keys, id: \.self) { k in - if k.hasPrefix("MOD:") { - let m = String(k.dropFirst(4)) - let st = state.state(m) - keyButton(KeyMap.label(m, os: os), highlight: st) { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - state.toggle(m) - } - } else { - keyButton(KeyMap.label(k, os: os), highlight: .off) { - UIImpactFeedbackGenerator(style: .light).impactOccurred(intensity: 0.6) - state.press(k) + ForEach(keys, id: \.self) { k in + if k.hasPrefix("MOD:") { + let m = String(k.dropFirst(4)) + let st = state.state(m) + keyButton(KeyMap.label(m, os: os), highlight: st) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + state.toggle(m) + } + } else { + keyButton(KeyMap.label(k, os: os), highlight: .off) { + UIImpactFeedbackGenerator(style: .light).impactOccurred(intensity: 0.6) + state.press(k) + } } } - } } .padding(.horizontal, 8) } @@ -187,10 +210,36 @@ struct KeyBar: View { } .frame(height: 50) .background(.ultraThinMaterial) + } else { + Button(action: hide) { + Image(systemName: "keyboard.chevron.compact.down") + .font(.system(size: 17, weight: .semibold)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, alignment: .trailing) + .padding(.trailing, 14) + } + .accessibilityLabel(L.t("hide_keyboard")) + .frame(height: 30) + .background(.ultraThinMaterial) + } } .preferredColorScheme(.dark) } + private func tab(_ label: String, index: Int) -> some View { + Button { switchPage(index) } label: { + Text(label) + .font(.caption.weight(page.selected == index ? .bold : .medium)) + .foregroundStyle(page.selected == index ? .white : .white.opacity(0.6)) + .padding(.horizontal, 8) + .frame(height: 32) + .overlay(alignment: .bottom) { + if page.selected == index { Capsule().fill(Theme.c2).frame(height: 2) } + } + } + .buttonStyle(.plain) + } + private func keyButton(_ label: String, highlight: KeyboardState.Sticky, _ f: @escaping () -> Void) -> some View { Button(action: f) { Text(label).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white) @@ -207,6 +256,43 @@ struct KeyBar: View { } } +/// Replaces the system keyboard while the shortcut tab is selected. +struct ShortcutInputPanel: View { + let state: KeyboardState + let os: OsKind + let switchPage: (Int) -> Void + @State private var items: [SavedShortcut] = [] + + var body: some View { + ScrollView { + LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) { + ForEach(items) { item in + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + state.chord(item.codes) + } label: { + Text(item.label()) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, minHeight: 40) + .background(Color.white.opacity(0.12), in: RoundedRectangle(cornerRadius: 9)) + } + .buttonStyle(.plain) + } + } + .padding(10) + } + .background(Theme.bg) + .onAppear { items = ShortcutProfiles.load(for: os) } + .simultaneousGesture(DragGesture(minimumDistance: 35).onEnded { value in + if value.translation.width < -60 && abs(value.translation.width) > abs(value.translation.height) { + switchPage(0) + } + }) + .preferredColorScheme(.dark) + } +} + /// 手势说明(第一次进入远程画面时,菜单里也能打开) struct GestureTips: View { let mode: Gestures.Mode From 53bd04a7cac054cc6eac7c2c4479626bebc8e5a5 Mon Sep 17 00:00:00 2001 From: Dlouxgit <57781857+Dlouxgit@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:54:23 +0800 Subject: [PATCH 3/6] Refine mobile shortcut tabs and tap feedback --- .../android/ui/session/PhoneSession.kt | 92 ++++++---- docs/android.md | 2 +- docs/android.zh-CN.md | 2 +- docs/ios.md | 2 +- docs/ios.zh-CN.md | 2 +- ios/Airhand/Session/SessionController.swift | 44 ++++- ios/Airhand/Session/SessionViews.swift | 169 +++++++++++++----- ios/Airhand/Session/Shortcuts.swift | 51 +++++- ios/Shared/L10n.swift | 4 +- 9 files changed, 276 insertions(+), 92 deletions(-) diff --git a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt index 52d46995..8a324da2 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt @@ -1,5 +1,6 @@ package app.airhand.android.ui.session +import android.view.HapticFeedbackConstants import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn @@ -12,6 +13,8 @@ import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints @@ -96,6 +99,7 @@ import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight @@ -129,6 +133,7 @@ import app.airhand.android.ui.phone.wheelModeDesc import app.airhand.android.ui.phone.wheelModeName import app.airhand.android.ui.snapPercent import app.airhand.android.ui.theme.Brand +import kotlinx.coroutines.delay import java.util.Locale import kotlin.math.roundToInt @@ -256,7 +261,7 @@ fun PhoneSession( val keysBar = when { shortcutPanel -> 272.dp imeVisible -> (if (landscape) 36.dp else 44.dp) + - (if (os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX) 32.dp else 0.dp) + (if (os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX) 40.dp else 0.dp) else -> 0.dp } val navActions = listOf(SystemAction.BACK, SystemAction.HOME, SystemAction.RECENTS).filter { it in actions } @@ -839,8 +844,9 @@ private fun SwapCtrlCommand(session: RemoteSession) { HorizontalDivider(Modifier.padding(vertical = 8.dp, horizontal = 16.dp)) } +@OptIn(ExperimentalLayoutApi::class) @Composable -private fun Shortcuts(os: OsKind, onSend: (List) -> Unit) { +private fun Shortcuts(os: OsKind, onSend: (List) -> Unit, panel: Boolean = false) { if (os !in listOf(OsKind.MAC, OsKind.WINDOWS, OsKind.LINUX)) return val store = AirhandApp.instance.shortcuts val context = LocalContext.current @@ -868,7 +874,18 @@ private fun Shortcuts(os: OsKind, onSend: (List) -> Unit) { Text(stringResource(if (editing) R.string.shortcut_done else R.string.shortcut_reorder)) } } - items.forEachIndexed { index, item -> + if (panel && !editing) { + FlowRow( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + items.forEach { item -> + Key(item.title ?: labels[item.id]?.let { context.getString(it) } ?: item.id, compact = true, feedback = true) { + onSend(item.codes) + } + } + } + } else items.forEachIndexed { index, item -> Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { Text( item.title ?: labels[item.id]?.let { stringResource(it) } ?: item.id, @@ -1465,13 +1482,11 @@ private fun KeysBar( ) { val meta = if (os == OsKind.MAC) "⌘" else if (os == OsKind.ANDROID) "◯" else "Win" val hasShortcuts = os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX - val context = LocalContext.current - val labels = remember(os) { ShortcutDefaults.forOs(os).associate { it.id to it.label } } Column(modifier.fillMaxWidth().background(Color(0xFF1B1F2B))) { if (hasShortcuts) { var drag = 0f Row( - Modifier.fillMaxWidth().height(32.dp) + Modifier.fillMaxWidth().height(40.dp) .pointerInput(tab) { detectHorizontalDragGestures( onDragStart = { drag = 0f }, @@ -1484,31 +1499,30 @@ private fun KeysBar( change.consume() }, ) - } - .padding(horizontal = 8.dp), + }, verticalAlignment = Alignment.CenterVertically, ) { listOf(R.string.menu_keyboard, R.string.menu_shortcuts).forEachIndexed { index, title -> - Text( - stringResource(title), - color = if (tab == index) Color.White else Color.White.copy(alpha = 0.6f), - fontWeight = if (tab == index) FontWeight.Bold else FontWeight.Normal, - fontSize = 12.sp, - modifier = Modifier.clickable { onTab(index) } - .padding(horizontal = 12.dp, vertical = 6.dp), - ) - } - if (tab == 1) { - Spacer(Modifier.weight(1f)) - IconButton(onClick = onHide, modifier = Modifier.size(32.dp)) { - Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + Box( + Modifier.weight(1f).height(40.dp).clickable { onTab(index) }, + contentAlignment = Alignment.Center, + ) { + Text( + stringResource(title), + color = if (tab == index) Color.White else Color.White.copy(alpha = 0.6f), + fontWeight = if (tab == index) FontWeight.Bold else FontWeight.Normal, + fontSize = 12.sp, + ) } } + IconButton(onClick = onHide, modifier = Modifier.size(40.dp)) { + Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + } } } if (tab == 1 && hasShortcuts) { var drag = 0f - FlowRow( + Column( modifier = Modifier.fillMaxWidth().weight(1f) .verticalScroll(rememberScrollState()) .pointerInput(tab) { @@ -1521,12 +1535,9 @@ private fun KeysBar( }, ) } - .padding(8.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), + .padding(top = 4.dp), ) { - AirhandApp.instance.shortcuts.list(os).forEach { item -> - Key(item.title ?: labels[item.id]?.let { context.getString(it) } ?: item.id, compact) { kb.chord(item.codes) } - } + Shortcuts(os, { kb.chord(it) }, panel = true) } } else { Row(verticalAlignment = Alignment.CenterVertically) { @@ -1551,8 +1562,10 @@ private fun KeysBar( Key("PgDn", compact) { kb.press("PageDown") } for (i in 1..12) Key("F$i", compact) { kb.press("F$i") } } - IconButton(onClick = onHide, modifier = Modifier.size(if (compact) 36.dp else 44.dp)) { - Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + if (!hasShortcuts) { + IconButton(onClick = onHide, modifier = Modifier.size(if (compact) 36.dp else 44.dp)) { + Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + } } } } @@ -1560,15 +1573,30 @@ private fun KeysBar( } @Composable -private fun Key(label: String, compact: Boolean = false, onClick: () -> Unit) { +private fun Key(label: String, compact: Boolean = false, feedback: Boolean = false, onClick: () -> Unit) { + val interaction = remember { MutableInteractionSource() } + val pressed by interaction.collectIsPressedAsState() + var flashSerial by remember { mutableIntStateOf(0) } + val view = LocalView.current + LaunchedEffect(flashSerial) { + if (flashSerial > 0) { + delay(220) + flashSerial = 0 + } + } + val click = if (feedback) Modifier.clickable(interactionSource = interaction, indication = null) { + onClick() + view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP) + flashSerial++ + } else Modifier.clickable(onClick = onClick) Box( Modifier .padding(horizontal = 2.dp, vertical = if (compact) 3.dp else 4.dp) .widthIn(min = if (compact) 40.dp else 44.dp) .height(if (compact) 30.dp else 36.dp) .clip(RoundedCornerShape(8.dp)) - .background(Color(0xFF2C3244)) - .clickable(onClick = onClick) + .background(if (feedback && (pressed || flashSerial > 0)) Brand.accent else Color(0xFF2C3244)) + .then(click) .padding(horizontal = if (compact) 8.dp else 10.dp), contentAlignment = Alignment.Center, ) { diff --git a/docs/android.md b/docs/android.md index 95ae8acc..2f449809 100644 --- a/docs/android.md +++ b/docs/android.md @@ -52,7 +52,7 @@ After you pinch to zoom the local view, a moment after your fingers stop the app - **Keyboard**: the picture doesn't shrink: when it fits above the keyboard it moves up there, otherwise (landscape, or a phone held upright on the other side) the part around the pointer moves above the keyboard and follows the pointer, and everything moves back once the keyboard is hidden; in landscape the extra keys row is shorter and the stats overlay is hidden for the time being. A row of extra keys sits on top of the keyboard: Esc, Tab, Ctrl, Alt, Shift, Win (⌘ for Macs), arrows, Home / End, PgUp / PgDn, Del, F1–F12. Modifiers are sticky: tap once for the next key only, again to lock, again to release (tap Ctrl, then type c = Ctrl+C). While an IME composes (pinyin etc.) the text shows above the extra keys and is only sent once chosen - When controlling a phone, **Back / Home / Recents** keys sit below the picture (can be turned off in Settings), and Keyboard & input in the menu holds system actions: notifications, quick settings, screenshot, lock screen, power menu, volume (whichever the phone supports). For computers it lists shortcuts for the remote OS (Windows / macOS / Linux) - When controlling a computer, you can add or edit keyboard combinations and move them up or down in Reorder mode. The list is saved locally on this Android device, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C -- With the keyboard open for a remote computer, tap Keyboard / Shortcuts above it or swipe right on those tabs to show the saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Use the menu's shortcuts page to edit the list +- With the keyboard open for a remote computer, tap the half-width Keyboard / Shortcuts tabs above it or swipe right on the tabs to show saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Add, edit, move, and remove custom shortcuts directly in the panel - A connected mouse and keyboard map directly to the remote mouse and keyboard. Over the picture the mouse shows just the remote cursor, without the system pointer on top; in Settings its wheel can be reversed, set to a speed (5%–200%) and to **Adaptive** (the default: a slow single notch moves half as far, spinning quickly speeds up to twice as far) or **Linear** (the same distance for every notch), and **Smooth mouse scrolling** splits each notch into a few small steps about 16 ms apart (the same total; closer to a trackpad on a Mac). Ctrl / ⌘ shortcuts on the keyboard go to the remote computer even while an input method is active, and keys still held are let go when the menu opens or the app goes to the background. When controlling a Mac, **Swap Ctrl and ⌘ Command** under Keyboard & input in the menu makes the keyboard's Ctrl work as ⌘ and the Win key as Control (copy with Ctrl+C on a Windows keyboard); the extra keys row and the shortcuts in the menu don't change. It's off by default and remembered per computer, as in the desktop console - **Games**: when the remote computer hides its cursor (turning the camera in a game), trackpad slides and touch drags send how far you moved instead of a position, so the camera turns smoothly and doesn't stop at the edge of the picture; a connected mouse is captured (Android 8+). **Mouse lock** under Mouse & touch in the menu does the same all the time, e.g. for Macs, which can't report a hidden cursor. For games played with the keyboard, see game keys below - **Privacy mode**: under Video & display in the menu when the remote is Windows or a Mac (with a version that supports it). It blanks all of the remote monitors and disables its keyboard and mouse, so only you can see and control it; the switch shows the current state (turning on, on, why it isn't available), and a failure also shows at the top of the picture. It turns off by itself after you disconnect and stays on while reconnecting. See [Usage → Privacy mode](usage.md#privacy-mode) diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index 5e9a0731..5aea9b00 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -52,7 +52,7 @@ - **键盘**:打开后画面不缩小:键盘上面放得下就挪到键盘上面,放不下(横屏、对方是竖着的手机)就把指针所在的地方挪到键盘上面,移动指针时跟着走,收起键盘后回到原来的位置;横屏时特殊键那一排矮一些,状态信息先不显示。键盘上面多一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12。修饰键是“粘滞”的:点一下只对下一个键有效,再点一下锁定,再点取消(例如点 Ctrl 再在键盘上打 c = Ctrl+C)。拼音等输入法组字时文字显示在特殊键上方,选好字才发过去 - 控制手机时画面下方有**返回 / 主页 / 最近任务**三个键(设置里可以关掉),菜单 → 键盘与输入里是通知栏、快捷设置、截屏、锁屏、电源菜单、音量等系统操作(对方手机能执行哪些就显示哪些);控制电脑时那里是按对方系统列出的快捷键(Windows / macOS / Linux) - 控制电脑时,可以添加、编辑组合键,在“调整顺序”模式里用上下箭头排序。列表保存在这台 Android 设备上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C -- 控制电脑并打开键盘时,可以点键盘上方的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。编辑列表仍在菜单的快捷键页 +- 控制电脑并打开键盘时,可以点键盘上方各占半行的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。快捷键面板内可直接添加、编辑、上下调整顺序和删除自定义项 - 外接鼠标、键盘直接对应远端的鼠标、键盘。鼠标在画面上时只显示对方的光标,不会再叠一个系统指针。滚轮在设置里可以改速度(5%–200%)、方向和换算方式:**自适应加速**(默认:慢慢滚一格只走半格,连着快滚加速到两倍)或**固定线性**(每格一样远);还可以打开**平滑滚动**(每一格拆成几小步、约 16 ms 一步发过去,加起来不变,控制 Mac 时更像触控板)。键盘上 Ctrl / ⌘ 的组合键不会被本机的输入法拿走;打开菜单、切到后台时按着的键都会松开。控制 Mac 时,菜单 → 键盘与输入里的**互换 Ctrl 和 ⌘ Command** 让键盘上的 Ctrl 当 ⌘ 用、Win 键当 Ctrl 用(用 Windows 键盘按 Ctrl+C 复制);键盘上方的特殊键和菜单里的快捷键不变。默认关闭,每台电脑分别记住,和桌面控制台一样 - **游戏**:对方电脑隐藏了光标时(游戏里转视角),触控板的滑动、触屏的拖动发的是“移动了多少”而不是位置,视角转得顺,拖到画面边上也不会停;外接鼠标会被抓住(Android 8+)。菜单 → 鼠标与触控里的**锁定鼠标**让它一直这样,例如对方是 Mac(检测不到光标隐藏)时。要按键盘的游戏用下面的游戏按键 - **防窥模式**:对方是 Windows、Mac(而且是支持它的版本)时菜单 → 视频与画面里有它。打开后对方所有的显示器黑屏、键盘鼠标不起作用,只有你看得到、操作得了;开关下面写着现在怎么样(正在打开、开着、开不了的原因),没能打开时画面上方也会提示。断开连接后自动恢复,断线重连时接着保持。详见[使用说明 → 防窥模式](usage.zh-CN.md#防窥模式) diff --git a/docs/ios.md b/docs/ios.md index b14e4381..1cb4e4fe 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -43,7 +43,7 @@ After zooming in, Airhand asks the remote for a sharper picture once your finger - **Mouse / trackpad (iPad)**: move, left / right / middle / side buttons and the wheel map to the remote; the remote's cursor shape is drawn locally. When the remote hides its cursor (games) or “Lock mouse” is on, the pointer is **locked** and raw movement is sent; hold Esc to release (iPadOS only allows pointer lock in full screen) - Phones get **Back / Home / Recents** below the picture (can be turned off) and their system actions on the shortcuts page; computers get shortcuts for their OS - For a remote computer, the shortcuts page lets you add or edit keyboard combinations and reorder them with Edit. The list is saved locally on this iPhone or iPad, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C -- With the keyboard open for a remote computer, tap Keyboard / Shortcuts above it or swipe right on those tabs to show the saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Use the menu's shortcuts page to edit the list +- With the keyboard open for a remote computer, tap the half-width Keyboard / Shortcuts tabs above it or swipe right on the tabs to show saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Add, edit, move, and remove custom shortcuts directly in the panel - **Clipboard**: text copied on the remote lands in this device's clipboard; the menu can send this device's text to the remote clipboard or type it (iOS asks once to allow pasting) - **Files**: files copied on the remote show a prompt; “Save to Files” transfers them into Files › On My iPhone › Airhand. “Send files” puts files from this device on the remote clipboard to paste there (only a list is sent until pasted) - **Sound** with adaptive jitter buffer; **A/V sync** for videos; **microphone** forwarding to Windows, macOS 14.2+ and Linux hosts, with system echo cancellation diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index 982551f3..ee968eac 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -44,7 +44,7 @@ - **外接鼠标 / 触控板(iPad)**:移动、左右中键、侧键、滚轮直接对应远端;本机不显示系统指针,画的是对方的光标形状。对方隐藏了光标(游戏里转视角)或者打开了“锁定鼠标”时,**锁定指针**、发原始移动量;长按 Esc 放开(iPadOS 只在 App 全屏时允许锁定指针) - 控制手机时画面下方有**返回 / 主页 / 最近任务**(设置里可以关掉),快捷键页里是对方手机支持的系统操作;控制电脑时快捷键按对方系统列出(Windows / macOS / Linux) - 控制电脑时,快捷键页可以添加、编辑组合键,点“编辑”后拖动调整顺序。列表保存在这台 iPhone 或 iPad 上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C -- 控制电脑并打开键盘时,可以点键盘上方的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。编辑列表仍在菜单的快捷键页 +- 控制电脑并打开键盘时,可以点键盘上方各占半行的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。快捷键面板内可直接添加、编辑、上下调整顺序和删除自定义项 - **剪贴板**:对方复制的文字自动放进本机剪贴板;菜单 → 剪贴板可以把本机复制的文字发到对方的剪贴板,或者直接打进对方的输入框(读本机剪贴板时 iOS 会问一次“允许粘贴”) - **文件**:对方复制的文件会提示“对方复制了 N 项”,点“保存到‘文件’”才传,存在“文件 › 我的 iPhone › Airhand”;菜单 → 发送文件选好本机的文件,放进对方的剪贴板,到对方那里粘贴(复制时只发清单,粘贴时才传) - **声音**:对方的声音同步过来(Opus + 自适应抖动缓冲,和桌面版同一套做法);**音画同步**看视频时打开。**麦克风**:对方能接收时(Windows、macOS 14.2+、Linux 被控端),菜单里打开就把本机的麦克风转发过去,开着系统的回声消除 diff --git a/ios/Airhand/Session/SessionController.swift b/ios/Airhand/Session/SessionController.swift index 1b8e2cfa..536c4111 100644 --- a/ios/Airhand/Session/SessionController.swift +++ b/ios/Airhand/Session/SessionController.swift @@ -159,6 +159,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private let keyField = KeyField() private let keyboard = KeyboardState() private let inputPage = InputPageState() + private lazy var shortcutModel = ShortcutPanelModel(os: session.os) private let game = GameLayerView() private let menuButton = FloatingMenuButton() private var overlayHost: UIHostingController! @@ -166,6 +167,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private var navHost: UIHostingController? private var accessory: UIHostingController! private var shortcutsInput: UIHostingController! + private var shortcutsInputView: UIInputView! private var zoom: CGFloat = 1 private var offset: CGPoint = .zero @@ -241,10 +243,21 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract keyField.onComposing = { [weak self] s in self?.keyboard.composing = s } keyField.onPresses = { [weak self] p, down in self?.hardwareKeys(p, down) ?? false } shortcutsInput = UIHostingController(rootView: ShortcutInputPanel( - state: keyboard, os: session.os, switchPage: { [weak self] page in self?.setInputPage(page) } + state: keyboard, model: shortcutModel, + switchPage: { [weak self] page in self?.setInputPage(page) }, + edit: { [weak self] item in self?.editShortcut(item) } )) - shortcutsInput.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 260) - shortcutsInput.view.autoresizingMask = [.flexibleWidth] + shortcutsInputView = UIInputView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 260), + inputViewStyle: .keyboard) + shortcutsInputView.backgroundColor = UIColor(Theme.bg) + shortcutsInput.view.translatesAutoresizingMaskIntoConstraints = false + shortcutsInputView.addSubview(shortcutsInput.view) + NSLayoutConstraint.activate([ + shortcutsInput.view.topAnchor.constraint(equalTo: shortcutsInputView.topAnchor), + shortcutsInput.view.leadingAnchor.constraint(equalTo: shortcutsInputView.leadingAnchor), + shortcutsInput.view.trailingAnchor.constraint(equalTo: shortcutsInputView.trailingAnchor), + shortcutsInput.view.bottomAnchor.constraint(equalTo: shortcutsInputView.bottomAnchor) + ]) accessory = UIHostingController(rootView: KeyBar( state: keyboard, os: session.os, page: inputPage, switchPage: { [weak self] page in self?.setInputPage(page) }, @@ -253,7 +266,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract accessory.view.backgroundColor = .clear accessory.sizingOptions = [.intrinsicContentSize] accessory.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, - height: session.os.isPhone ? 54 : 86) + height: session.os.isPhone ? 54 : 90) accessory.view.autoresizingMask = [.flexibleWidth] keyField.inputAccessoryView = accessory.view view.addSubview(keyField) @@ -801,10 +814,31 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private func setInputPage(_ page: Int) { guard inputPage.selected != page else { return } inputPage.selected = page - keyField.inputView = page == 1 ? shortcutsInput.view : nil + if page == 1 { shortcutModel.reload() } + accessory.view.frame.size.height = session.os.isPhone ? 54 : (page == 1 ? 40 : 90) + accessory.view.invalidateIntrinsicContentSize() + keyField.inputView = page == 1 ? shortcutsInputView : nil if keyField.isFirstResponder { keyField.reloadInputViews() } } + private func editShortcut(_ item: SavedShortcut) { + setKeyboard(false) + let host = UIHostingController(rootView: ShortcutEditor( + shortcut: item, os: session.os, + save: { [weak self] changed in self?.shortcutModel.upsert(changed) }, + close: { [weak self] in + guard let self else { return } + self.dismiss(animated: true) { [weak self] in + self?.setKeyboard(true) + self?.setInputPage(1) + } + } + )) + host.overrideUserInterfaceStyle = .dark + host.isModalInPresentation = true + present(host, animated: true) + } + @objc private func keyboardFrame(_ n: Notification) { var h: CGFloat = 0 if n.name != UIResponder.keyboardWillHideNotification, let f = n.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { diff --git a/ios/Airhand/Session/SessionViews.swift b/ios/Airhand/Session/SessionViews.swift index cdc63d3a..161ea727 100644 --- a/ios/Airhand/Session/SessionViews.swift +++ b/ios/Airhand/Session/SessionViews.swift @@ -166,13 +166,12 @@ struct KeyBar: View { .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 4) } if hasShortcuts { - HStack(spacing: 18) { - tab(L.t("menu_keyboard"), index: 0) - tab(L.t("menu_shortcuts"), index: 1) - Spacer() + HStack(spacing: 0) { + tab(L.t("menu_keyboard"), index: 0).frame(maxWidth: .infinity) + tab(L.t("menu_shortcuts"), index: 1).frame(maxWidth: .infinity) + hideButton.frame(width: 46) } - .padding(.horizontal, 12) - .frame(height: 32) + .frame(height: 40) .contentShape(Rectangle()) .simultaneousGesture(DragGesture(minimumDistance: 25).onEnded { value in if value.translation.width > 40 { switchPage(1) } @@ -182,8 +181,8 @@ struct KeyBar: View { } if page.selected == 0 || !hasShortcuts { HStack(spacing: 0) { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { ForEach(keys, id: \.self) { k in if k.hasPrefix("MOD:") { let m = String(k.dropFirst(4)) @@ -199,27 +198,12 @@ struct KeyBar: View { } } } + } + .padding(.horizontal, 8) } - .padding(.horizontal, 8) - } - Button(action: hide) { - Image(systemName: "keyboard.chevron.compact.down").font(.system(size: 17, weight: .semibold)) - .foregroundStyle(.white).frame(width: 46, height: 40) - } - .accessibilityLabel(L.t("hide_keyboard")) - } - .frame(height: 50) - .background(.ultraThinMaterial) - } else { - Button(action: hide) { - Image(systemName: "keyboard.chevron.compact.down") - .font(.system(size: 17, weight: .semibold)) - .foregroundStyle(.white) - .frame(maxWidth: .infinity, alignment: .trailing) - .padding(.trailing, 14) + if !hasShortcuts { hideButton.frame(width: 46) } } - .accessibilityLabel(L.t("hide_keyboard")) - .frame(height: 30) + .frame(height: 50) .background(.ultraThinMaterial) } } @@ -231,8 +215,8 @@ struct KeyBar: View { Text(label) .font(.caption.weight(page.selected == index ? .bold : .medium)) .foregroundStyle(page.selected == index ? .white : .white.opacity(0.6)) - .padding(.horizontal, 8) - .frame(height: 32) + .frame(maxWidth: .infinity, minHeight: 40) + .contentShape(Rectangle()) .overlay(alignment: .bottom) { if page.selected == index { Capsule().fill(Theme.c2).frame(height: 2) } } @@ -240,6 +224,18 @@ struct KeyBar: View { .buttonStyle(.plain) } + private var hideButton: some View { + Button(action: hide) { + Image(systemName: "keyboard.chevron.compact.down") + .font(.system(size: 17, weight: .semibold)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, minHeight: 40) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(L.t("hide_keyboard")) + } + private func keyButton(_ label: String, highlight: KeyboardState.Sticky, _ f: @escaping () -> Void) -> some View { Button(action: f) { Text(label).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white) @@ -259,31 +255,86 @@ struct KeyBar: View { /// Replaces the system keyboard while the shortcut tab is selected. struct ShortcutInputPanel: View { let state: KeyboardState - let os: OsKind + let model: ShortcutPanelModel let switchPage: (Int) -> Void - @State private var items: [SavedShortcut] = [] + let edit: (SavedShortcut) -> Void + @State private var flashedShortcut: String? + @State private var flashGeneration = 0 var body: some View { - ScrollView { - LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) { - ForEach(items) { item in - Button { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - state.chord(item.codes) - } label: { - Text(item.label()) - .font(.subheadline.weight(.medium)) - .foregroundStyle(.white) - .frame(maxWidth: .infinity, minHeight: 40) - .background(Color.white.opacity(0.12), in: RoundedRectangle(cornerRadius: 9)) + VStack(spacing: 0) { + HStack { + Button { edit(SavedShortcut(id: "custom:\(UUID().uuidString)", title: "", codes: [])) } label: { + Label(L.t("shortcut_add"), systemImage: "plus") + } + Spacer() + Button(model.editing ? L.t("done") : L.t("shortcut_reorder")) { + model.editing.toggle() + } + } + .font(.subheadline.weight(.medium)) + .foregroundStyle(.white) + .padding(.horizontal, 14) + .frame(height: 38) + + ScrollView { + Group { + if model.editing { + LazyVStack(spacing: 6) { + ForEach(Array(model.items.indices), id: \.self) { index in + let item = model.items[index] + HStack(spacing: 4) { + Text(item.label()).font(.subheadline).lineLimit(1) + .frame(maxWidth: .infinity, alignment: .leading) + action("pencil", L.t("shortcut_edit")) { edit(item) } + action("arrow.up", L.t("shortcut_reorder"), disabled: index == 0) { + model.move(index, by: -1) + } + action("arrow.down", L.t("shortcut_reorder"), disabled: index == model.items.count - 1) { + model.move(index, by: 1) + } + if item.id.hasPrefix("custom:") { + action("trash", L.t("delete")) { model.delete(item) } + } + } + .foregroundStyle(.white) + .padding(.leading, 12) + .padding(.trailing, 4) + .frame(height: 42) + .background(Color.white.opacity(0.12), in: RoundedRectangle(cornerRadius: 9)) + } + } + } else { + LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) { + ForEach(model.items) { item in + Button { + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + state.chord(item.codes) + flashGeneration += 1 + let generation = flashGeneration + flashedShortcut = item.id + DispatchQueue.main.asyncAfter(deadline: .now() + 0.22) { + if flashGeneration == generation { flashedShortcut = nil } + } + } label: { + Text(item.label()) + .font(.subheadline.weight(.medium)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, minHeight: 40) + } + .buttonStyle(ShortcutTileStyle(highlighted: flashedShortcut == item.id)) + } + } } - .buttonStyle(.plain) } + .padding(.horizontal, 10) + .padding(.bottom, 10) } - .padding(10) } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .background(Theme.bg) - .onAppear { items = ShortcutProfiles.load(for: os) } + .ignoresSafeArea(.container, edges: .top) + .onAppear { model.reload() } .simultaneousGesture(DragGesture(minimumDistance: 35).onEnded { value in if value.translation.width < -60 && abs(value.translation.width) > abs(value.translation.height) { switchPage(0) @@ -291,6 +342,32 @@ struct ShortcutInputPanel: View { }) .preferredColorScheme(.dark) } + + private func action(_ icon: String, _ label: String, disabled: Bool = false, + _ perform: @escaping () -> Void) -> some View { + Button(action: perform) { + Image(systemName: icon).font(.system(size: 15, weight: .medium)) + .frame(width: 36, height: 40).contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(label) + .disabled(disabled) + } +} + +private struct ShortcutTileStyle: ButtonStyle { + let highlighted: Bool + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .background( + configuration.isPressed ? Theme.c2.opacity(0.85) : + (highlighted ? Theme.c2.opacity(0.65) : Color.white.opacity(0.12)), + in: RoundedRectangle(cornerRadius: 9) + ) + .scaleEffect(configuration.isPressed ? 0.97 : 1) + .animation(.easeOut(duration: 0.12), value: configuration.isPressed) + } } /// 手势说明(第一次进入远程画面时,菜单里也能打开) diff --git a/ios/Airhand/Session/Shortcuts.swift b/ios/Airhand/Session/Shortcuts.swift index 0d90f3a9..1f839e25 100644 --- a/ios/Airhand/Session/Shortcuts.swift +++ b/ios/Airhand/Session/Shortcuts.swift @@ -1,4 +1,5 @@ import SwiftUI +import Observation /// A shortcut is local to the controller. The wire protocol still receives ordinary key edges. struct SavedShortcut: Codable, Identifiable, Equatable { @@ -50,19 +51,59 @@ enum ShortcutProfiles { } } +@Observable final class ShortcutPanelModel { + let os: OsKind + var items: [SavedShortcut] + var editing = false + + init(os: OsKind) { + self.os = os + items = ShortcutProfiles.load(for: os) + } + + func reload() { items = ShortcutProfiles.load(for: os) } + + func upsert(_ item: SavedShortcut) { + if let index = items.firstIndex(where: { $0.id == item.id }) { + items[index] = item + } else { + items.append(item) + } + persist() + } + + func move(_ index: Int, by offset: Int) { + let destination = index + offset + guard items.indices.contains(index), items.indices.contains(destination) else { return } + items.swapAt(index, destination) + persist() + } + + func delete(_ item: SavedShortcut) { + guard item.id.hasPrefix("custom:") else { return } + items.removeAll { $0.id == item.id } + persist() + } + + private func persist() { ShortcutProfiles.save(items, for: os) } +} + struct ShortcutEditor: View { let original: SavedShortcut let os: OsKind let save: (SavedShortcut) -> Void + let close: (() -> Void)? @Environment(\.dismiss) private var dismiss @State private var title: String @State private var codes: [String] @State private var picking = false - init(shortcut: SavedShortcut, os: OsKind, save: @escaping (SavedShortcut) -> Void) { + init(shortcut: SavedShortcut, os: OsKind, save: @escaping (SavedShortcut) -> Void, + close: (() -> Void)? = nil) { original = shortcut self.os = os self.save = save + self.close = close _title = State(initialValue: shortcut.title ?? (shortcut.id.hasPrefix("custom:") ? "" : L.t(shortcut.id))) _codes = State(initialValue: shortcut.codes) } @@ -87,7 +128,7 @@ struct ShortcutEditor: View { .navigationTitle(L.t("shortcut_edit")) .navigationBarTitleDisplayMode(.inline) .toolbar { - ToolbarItem(placement: .cancellationAction) { Button(L.t("cancel")) { dismiss() } } + ToolbarItem(placement: .cancellationAction) { Button(L.t("cancel")) { finish() } } ToolbarItem(placement: .confirmationAction) { Button(L.t("ok")) { var item = original @@ -95,7 +136,7 @@ struct ShortcutEditor: View { item.title = name == L.t(original.id) && !original.id.hasPrefix("custom:") ? nil : name item.codes = codes save(item) - dismiss() + finish() } .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || codes.isEmpty) } @@ -106,4 +147,8 @@ struct ShortcutEditor: View { } .preferredColorScheme(.dark) } + + private func finish() { + if let close { close() } else { dismiss() } + } } diff --git a/ios/Shared/L10n.swift b/ios/Shared/L10n.swift index 1cd8c417..3c22b820 100644 --- a/ios/Shared/L10n.swift +++ b/ios/Shared/L10n.swift @@ -158,7 +158,7 @@ enum L { "game_mouse_left": "左键", "game_mouse_right": "右键", "game_mouse_middle": "中键", "game_wheel_up": "滚轮↑", "game_wheel_down": "滚轮↓", "game_duplicate_item": "复制", "game_empty_layout_hint": "还没有按钮,点上面的 + 添加", "game_tip": "按住按钮就是按着那个键;空白处拖动在游戏隐藏光标时转视角。菜单 → 游戏按键 → 编辑布局可以自己摆。", // 快捷键 - "shortcut_add": "添加快捷键", "shortcut_edit": "编辑快捷键", "shortcut_name": "名称", "shortcut_keys": "按键", "shortcut_pick": "选择按键", + "shortcut_add": "添加快捷键", "shortcut_edit": "编辑快捷键", "shortcut_reorder": "调整顺序", "shortcut_name": "名称", "shortcut_keys": "按键", "shortcut_pick": "选择按键", "shortcut_pick_hint": "按顺序选择最多 4 个键;先选修饰键,最后选主键", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab 切换窗口", "combo_win": "Win 开始菜单", "combo_win_d": "Win + D 显示桌面", "combo_win_e": "Win + E 文件资源管理器", "combo_win_l": "Win + L 锁屏", @@ -337,7 +337,7 @@ enum L { "game_group_function": "Function keys", "game_group_nav": "Navigation & editing", "game_group_symbols": "Symbols", "game_mouse_left": "Left", "game_mouse_right": "Right", "game_mouse_middle": "Middle", "game_wheel_up": "Wheel ↑", "game_wheel_down": "Wheel ↓", "game_duplicate_item": "Duplicate", "game_empty_layout_hint": "No buttons yet — tap + above to add one", "game_tip": "Hold a button to hold its key; drag on empty space to turn the view when a game hides the cursor. Menu → Game controls → Edit layout to arrange them.", - "shortcut_add": "Add shortcut", "shortcut_edit": "Edit shortcut", "shortcut_name": "Name", "shortcut_keys": "Keys", "shortcut_pick": "Choose keys", + "shortcut_add": "Add shortcut", "shortcut_edit": "Edit shortcut", "shortcut_reorder": "Reorder", "shortcut_name": "Name", "shortcut_keys": "Keys", "shortcut_pick": "Choose keys", "shortcut_pick_hint": "Choose up to 4 keys in order: modifiers first, main key last", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab switch windows", "combo_win": "Win Start menu", "combo_win_d": "Win + D show desktop", "combo_win_e": "Win + E File Explorer", "combo_win_l": "Win + L lock", From 6fa28f2575fdad73ade2010bc0598ad9eeb4706f Mon Sep 17 00:00:00 2001 From: Dlouxgit <57781857+Dlouxgit@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:24:54 +0800 Subject: [PATCH 4/6] Polish mobile shortcut feedback and keyboard layout --- .../java/app/airhand/android/ui/session/PhoneSession.kt | 2 +- ios/Airhand/Session/SessionController.swift | 9 ++++++--- ios/Airhand/Session/SessionViews.swift | 8 ++++++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt index 8a324da2..74f6ceaf 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt @@ -1595,7 +1595,7 @@ private fun Key(label: String, compact: Boolean = false, feedback: Boolean = fal .widthIn(min = if (compact) 40.dp else 44.dp) .height(if (compact) 30.dp else 36.dp) .clip(RoundedCornerShape(8.dp)) - .background(if (feedback && (pressed || flashSerial > 0)) Brand.accent else Color(0xFF2C3244)) + .background(if (feedback && (pressed || flashSerial > 0)) Color(0xFF474A53) else Color(0xFF2C3244)) .then(click) .padding(horizontal = if (compact) 8.dp else 10.dp), contentAlignment = Alignment.Center, diff --git a/ios/Airhand/Session/SessionController.swift b/ios/Airhand/Session/SessionController.swift index 536c4111..1cb53d26 100644 --- a/ios/Airhand/Session/SessionController.swift +++ b/ios/Airhand/Session/SessionController.swift @@ -243,13 +243,15 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract keyField.onComposing = { [weak self] s in self?.keyboard.composing = s } keyField.onPresses = { [weak self] p, down in self?.hardwareKeys(p, down) ?? false } shortcutsInput = UIHostingController(rootView: ShortcutInputPanel( - state: keyboard, model: shortcutModel, + state: keyboard, os: session.os, page: inputPage, model: shortcutModel, switchPage: { [weak self] page in self?.setInputPage(page) }, + hide: { [weak self] in self?.setKeyboard(false) }, edit: { [weak self] item in self?.editShortcut(item) } )) - shortcutsInputView = UIInputView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 260), + shortcutsInputView = UIInputView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 300), inputViewStyle: .keyboard) shortcutsInputView.backgroundColor = UIColor(Theme.bg) + shortcutsInput.view.backgroundColor = UIColor(Theme.bg) shortcutsInput.view.translatesAutoresizingMaskIntoConstraints = false shortcutsInputView.addSubview(shortcutsInput.view) NSLayoutConstraint.activate([ @@ -815,8 +817,9 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract guard inputPage.selected != page else { return } inputPage.selected = page if page == 1 { shortcutModel.reload() } - accessory.view.frame.size.height = session.os.isPhone ? 54 : (page == 1 ? 40 : 90) + accessory.view.frame.size.height = session.os.isPhone ? 54 : 90 accessory.view.invalidateIntrinsicContentSize() + keyField.inputAccessoryView = page == 1 ? nil : accessory.view keyField.inputView = page == 1 ? shortcutsInputView : nil if keyField.isFirstResponder { keyField.reloadInputViews() } } diff --git a/ios/Airhand/Session/SessionViews.swift b/ios/Airhand/Session/SessionViews.swift index 161ea727..5a0e13de 100644 --- a/ios/Airhand/Session/SessionViews.swift +++ b/ios/Airhand/Session/SessionViews.swift @@ -255,14 +255,19 @@ struct KeyBar: View { /// Replaces the system keyboard while the shortcut tab is selected. struct ShortcutInputPanel: View { let state: KeyboardState + let os: OsKind + let page: InputPageState let model: ShortcutPanelModel let switchPage: (Int) -> Void + let hide: () -> Void let edit: (SavedShortcut) -> Void @State private var flashedShortcut: String? @State private var flashGeneration = 0 var body: some View { VStack(spacing: 0) { + KeyBar(state: state, os: os, page: page, switchPage: switchPage, hide: hide) + HStack { Button { edit(SavedShortcut(id: "custom:\(UUID().uuidString)", title: "", codes: [])) } label: { Label(L.t("shortcut_add"), systemImage: "plus") @@ -361,8 +366,7 @@ private struct ShortcutTileStyle: ButtonStyle { func makeBody(configuration: Configuration) -> some View { configuration.label .background( - configuration.isPressed ? Theme.c2.opacity(0.85) : - (highlighted ? Theme.c2.opacity(0.65) : Color.white.opacity(0.12)), + Color.white.opacity(configuration.isPressed ? 0.29 : (highlighted ? 0.23 : 0.12)), in: RoundedRectangle(cornerRadius: 9) ) .scaleEffect(configuration.isPressed ? 0.97 : 1) From 5211c67e6b9dddbac72085a6708a143c957a50e3 Mon Sep 17 00:00:00 2001 From: sqlpxc Date: Thu, 3 Dec 2026 15:49:52 +0800 Subject: [PATCH 5/6] Android: share one shortcut list, toggle the panel from the extra keys row --- .../app/airhand/android/data/Shortcuts.kt | 77 +++- .../app/airhand/android/ui/session/GameUi.kt | 15 +- .../android/ui/session/PhoneSession.kt | 357 +++++++++--------- .../app/src/main/res/values-zh/strings.xml | 3 +- android/app/src/main/res/values/strings.xml | 3 +- .../app/airhand/android/data/ShortcutsTest.kt | 32 +- 6 files changed, 291 insertions(+), 196 deletions(-) diff --git a/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt b/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt index 20c04186..072e017d 100644 --- a/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt +++ b/android/app/src/main/java/app/airhand/android/data/Shortcuts.kt @@ -5,23 +5,45 @@ import androidx.annotation.StringRes import app.airhand.android.R import app.airhand.android.core.OsKind import app.airhand.android.core.optStringOrNull +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import org.json.JSONArray import org.json.JSONObject import java.io.File import java.util.UUID -/** Controller-side shortcut; codes are W3C KeyboardEvent.code values sent by the existing input protocol. */ +/** + * 快捷键(控制电脑时):只存在控制端,按的是 W3C `KeyboardEvent.code`,用现有的按键协议发,被控端不用改。 + * 内置的 [id] 是它的字符串资源名,[title] 为空时显示内置的名字(跟着语言变);自己加的 [id] 以 `custom:` 开头 + */ data class SavedShortcut(val id: String, val title: String?, val codes: List) { + /** 自己加的(只有这些能删) */ + val custom: Boolean get() = id.startsWith(CUSTOM) + fun toJson(): JSONObject = JSONObject().put("id", id).put("title", title ?: JSONObject.NULL).put("codes", JSONArray(codes)) companion object { - fun custom() = SavedShortcut("custom:${UUID.randomUUID()}", "", emptyList()) + const val CUSTOM = "custom:" + + /** 一个快捷键最多几个键 */ + const val MAX_KEYS = 4 + + private val MODIFIERS = setOf("ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight", "AltLeft", "AltRight", "MetaLeft", "MetaRight") + + fun custom() = SavedShortcut(CUSTOM + UUID.randomUUID(), null, emptyList()) + + /** 键盘上的键(W3C code 只有字母数字):鼠标键、滚轮、手柄的按钮(`mouse:left`、`pad:a`)不行 */ + fun isKey(code: String): Boolean = code.length in 1..32 && code.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' } + + /** 修饰键放在前面:按顺序按下、倒序松开,先选了 C 再选 Ctrl 也是 Ctrl+C */ + fun ordered(codes: List): List = codes.sortedBy { if (it in MODIFIERS) 0 else 1 } fun parse(o: JSONObject): SavedShortcut? { val id = o.optString("id").takeIf { it.isNotBlank() } ?: return null val a = o.optJSONArray("codes") ?: return null val codes = (0 until a.length()).map { a.optString(it) } - if (codes.isEmpty() || codes.size > 4 || codes.any { !GameBind.valid(it) || it.startsWith("mouse:") || it.startsWith("wheel:") }) return null + if (codes.isEmpty() || codes.size > MAX_KEYS || !codes.all(::isKey)) return null return SavedShortcut(id, o.optStringOrNull("title")?.takeIf { it.isNotBlank() }, codes) } } @@ -31,7 +53,11 @@ data class ShortcutPreset(val id: String, @StringRes val label: Int, val codes: fun saved() = SavedShortcut(id, null, codes) } +/** 内置的快捷键:按被控端的系统(Mac 的复制是 ⌘C,Windows / Linux 是 Ctrl+C) */ object ShortcutDefaults { + /** 有快捷键的系统:电脑。手机那边是系统操作(通知栏、截屏……) */ + fun supports(os: OsKind): Boolean = os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX + fun forOs(os: OsKind): List = when (os) { OsKind.MAC -> listOf( ShortcutPreset("combo_cmd_tab", R.string.combo_cmd_tab, listOf("MetaLeft", "Tab")), @@ -60,31 +86,58 @@ object ShortcutDefaults { ShortcutPreset("combo_undo", R.string.combo_undo, listOf("ControlLeft", "KeyZ")), ShortcutPreset("combo_print_screen", R.string.combo_print_screen, listOf("PrintScreen")), ) + // 和 Windows 一样,去掉 Linux 上没有对应功能的 Win 系列和任务管理器 OsKind.LINUX -> listOf( + ShortcutPreset("combo_ctrl_alt_del", R.string.combo_ctrl_alt_del, listOf("ControlLeft", "AltLeft", "Delete")), ShortcutPreset("combo_alt_tab", R.string.combo_alt_tab, listOf("AltLeft", "Tab")), + ShortcutPreset("combo_alt_f4", R.string.combo_alt_f4, listOf("AltLeft", "F4")), ShortcutPreset("combo_copy", R.string.combo_copy, listOf("ControlLeft", "KeyC")), ShortcutPreset("combo_paste", R.string.combo_paste, listOf("ControlLeft", "KeyV")), ShortcutPreset("combo_undo", R.string.combo_undo, listOf("ControlLeft", "KeyZ")), + ShortcutPreset("combo_print_screen", R.string.combo_print_screen, listOf("PrintScreen")), ) else -> emptyList() } + + /** + * 保存过的列表 + 后来新加的内置快捷键:内置的删不掉,保存的列表里没有的就是新版本加的,放在最后; + * 新版本去掉了的内置快捷键也不再显示。没保存过([saved] 为 null)就是内置的 + */ + fun merge(os: OsKind, saved: List?): List { + val presets = forOs(os) + if (saved == null) return presets.map(ShortcutPreset::saved) + val ids = presets.mapTo(HashSet()) { it.id } + val kept = saved.filter { it.custom || it.id in ids } + val have = kept.mapTo(HashSet()) { it.id } + return kept + presets.filter { it.id !in have }.map(ShortcutPreset::saved) + } } -/** Profiles are keyed by remote OS so editing a Mac shortcut never changes the Windows list. */ +/** 快捷键列表:按被控端的系统分开存(改 Mac 的不影响 Windows 的),只存改过的系统。菜单和键盘的快捷键面板都看这一份 */ class ShortcutStore(context: Context) { private val file = File(context.filesDir, "shortcuts.json") + private val _flow = MutableStateFlow(load()) - @Synchronized - fun list(os: OsKind): List { - val saved = runCatching { JSONObject(JsonFile.read(file) ?: "{}") }.getOrDefault(JSONObject()).optJSONArray(os.wire) - return saved?.let { a -> (0 until a.length()).mapNotNull { i -> a.optJSONObject(i)?.let { SavedShortcut.parse(it) } } } - ?: ShortcutDefaults.forOs(os).map(ShortcutPreset::saved) + /** 系统([OsKind.wire])→ 保存的列表 */ + val flow: StateFlow>> = _flow.asStateFlow() + + private fun load(): Map> { + val o = JsonFile.read(file)?.let { runCatching { JSONObject(it) }.getOrNull() } ?: return emptyMap() + return o.keys().asSequence().associateWith { os -> + val a = o.optJSONArray(os) ?: JSONArray() + (0 until a.length()).mapNotNull { i -> a.optJSONObject(i)?.let(SavedShortcut::parse) } + } } + fun list(os: OsKind, saved: Map> = _flow.value): List = + ShortcutDefaults.merge(os, saved[os.wire]) + @Synchronized fun save(os: OsKind, items: List) { - val profiles = runCatching { JSONObject(JsonFile.read(file) ?: "{}") }.getOrDefault(JSONObject()) - profiles.put(os.wire, JSONArray(items.map(SavedShortcut::toJson))) - JsonFile.write(file, profiles.toString()) + val next = _flow.value + (os.wire to items) + _flow.value = next + val o = JSONObject() + next.forEach { (k, v) -> o.put(k, JSONArray(v.map(SavedShortcut::toJson))) } + JsonFile.write(file, o.toString()) } } diff --git a/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt b/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt index cd6b9c5a..cf368f6b 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt @@ -96,6 +96,7 @@ import app.airhand.android.data.GameStick import app.airhand.android.data.GameTemplate import app.airhand.android.data.KeyMode import app.airhand.android.data.PadStick +import app.airhand.android.data.SavedShortcut import app.airhand.android.ui.ConfirmDialog import app.airhand.android.ui.EditTextDialog import kotlin.math.ln @@ -725,7 +726,8 @@ private fun ColumnScope.LayoutPanel(ed: LayoutEditor) { /** * 选键:平时点一个键就选好了;打开"组合键"之后可以按顺序点最多 3 个(一起按下,例如 Ctrl+1),再点"确定"。 - * [onStick] 不为 null 时(添加)最上面还有摇杆(按哪几个键、手柄的哪个摇杆);最下面是画面上的手柄的按钮 + * [onStick] 不为 null 时(添加)最上面还有摇杆(按哪几个键、手柄的哪个摇杆);最下面是画面上的手柄的按钮。 + * 选快捷键时 [keyboardOnly]:只列键盘上的键、一直是组合键(最多 [maxKeys] 个);[macKeys] 控制 Mac 时 Win / Alt 写成 ⌘ / ⌥ */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable @@ -739,7 +741,7 @@ internal fun KeyPicker( maxKeys: Int = GameBind.MAX_BINDS, ) { val text = strings() - fun keyName(code: String) = if (macKeys && code in listOf("MetaLeft", "MetaRight")) "⌘" else GameKeys.label(code, text) + fun keyName(code: String) = keyLabel(code, macKeys, text) var combo by remember { mutableStateOf(keyboardOnly || initial.size > 1) } val chosen = remember { mutableStateListOf().apply { if (keyboardOnly || initial.size > 1) addAll(initial) } } ModalBottomSheet( @@ -794,7 +796,7 @@ internal fun KeyPicker( KeyCap(stringResource(R.string.game_pad_right_stick)) { onStick(GameBind.WASD, PadStick.RIGHT) } } } - GameKeys.groups.filter { !keyboardOnly || it.title != R.string.game_group_mouse }.forEach { g -> + GameKeys.groups.filter { !keyboardOnly || it.tokens.all(SavedShortcut::isKey) }.forEach { g -> GroupTitle(stringResource(g.title)) FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { g.tokens.forEach { t -> @@ -817,6 +819,13 @@ internal fun KeyPicker( } } +/** 键名;控制 Mac 时 Win 键写成 ⌘、Alt 写成 ⌥(和键盘上方的特殊键一样) */ +internal fun keyLabel(code: String, mac: Boolean, text: (Int) -> String): String = when { + mac && (code == "MetaLeft" || code == "MetaRight") -> "⌘" + mac && (code == "AltLeft" || code == "AltRight") -> "⌥" + else -> GameKeys.label(code, text) +} + @Composable private fun GroupTitle(text: String) { Text( diff --git a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt index 69c518a4..461b0123 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/PhoneSession.kt @@ -10,7 +10,6 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectDragGestures -import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.interaction.MutableInteractionSource @@ -43,7 +42,10 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.ArrowBack +import androidx.compose.material.icons.outlined.ArrowDownward +import androidx.compose.material.icons.outlined.ArrowUpward import androidx.compose.material.icons.outlined.Close +import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.automirrored.outlined.HelpOutline import androidx.compose.material.icons.outlined.HighQuality import androidx.compose.material.icons.outlined.Keyboard @@ -67,6 +69,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField @@ -78,6 +81,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState @@ -200,8 +204,9 @@ fun PhoneSession( var mode by remember(os) { mutableStateOf(initialMode(settings.touchMode, os)) } var menu by remember { mutableStateOf(false) } - var inputTab by remember { mutableIntStateOf(0) } - LaunchedEffect(keyboardOpen.value) { if (!keyboardOpen.value) inputTab = 0 } + // 键盘换成了快捷键面板(控制电脑时);关了键盘再打开是系统键盘 + var shortcutsOpen by remember { mutableStateOf(false) } + LaunchedEffect(keyboardOpen.value) { if (!keyboardOpen.value) shortcutsOpen = false } var page by remember { mutableStateOf(Page.MAIN) } var confirmExit by remember { mutableStateOf(false) } var dismissed by remember { mutableStateOf(setOf()) } @@ -242,36 +247,45 @@ fun PhoneSession( view.showCursor = gm == Gestures.Mode.TRACKPAD || gm == Gestures.Mode.TOUCH } - // 键盘:按钮 / 三指点击打开;用系统的返回收起时同步状态 + // 键盘:按钮 / 三指点击打开;用系统的返回收起时同步状态。 + // 控制电脑时特殊键那一排上有“快捷键”:把系统键盘换成快捷键面板,再点换回来 val imeVisible = WindowInsets.isImeVisible var imeWasVisible by remember { mutableStateOf(false) } - LaunchedEffect(keyboardOpen.value, inputTab) { - if (keyboardOpen.value && inputTab == 0) view.showKeyboard() else view.hideKeyboard() + val hasShortcuts = ShortcutDefaults.supports(os) + val shortcutPanel = hasShortcuts && keyboardOpen.value && shortcutsOpen + LaunchedEffect(keyboardOpen.value, shortcutPanel) { + if (keyboardOpen.value && !shortcutPanel) view.showKeyboard() else view.hideKeyboard() } LaunchedEffect(imeVisible) { - if (imeWasVisible && !imeVisible && inputTab == 0) keyboardOpen.value = false + // 换成快捷键面板时系统键盘是我们收起来的,不算关键盘 + if (imeWasVisible && !imeVisible && !shortcutPanel) keyboardOpen.value = false imeWasVisible = imeVisible } + // 特殊键那一排:控制电脑时键盘一打开就有(换成快捷键面板、接着实体键盘没弹出系统键盘时也在),控制手机时跟着系统键盘 + val inputBar = if (hasShortcuts) keyboardOpen.value else imeVisible BackHandler(enabled = !menu && editor == null) { confirmExit = true } + // 系统键盘没弹出来(快捷键面板、实体键盘)时返回键关掉键盘;弹出来时返回键是系统键盘自己收 + BackHandler(enabled = inputBar && !imeVisible && !menu && editor == null) { keyboardOpen.value = false } val imeBottom = WindowInsets.ime.asPaddingValues().calculateBottomPadding() - val shortcutPanel = keyboardOpen.value && inputTab == 1 && - (os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX) - BackHandler(enabled = shortcutPanel && !menu) { keyboardOpen.value = false; inputTab = 0 } + val keyRow = if (landscape) 36.dp else 44.dp + // 快捷键面板和刚才的系统键盘一样高,换的时候画面不跳;这个方向上还没弹出过系统键盘时用个差不多的高度 + var imeHeight by remember(landscape) { mutableStateOf(0.dp) } + LaunchedEffect(imeBottom) { if (imeVisible && imeBottom > imeHeight) imeHeight = imeBottom } + val panelHeight = if (imeHeight >= 120.dp) imeHeight else if (landscape) 180.dp else 260.dp val keysBar = when { - shortcutPanel -> 272.dp - imeVisible -> (if (landscape) 36.dp else 44.dp) + - (if (os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX) 40.dp else 0.dp) + shortcutPanel -> keyRow + panelHeight + inputBar -> keyRow else -> 0.dp } + // 特殊键下面是系统键盘;快捷键面板时它们在最下面 + val barBottom = if (shortcutPanel) 0.dp else imeBottom val navActions = listOf(SystemAction.BACK, SystemAction.HOME, SystemAction.RECENTS).filter { it in actions } - val navBar = if (navActions.isNotEmpty() && settings.navKeys && !keyboardOpen.value) 48.dp else 0.dp + val navBar = if (navActions.isNotEmpty() && settings.navKeys && !inputBar) 48.dp else 0.dp // 画面不跟着键盘缩小:键盘和特殊键挡着多高告诉 RemoteView,它把画面(放不下时是光标所在的地方)挪到键盘上面 val density = LocalDensity.current - val imeInsetPx = if (imeVisible || shortcutPanel) with(density) { - (if (shortcutPanel) keysBar else imeBottom + keysBar).toPx() - } else 0f + val imeInsetPx = if (inputBar) with(density) { (barBottom + keysBar).toPx() } else 0f LaunchedEffect(imeInsetPx, landscape) { view.setKeyboardInset(imeInsetPx) } Box(Modifier.fillMaxSize().background(Color.Black)) { @@ -286,7 +300,7 @@ fun PhoneSession( // 游戏按键:连上了、没盖住、没开键盘(键盘会挡住)、没在编辑时才显示;收起、换方案都先松开按着的键 val live = phase == RemoteSession.Phase.Live && video != null - val showGame = gameOn && live && !covered && !keyboardOpen.value && editor == null + val showGame = gameOn && live && !covered && !inputBar && editor == null LaunchedEffect(showGame, gameLayout) { view.setGame(if (showGame) gameLayout else null) } // 画面上的手柄:只是收起时放回原位、不拔掉(游戏不会以为手柄断开了);关掉游戏按键、换成没有手柄的方案时拔掉 val padLayout = gameOn && gameLayout?.usesPad == true @@ -308,7 +322,7 @@ fun PhoneSession( verticalArrangement = Arrangement.spacedBy(6.dp), ) { // 横屏开着键盘时不显示状态信息:本来就没剩多高了 - if (settings.showStats && !covered && !(imeVisible && landscape)) StatsHud(session) + if (settings.showStats && !covered && !(inputBar && landscape)) StatsHud(session) messages.forEach { (key, text) -> Box(Modifier.padding(horizontal = 44.dp)) { NoticePill(text) { dismissed = dismissed + key } @@ -330,17 +344,17 @@ fun PhoneSession( } } - if (imeVisible || shortcutPanel) { + if (inputBar) { KeysBar( kb, os, compact = landscape, - tab = inputTab, - onTab = { inputTab = it }, - onHide = { keyboardOpen.value = false; inputTab = 0 }, + shortcuts = shortcutPanel, + onShortcuts = if (hasShortcuts) ({ shortcutsOpen = !shortcutsOpen }) else null, + onHide = { keyboardOpen.value = false }, modifier = Modifier .align(Alignment.BottomCenter) - .padding(bottom = if (shortcutPanel) 0.dp else imeBottom) + .padding(bottom = barBottom) .height(keysBar), ) } else if (navBar > 0.dp) { @@ -355,7 +369,7 @@ fun PhoneSession( if (!covered && editor == null) { MenuHandle( - bottomInset = (if (shortcutPanel) 0.dp else imeBottom) + keysBar + navBar, + bottomInset = barBottom + keysBar + navBar, doubleTapKeyboard = settings.doubleTapKeyboard, onClick = { page = Page.MAIN @@ -848,34 +862,30 @@ private fun SwapCtrlCommand(session: RemoteSession) { HorizontalDivider(Modifier.padding(vertical = 8.dp, horizontal = 16.dp)) } +/** + * 快捷键(控制电脑时):菜单 → 键盘与输入里是一列,键盘的快捷键面板([panel])里是一格格的按钮,点了就发。 + * 两处都能添加、编辑(点名字改名字和按键、上下移、删自己加的);按被控端的系统分开存,两处看的是同一份([ShortcutStore]) + */ @OptIn(ExperimentalLayoutApi::class) @Composable private fun Shortcuts(os: OsKind, onSend: (List) -> Unit, panel: Boolean = false) { - if (os !in listOf(OsKind.MAC, OsKind.WINDOWS, OsKind.LINUX)) return + if (!ShortcutDefaults.supports(os)) return val store = AirhandApp.instance.shortcuts + val saved by store.flow.collectAsState() + val items = store.list(os, saved) val context = LocalContext.current - var items by remember(os) { mutableStateOf(store.list(os)) } + val labels = remember(os) { ShortcutDefaults.forOs(os).associate { it.id to it.label } } + fun defaultName(item: SavedShortcut): String? = labels[item.id]?.let { context.getString(it) } + fun name(item: SavedShortcut): String = item.title ?: defaultName(item) ?: item.id var editing by remember(os) { mutableStateOf(false) } var selected by remember(os) { mutableStateOf(null) } - var picking by remember(os) { mutableStateOf(false) } - var title by remember(os) { mutableStateOf("") } - var codes by remember(os) { mutableStateOf(emptyList()) } - val labels = remember(os) { ShortcutDefaults.forOs(os).associate { it.id to it.label } } - fun persist(next: List) { - items = next - store.save(os, next) - } - fun open(item: SavedShortcut) { - selected = item - title = item.title ?: labels[item.id]?.let { context.getString(it) }.orEmpty() - codes = item.codes - } + fun move(index: Int, by: Int) = store.save(os, items.toMutableList().apply { add(index + by, removeAt(index)) }) Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { - TextButton(onClick = { open(SavedShortcut.custom()) }) { Text(stringResource(R.string.shortcut_add)) } + TextButton(onClick = { selected = SavedShortcut.custom() }) { Text(stringResource(R.string.shortcut_add)) } Spacer(Modifier.weight(1f)) TextButton(onClick = { editing = !editing }) { - Text(stringResource(if (editing) R.string.shortcut_done else R.string.shortcut_reorder)) + Text(stringResource(if (editing) R.string.shortcut_done else R.string.shortcut_edit)) } } if (panel && !editing) { @@ -883,75 +893,110 @@ private fun Shortcuts(os: OsKind, onSend: (List) -> Unit, panel: Boolean modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), ) { - items.forEach { item -> - Key(item.title ?: labels[item.id]?.let { context.getString(it) } ?: item.id, compact = true, feedback = true) { - onSend(item.codes) - } - } + items.forEach { item -> Key(name(item), compact = true, feedback = true) { onSend(item.codes) } } } } else items.forEachIndexed { index, item -> Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) { Text( - item.title ?: labels[item.id]?.let { stringResource(it) } ?: item.id, + name(item), style = MaterialTheme.typography.bodyLarge, - modifier = Modifier.weight(1f).clickable(enabled = !editing) { onSend(item.codes) } + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier + .weight(1f) + .clickable { if (editing) selected = item else onSend(item.codes) } .padding(horizontal = 8.dp, vertical = 12.dp), ) if (editing) { - TextButton(onClick = { open(item) }) { Text(stringResource(R.string.shortcut_edit)) } - TextButton(onClick = { - val next = items.toMutableList() - next.add(index - 1, next.removeAt(index)) - persist(next) - }, enabled = index > 0) { Text("↑") } - TextButton(onClick = { - val next = items.toMutableList() - next.add(index + 1, next.removeAt(index)) - persist(next) - }, enabled = index < items.lastIndex) { Text("↓") } - if (item.id.startsWith("custom:")) { - IconButton(onClick = { persist(items.filterNot { it.id == item.id }) }) { - Icon(Icons.Outlined.Close, contentDescription = stringResource(R.string.delete)) + IconButton(onClick = { move(index, -1) }, enabled = index > 0) { + Icon(Icons.Outlined.ArrowUpward, stringResource(R.string.shortcut_move_up)) + } + IconButton(onClick = { move(index, 1) }, enabled = index < items.lastIndex) { + Icon(Icons.Outlined.ArrowDownward, stringResource(R.string.shortcut_move_down)) + } + if (item.custom) { + IconButton(onClick = { store.save(os, items.filterNot { it.id == item.id }) }) { + Icon(Icons.Outlined.Delete, stringResource(R.string.delete)) } + } else { + Spacer(Modifier.size(48.dp)) } } } } - if (selected != null && !picking) { - AlertDialog( - onDismissRequest = { selected = null }, - title = { Text(stringResource(R.string.shortcut_edit)) }, - text = { - Column { - OutlinedTextField(value = title, onValueChange = { title = it }, label = { Text(stringResource(R.string.shortcut_name)) }) - TextButton(onClick = { picking = true }) { - Text(if (codes.isEmpty()) stringResource(R.string.shortcut_pick) else codes.joinToString("+") { - if (os == OsKind.MAC && it in listOf("MetaLeft", "MetaRight")) "⌘" else GameKeys.label(it) { id -> context.getString(id) } - }) - } - } + selected?.let { item -> + ShortcutDialog( + os, + item, + isNew = items.none { it.id == item.id }, + defaultName = defaultName(item), + onDismiss = { selected = null }, + onSave = { changed -> + store.save(os, if (items.any { it.id == changed.id }) items.map { if (it.id == changed.id) changed else it } else items + changed) + selected = null }, - confirmButton = { - TextButton(onClick = { - val item = selected ?: return@TextButton - val name = title.trim() - val defaultName = labels[item.id]?.let { context.getString(it) } - val changed = item.copy(title = name.takeUnless { it == defaultName }, codes = codes) - persist(if (items.any { it.id == item.id }) items.map { if (it.id == item.id) changed else it } else items + changed) - selected = null - }, enabled = title.isNotBlank() && codes.isNotEmpty()) { Text(stringResource(R.string.save)) } + ) + } +} + +/** 添加 / 编辑一个快捷键:名字和按键(选键时名字还空着就先填上按键)。名字和内置的一样时不存,换了语言跟着变 */ +@Composable +private fun ShortcutDialog( + os: OsKind, + item: SavedShortcut, + isNew: Boolean, + defaultName: String?, + onDismiss: () -> Unit, + onSave: (SavedShortcut) -> Unit, +) { + val context = LocalContext.current + val text: (Int) -> String = { context.getString(it) } + fun keysName(codes: List) = codes.joinToString("+") { keyLabel(it, os == OsKind.MAC, text) } + var title by remember { mutableStateOf(item.title ?: defaultName.orEmpty()) } + var codes by remember { mutableStateOf(item.codes) } + var picking by remember { mutableStateOf(false) } + if (picking) { + KeyPicker( + initial = codes, + onStick = null, + onPick = { + codes = SavedShortcut.ordered(it) + if (title.isBlank()) title = keysName(codes) + picking = false }, - dismissButton = { TextButton(onClick = { selected = null }) { Text(stringResource(R.string.cancel)) } }, + onDismiss = { picking = false }, + keyboardOnly = true, + macKeys = os == OsKind.MAC, + maxKeys = SavedShortcut.MAX_KEYS, ) + return } - if (picking) KeyPicker( - initial = codes, - onStick = null, - onPick = { codes = it; picking = false }, - onDismiss = { picking = false }, - keyboardOnly = true, - macKeys = os == OsKind.MAC, - maxKeys = 4, + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(if (isNew) R.string.shortcut_add else R.string.shortcut_edit)) }, + text = { + Column { + OutlinedTextField( + value = title, + onValueChange = { title = it }, + label = { Text(stringResource(R.string.shortcut_name)) }, + singleLine = true, + ) + TextButton(onClick = { picking = true }) { + Text(if (codes.isEmpty()) stringResource(R.string.shortcut_pick) else keysName(codes)) + } + } + }, + confirmButton = { + TextButton( + onClick = { + val name = title.trim() + onSave(item.copy(title = name.takeUnless { it == defaultName }, codes = codes)) + }, + enabled = title.isNotBlank() && codes.isNotEmpty(), + ) { Text(stringResource(R.string.save)) } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } }, ) } @@ -1517,103 +1562,65 @@ private fun GestureTips(mode: Gestures.Mode, onDone: () -> Unit) { // ───────────────────────────── 键盘上方的特殊键 / 手机导航键 ───────────────────────────── -@OptIn(ExperimentalLayoutApi::class) +/** + * 键盘上方的特殊键。控制电脑时右边多一个“快捷键”([onShortcuts]):点了把系统键盘换成快捷键面板 + * ([shortcuts],在特殊键下面),这时它变成“键盘”,再点换回来 + */ @Composable private fun KeysBar( kb: KeyboardController, os: OsKind, compact: Boolean = false, - tab: Int, - onTab: (Int) -> Unit, + shortcuts: Boolean = false, + onShortcuts: (() -> Unit)?, onHide: () -> Unit, modifier: Modifier, ) { val meta = if (os == OsKind.MAC) "⌘" else if (os == OsKind.ANDROID) "◯" else "Win" - val hasShortcuts = os == OsKind.MAC || os == OsKind.WINDOWS || os == OsKind.LINUX Column(modifier.fillMaxWidth().background(Color(0xFF1B1F2B))) { - if (hasShortcuts) { - var drag = 0f + Row(Modifier.height(if (compact) 36.dp else 44.dp), verticalAlignment = Alignment.CenterVertically) { Row( - Modifier.fillMaxWidth().height(40.dp) - .pointerInput(tab) { - detectHorizontalDragGestures( - onDragStart = { drag = 0f }, - onDragEnd = { - if (drag > 40f) onTab(1) - if (drag < -40f) onTab(0) - }, - onHorizontalDrag = { change, amount -> - drag += amount - change.consume() - }, - ) - }, + Modifier + .weight(1f) + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { - listOf(R.string.menu_keyboard, R.string.menu_shortcuts).forEachIndexed { index, title -> - Box( - Modifier.weight(1f).height(40.dp).clickable { onTab(index) }, - contentAlignment = Alignment.Center, - ) { - Text( - stringResource(title), - color = if (tab == index) Color.White else Color.White.copy(alpha = 0.6f), - fontWeight = if (tab == index) FontWeight.Bold else FontWeight.Normal, - fontSize = 12.sp, - ) - } - } - IconButton(onClick = onHide, modifier = Modifier.size(40.dp)) { - Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) - } + Key("Esc", compact) { kb.press("Escape") } + Key("Tab", compact) { kb.press("Tab") } + ModKey("Ctrl", kb, KeyboardController.Mod.CTRL, compact) + ModKey(if (os == OsKind.MAC) "⌥" else "Alt", kb, KeyboardController.Mod.ALT, compact) + ModKey("⇧", kb, KeyboardController.Mod.SHIFT, compact) + ModKey(meta, kb, KeyboardController.Mod.META, compact) + Key("←", compact) { kb.press("ArrowLeft") } + Key("↑", compact) { kb.press("ArrowUp") } + Key("↓", compact) { kb.press("ArrowDown") } + Key("→", compact) { kb.press("ArrowRight") } + Key("Del", compact) { kb.press("Delete") } + Key("Home", compact) { kb.press("Home") } + Key("End", compact) { kb.press("End") } + Key("PgUp", compact) { kb.press("PageUp") } + Key("PgDn", compact) { kb.press("PageDown") } + for (i in 1..12) Key("F$i", compact) { kb.press("F$i") } } - } - if (tab == 1 && hasShortcuts) { - var drag = 0f - Column( - modifier = Modifier.fillMaxWidth().weight(1f) - .verticalScroll(rememberScrollState()) - .pointerInput(tab) { - detectHorizontalDragGestures( - onDragStart = { drag = 0f }, - onDragEnd = { if (drag < -60f) onTab(0) }, - onHorizontalDrag = { change, amount -> - drag += amount - change.consume() - }, - ) - } - .padding(top = 4.dp), - ) { - Shortcuts(os, { kb.chord(it) }, panel = true) + if (onShortcuts != null) { + Key(stringResource(if (shortcuts) R.string.menu_keyboard else R.string.menu_shortcuts), compact, onClick = onShortcuts) } - } else { - Row(verticalAlignment = Alignment.CenterVertically) { - Row( - Modifier.weight(1f).horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp), - verticalAlignment = Alignment.CenterVertically, + IconButton(onClick = onHide, modifier = Modifier.size(if (compact) 36.dp else 44.dp)) { + Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) + } + } + if (shortcuts) { + // 没套 Surface:面板里没写颜色的字和图标用白色(不然是黑色) + CompositionLocalProvider(LocalContentColor provides Color.White) { + Column( + Modifier + .fillMaxWidth() + .weight(1f) + .verticalScroll(rememberScrollState()) + .padding(bottom = 8.dp), ) { - Key("Esc", compact) { kb.press("Escape") } - Key("Tab", compact) { kb.press("Tab") } - ModKey("Ctrl", kb, KeyboardController.Mod.CTRL, compact) - ModKey(if (os == OsKind.MAC) "⌥" else "Alt", kb, KeyboardController.Mod.ALT, compact) - ModKey("⇧", kb, KeyboardController.Mod.SHIFT, compact) - ModKey(meta, kb, KeyboardController.Mod.META, compact) - Key("←", compact) { kb.press("ArrowLeft") } - Key("↑", compact) { kb.press("ArrowUp") } - Key("↓", compact) { kb.press("ArrowDown") } - Key("→", compact) { kb.press("ArrowRight") } - Key("Del", compact) { kb.press("Delete") } - Key("Home", compact) { kb.press("Home") } - Key("End", compact) { kb.press("End") } - Key("PgUp", compact) { kb.press("PageUp") } - Key("PgDn", compact) { kb.press("PageDown") } - for (i in 1..12) Key("F$i", compact) { kb.press("F$i") } - } - if (!hasShortcuts) { - IconButton(onClick = onHide, modifier = Modifier.size(if (compact) 36.dp else 44.dp)) { - Icon(Icons.Outlined.KeyboardHide, stringResource(R.string.hide_keyboard), tint = Color.White) - } + Shortcuts(os, kb::chord, panel = true) } } } diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml index 1be59ff7..fd90af2a 100644 --- a/android/app/src/main/res/values-zh/strings.xml +++ b/android/app/src/main/res/values-zh/strings.xml @@ -461,7 +461,8 @@ 编辑 名称 选择按键 - 调整顺序 + 上移 + 下移 完成 Ctrl + Alt + Del Alt + Tab 切换窗口 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index efc1097f..6639c4de 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -468,7 +468,8 @@ Edit Name Choose keys - Reorder + Move up + Move down Done Ctrl + Alt + Del Alt + Tab switch windows diff --git a/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt b/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt index 22567a9f..7c3c19fd 100644 --- a/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt +++ b/android/app/src/test/java/app/airhand/android/data/ShortcutsTest.kt @@ -15,9 +15,33 @@ class ShortcutsTest { } @Test fun savedShortcutRejectsNonKeyboardInput() { - val bad = JSONObject().put("id", "custom:bad").put("title", "Bad").put("codes", JSONArray(listOf("mouse:left"))) - assertNull(SavedShortcut.parse(bad)) - val good = JSONObject().put("id", "custom:copy").put("title", "Copy").put("codes", JSONArray(listOf("MetaLeft", "KeyC"))) - assertEquals(listOf("MetaLeft", "KeyC"), SavedShortcut.parse(good)?.codes) + fun parse(vararg codes: String) = + SavedShortcut.parse(JSONObject().put("id", "custom:x").put("title", "X").put("codes", JSONArray(codes.toList()))) + assertNull(parse("mouse:left")) + assertNull(parse("ControlLeft", "wheel:up")) + assertNull(parse("pad:a")) + assertNull(parse()) + assertNull(parse("ControlLeft", "AltLeft", "ShiftLeft", "MetaLeft", "KeyA")) + assertEquals(listOf("MetaLeft", "KeyC"), parse("MetaLeft", "KeyC")?.codes) + } + + @Test fun modifiersArePressedFirst() { + assertEquals(listOf("ControlLeft", "ShiftLeft", "KeyC"), SavedShortcut.ordered(listOf("KeyC", "ControlLeft", "ShiftLeft"))) + assertEquals(listOf("MetaLeft", "Tab"), SavedShortcut.ordered(listOf("MetaLeft", "Tab"))) + } + + @Test fun savedListKeepsOrderAndPicksUpNewPresets() { + val defaults = ShortcutDefaults.merge(OsKind.LINUX, null) + assertEquals(ShortcutDefaults.forOs(OsKind.LINUX).map { it.id }, defaults.map { it.id }) + + // 用户把复制挪到最前、加了一个自己的;保存的列表里少了一个内置的(新版本加的)、多了一个已经去掉的内置的 + val custom = SavedShortcut("custom:1", "Find", listOf("ControlLeft", "KeyF")) + val saved = listOf(defaults.first { it.id == "combo_copy" }, custom, SavedShortcut("combo_gone", null, listOf("KeyG"))) + + defaults.filter { it.id != "combo_copy" && it.id != "combo_undo" } + val merged = ShortcutDefaults.merge(OsKind.LINUX, saved) + assertEquals("combo_copy", merged[0].id) + assertEquals(custom, merged[1]) + assertEquals("combo_undo", merged.last().id) + assertEquals(defaults.size + 1, merged.size) } } From d112aea44610f7f363d49403546a67710dac5b53 Mon Sep 17 00:00:00 2001 From: sqlpxc Date: Thu, 3 Dec 2026 16:06:42 +0800 Subject: [PATCH 6/6] iOS: share one shortcut list, toggle the panel from the extra keys row; update docs --- .../app/airhand/android/ui/session/GameUi.kt | 7 +- docs/android.md | 4 +- docs/android.zh-CN.md | 4 +- docs/ios.md | 4 +- docs/ios.zh-CN.md | 4 +- ios/Airhand/Session/GameEditor.swift | 6 +- ios/Airhand/Session/SessionController.swift | 28 ++-- ios/Airhand/Session/SessionMenu.swift | 39 ++--- ios/Airhand/Session/SessionViews.swift | 139 +++++++----------- ios/Airhand/Session/Shortcuts.swift | 134 +++++++++++------ ios/Shared/L10n.swift | 10 +- ios/Tests/ShortcutTests.swift | 29 ++++ 12 files changed, 227 insertions(+), 181 deletions(-) diff --git a/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt b/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt index cf368f6b..0a87014e 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt @@ -821,8 +821,11 @@ internal fun KeyPicker( /** 键名;控制 Mac 时 Win 键写成 ⌘、Alt 写成 ⌥(和键盘上方的特殊键一样) */ internal fun keyLabel(code: String, mac: Boolean, text: (Int) -> String): String = when { - mac && (code == "MetaLeft" || code == "MetaRight") -> "⌘" - mac && (code == "AltLeft" || code == "AltRight") -> "⌥" + !mac -> GameKeys.label(code, text) + code == "MetaLeft" -> "⌘" + code == "MetaRight" -> "R-⌘" + code == "AltLeft" -> "⌥" + code == "AltRight" -> "R-⌥" else -> GameKeys.label(code, text) } diff --git a/docs/android.md b/docs/android.md index c7e71c05..04cfc5e2 100644 --- a/docs/android.md +++ b/docs/android.md @@ -51,8 +51,8 @@ After you pinch to zoom the local view, a moment after your fingers stop the app - In trackpad mode the pointer is drawn locally (with the remote shape), so it moves without lag; in touch mode a fading circle shows where you tapped - **Keyboard**: the picture doesn't shrink: when it fits above the keyboard it moves up there, otherwise (landscape, or a phone held upright on the other side) the part around the pointer moves above the keyboard and follows the pointer, and everything moves back once the keyboard is hidden; in landscape the extra keys row is shorter and the stats overlay is hidden for the time being. A row of extra keys sits on top of the keyboard: Esc, Tab, Ctrl, Alt, Shift, Win (⌘ for Macs), arrows, Home / End, PgUp / PgDn, Del, F1–F12. Modifiers are sticky: tap once for the next key only, again to lock, again to release (tap Ctrl, then type c = Ctrl+C). While an IME composes (pinyin etc.) the text shows above the extra keys and is only sent once chosen - When controlling a phone, **Back / Home / Recents** keys sit below the picture (can be turned off in Settings), and Keyboard & input in the menu holds system actions: notifications, quick settings, screenshot, lock screen, power menu, volume (whichever the phone supports). For computers it lists shortcuts for the remote OS (Windows / macOS / Linux) -- When controlling a computer, you can add or edit keyboard combinations and move them up or down in Reorder mode. The list is saved locally on this Android device, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C -- With the keyboard open for a remote computer, tap the half-width Keyboard / Shortcuts tabs above it or swipe right on the tabs to show saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Add, edit, move, and remove custom shortcuts directly in the panel +- When controlling a computer, the shortcuts can be changed: add your own key combinations; after tapping Edit, tap a name to change it and its keys, move shortcuts up or down, and delete the ones you added. The list is saved on this device separately for each remote OS (Mac uses ⌘C for Copy, Windows and Linux use Ctrl+C); built-in shortcuts added in later versions show up at the end +- With the keyboard open for a remote computer, **Shortcuts** at the right end of the extra keys row swaps the system keyboard for the same list as buttons (with the same Add and Edit), at the keyboard's height; it turns into **Keyboard**, which switches back. The extra keys stay above both - A connected mouse and keyboard map directly to the remote mouse and keyboard. Over the picture the mouse shows just the remote cursor, without the system pointer on top; in Settings its wheel can be reversed, set to a speed (5%–200%) and to **Adaptive** (the default: a slow single notch moves half as far, spinning quickly speeds up to twice as far) or **Linear** (the same distance for every notch), and **Smooth mouse scrolling** splits each notch into a few small steps about 16 ms apart (the same total; closer to a trackpad on a Mac). Some tablets (firmware on some Huawei MatePads) report the wheel as a one-finger swipe starting at the pointer; it is still sent as the wheel (one notch per 64 dp) rather than moving the remote pointer or clicking. Ctrl / ⌘ shortcuts on the keyboard go to the remote computer even while an input method is active, and keys still held are let go when the menu opens or the app goes to the background. When controlling a Mac, **Swap Ctrl and ⌘ Command** under Keyboard & input in the menu makes the keyboard's Ctrl work as ⌘ and the Win key as Control (copy with Ctrl+C on a Windows keyboard); the extra keys row and the shortcuts in the menu don't change. It's off by default and remembered per computer, as in the desktop console - **Games**: when the remote computer hides its cursor (turning the camera in a game), trackpad slides and touch drags send how far you moved instead of a position, so the camera turns smoothly and doesn't stop at the edge of the picture; a connected mouse is captured (Android 8+). **Mouse lock** under Mouse & touch in the menu does the same all the time, e.g. for Macs, which can't report a hidden cursor. For games played with the keyboard, see game keys below - **Privacy mode**: under Video & display in the menu when the remote is Windows or a Mac (with a version that supports it). It blanks all of the remote monitors and disables its keyboard and mouse, so only you can see and control it; the switch shows the current state (turning on, on, why it isn't available), and a failure also shows at the top of the picture. It turns off by itself after you disconnect and stays on while reconnecting. See [Usage → Privacy mode](usage.md#privacy-mode) diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index f558e603..b11cce16 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -51,8 +51,8 @@ - 触控板模式下指针由本机画出来(形状来自对方),移动没有延迟;触屏模式点按处有一个淡出的圆作为反馈 - **键盘**:打开后画面不缩小:键盘上面放得下就挪到键盘上面,放不下(横屏、对方是竖着的手机)就把指针所在的地方挪到键盘上面,移动指针时跟着走,收起键盘后回到原来的位置;横屏时特殊键那一排矮一些,状态信息先不显示。键盘上面多一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12。修饰键是“粘滞”的:点一下只对下一个键有效,再点一下锁定,再点取消(例如点 Ctrl 再在键盘上打 c = Ctrl+C)。拼音等输入法组字时文字显示在特殊键上方,选好字才发过去 - 控制手机时画面下方有**返回 / 主页 / 最近任务**三个键(设置里可以关掉),菜单 → 键盘与输入里是通知栏、快捷设置、截屏、锁屏、电源菜单、音量等系统操作(对方手机能执行哪些就显示哪些);控制电脑时那里是按对方系统列出的快捷键(Windows / macOS / Linux) -- 控制电脑时,可以添加、编辑组合键,在“调整顺序”模式里用上下箭头排序。列表保存在这台 Android 设备上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C -- 控制电脑并打开键盘时,可以点键盘上方各占半行的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。快捷键面板内可直接添加、编辑、上下调整顺序和删除自定义项 +- 控制电脑时快捷键可以改:添加自己的组合键;点“编辑”后点名字改名字和按键、上下移、删掉自己加的。列表存在这台设备上,按被控端的系统分开(Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C),以后版本新加的内置快捷键会出现在最后 +- 控制电脑并打开键盘时,特殊键那一排最右边的**快捷键**把系统键盘换成一格格的快捷键(同一份列表,也能添加、编辑),和系统键盘一样高;这时它变成**键盘**,点了换回来。特殊键一直在上面 - 外接鼠标、键盘直接对应远端的鼠标、键盘。鼠标在画面上时只显示对方的光标,不会再叠一个系统指针。滚轮在设置里可以改速度(5%–200%)、方向和换算方式:**自适应加速**(默认:慢慢滚一格只走半格,连着快滚加速到两倍)或**固定线性**(每格一样远);还可以打开**平滑滚动**(每一格拆成几小步、约 16 ms 一步发过去,加起来不变,控制 Mac 时更像触控板)。有的平板(华为 MatePad 的一些固件)把外接鼠标的滚轮报成从指针那里开始的单指滑动,也照样当滚轮发(按 64 dp 一格算),不会变成移动对方的指针或者点击。键盘上 Ctrl / ⌘ 的组合键不会被本机的输入法拿走;打开菜单、切到后台时按着的键都会松开。控制 Mac 时,菜单 → 键盘与输入里的**互换 Ctrl 和 ⌘ Command** 让键盘上的 Ctrl 当 ⌘ 用、Win 键当 Ctrl 用(用 Windows 键盘按 Ctrl+C 复制);键盘上方的特殊键和菜单里的快捷键不变。默认关闭,每台电脑分别记住,和桌面控制台一样 - **游戏**:对方电脑隐藏了光标时(游戏里转视角),触控板的滑动、触屏的拖动发的是“移动了多少”而不是位置,视角转得顺,拖到画面边上也不会停;外接鼠标会被抓住(Android 8+)。菜单 → 鼠标与触控里的**锁定鼠标**让它一直这样,例如对方是 Mac(检测不到光标隐藏)时。要按键盘的游戏用下面的游戏按键 - **防窥模式**:对方是 Windows、Mac(而且是支持它的版本)时菜单 → 视频与画面里有它。打开后对方所有的显示器黑屏、键盘鼠标不起作用,只有你看得到、操作得了;开关下面写着现在怎么样(正在打开、开着、开不了的原因),没能打开时画面上方也会提示。断开连接后自动恢复,断线重连时接着保持。详见[使用说明 → 防窥模式](usage.zh-CN.md#防窥模式) diff --git a/docs/ios.md b/docs/ios.md index 720f7bf1..3bc6c3f9 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -42,8 +42,8 @@ After zooming in, Airhand asks the remote for a sharper picture once your finger - **Hardware keyboard**: physical keys are sent as key down / up (hold W in a game). Shortcuts the system keeps (⌘Tab, ⌘Space, Globe) can't be passed — use the shortcuts page - **Mouse / trackpad (iPad)**: move, left / right / middle / side buttons and the wheel map to the remote; the remote's cursor shape is drawn locally. When the remote hides its cursor (games) or “Lock mouse” is on, the pointer is **locked** and raw movement is sent; hold Esc to release (iPadOS only allows pointer lock in full screen) - Phones get **Back / Home / Recents** below the picture (can be turned off) and their system actions on the shortcuts page; computers get shortcuts for their OS -- For a remote computer, the shortcuts page lets you add or edit keyboard combinations and reorder them with Edit. The list is saved locally on this iPhone or iPad, separately for each remote OS; Mac uses ⌘C for Copy, while Windows and Linux use Ctrl+C -- With the keyboard open for a remote computer, tap the half-width Keyboard / Shortcuts tabs above it or swipe right on the tabs to show saved shortcuts in place of the system keyboard. Swipe left on the shortcuts panel to return to the keyboard. Add, edit, move, and remove custom shortcuts directly in the panel +- For a remote computer, the shortcuts page lets you add your own key combinations, change them with the pencil, reorder them after tapping Edit, and delete the ones you added. The list is saved on this iPhone or iPad separately for each remote OS (Mac uses ⌘C for Copy, Windows and Linux use Ctrl+C); built-in shortcuts added in later versions show up at the end +- With the keyboard open for a remote computer, **Shortcuts** at the right end of the extra keys row swaps the system keyboard for the same list as buttons (with Add and Edit), at the keyboard's height; it turns into **Keyboard**, which switches back. The extra keys stay above both - **Clipboard**: text copied on the remote lands in this device's clipboard; the menu can send this device's text to the remote clipboard or type it (iOS asks once to allow pasting) - **Files**: files copied on the remote show a prompt; “Save to Files” transfers them into Files › On My iPhone › Airhand. “Send files” puts files from this device on the remote clipboard to paste there (only a list is sent until pasted) - **Sound** with adaptive jitter buffer; **A/V sync** for videos; **microphone** forwarding to Windows, macOS 14.2+ and Linux hosts, with system echo cancellation diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index d7dda351..6421d82c 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -43,8 +43,8 @@ - **外接键盘**:按物理键发(游戏里按住 W 就是按住),系统拦下的组合键(⌘Tab、⌘空格、地球键)传不过去 - **外接鼠标 / 触控板(iPad)**:移动、左右中键、侧键、滚轮直接对应远端;本机不显示系统指针,画的是对方的光标形状。对方隐藏了光标(游戏里转视角)或者打开了“锁定鼠标”时,**锁定指针**、发原始移动量;长按 Esc 放开(iPadOS 只在 App 全屏时允许锁定指针) - 控制手机时画面下方有**返回 / 主页 / 最近任务**(设置里可以关掉),快捷键页里是对方手机支持的系统操作;控制电脑时快捷键按对方系统列出(Windows / macOS / Linux) -- 控制电脑时,快捷键页可以添加、编辑组合键,点“编辑”后拖动调整顺序。列表保存在这台 iPhone 或 iPad 上,按被控端系统分别保存;Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C -- 控制电脑并打开键盘时,可以点键盘上方各占半行的“键盘 / 快捷键”标签,或在标签上右滑,把系统键盘换成已保存的快捷键;在快捷键面板左滑回到键盘。快捷键面板内可直接添加、编辑、上下调整顺序和删除自定义项 +- 控制电脑时,快捷键页可以添加自己的组合键、点铅笔修改、点“编辑”后拖动排序、删掉自己加的。列表存在这台 iPhone 或 iPad 上,按被控端的系统分开(Mac 的复制是 ⌘C,Windows 和 Linux 是 Ctrl+C),以后版本新加的内置快捷键会出现在最后 +- 控制电脑并打开键盘时,特殊键那一排最右边的**快捷键**把系统键盘换成一格格的快捷键(同一份列表,也能添加、编辑),和系统键盘一样高;这时它变成**键盘**,点了换回来。特殊键一直在上面 - **剪贴板**:对方复制的文字自动放进本机剪贴板;菜单 → 剪贴板可以把本机复制的文字发到对方的剪贴板,或者直接打进对方的输入框(读本机剪贴板时 iOS 会问一次“允许粘贴”) - **文件**:对方复制的文件会提示“对方复制了 N 项”,点“保存到‘文件’”才传,存在“文件 › 我的 iPhone › Airhand”;菜单 → 发送文件选好本机的文件,放进对方的剪贴板,到对方那里粘贴(复制时只发清单,粘贴时才传) - **声音**:对方的声音同步过来(Opus + 自适应抖动缓冲,和桌面版同一套做法);**音画同步**看视频时打开。**麦克风**:对方能接收时(Windows、macOS 14.2+、Linux 被控端),菜单里打开就把本机的麦克风转发过去,开着系统的回声消除 diff --git a/ios/Airhand/Session/GameEditor.swift b/ios/Airhand/Session/GameEditor.swift index b8f873d6..7135ea80 100644 --- a/ios/Airhand/Session/GameEditor.swift +++ b/ios/Airhand/Session/GameEditor.swift @@ -390,7 +390,8 @@ struct LayoutSettings: View { } } -/// 选按键:鼠标、常用、字母、数字、功能键、方向和编辑、符号;按顺序点最多 3 个就是组合键 +/// 选按键:鼠标、常用、字母、数字、功能键、方向和编辑、符号;按顺序点最多 3 个就是组合键。 +/// 选快捷键时(`keyboardOnly`)只列键盘上的键,最多 `maxKeys` 个 struct KeyPicker: View { let initial: [String] let os: OsKind @@ -426,7 +427,8 @@ struct KeyPicker: View { ScrollView { VStack(alignment: .leading, spacing: 18) { Text(L.t(keyboardOnly ? "shortcut_pick_hint" : "game_pick_combo")).font(.footnote).foregroundStyle(Theme.sub) - ForEach(groups.filter { !keyboardOnly || $0.0 != "game_group_mouse" }, id: \.0) { title, list in + // 选快捷键时只列键盘上的键(没有鼠标、手柄) + ForEach(groups.filter { !keyboardOnly || $0.1.allSatisfy(SavedShortcut.isKey) }, id: \.0) { title, list in VStack(alignment: .leading, spacing: 8) { SectionTitle(text: L.t(title)) LazyVGrid(columns: [GridItem(.adaptive(minimum: 58), spacing: 8)], spacing: 8) { diff --git a/ios/Airhand/Session/SessionController.swift b/ios/Airhand/Session/SessionController.swift index e7508efc..a8a7d7ec 100644 --- a/ios/Airhand/Session/SessionController.swift +++ b/ios/Airhand/Session/SessionController.swift @@ -159,7 +159,6 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private let keyField = KeyField() private let keyboard = KeyboardState() private let inputPage = InputPageState() - private lazy var shortcutModel = ShortcutPanelModel(os: session.os) private let game = GameLayerView() private let menuButton = FloatingMenuButton() private var overlayHost: UIHostingController! @@ -172,6 +171,8 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private var zoom: CGFloat = 1 private var offset: CGPoint = .zero private var keyboardHeight: CGFloat = 0 + /// 刚才系统键盘(连上面那排特殊键)有多高:快捷键面板和它一样高,换的时候画面不跳 + private var systemKeyboardHeight: CGFloat = 0 private var touchIds: [ObjectIdentifier: Int] = [:] private var nextTouchId = 0 private var activeTouches: [ObjectIdentifier: UITouch] = [:] @@ -257,7 +258,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract keyField.onComposing = { [weak self] s in self?.keyboard.composing = s } keyField.onPresses = { [weak self] p, down in self?.hardwareKeys(p, down) ?? false } shortcutsInput = UIHostingController(rootView: ShortcutInputPanel( - state: keyboard, os: session.os, page: inputPage, model: shortcutModel, + state: keyboard, os: session.os, page: inputPage, switchPage: { [weak self] page in self?.setInputPage(page) }, hide: { [weak self] in self?.setKeyboard(false) }, edit: { [weak self] item in self?.editShortcut(item) } @@ -281,8 +282,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract )) accessory.view.backgroundColor = .clear accessory.sizingOptions = [.intrinsicContentSize] - accessory.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, - height: session.os.isPhone ? 54 : 90) + accessory.view.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 54) accessory.view.autoresizingMask = [.flexibleWidth] keyField.inputAccessoryView = accessory.view view.addSubview(keyField) @@ -874,27 +874,32 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract } } + /// 键盘那里换成快捷键面板(1)或者系统键盘(0)。面板和刚才的系统键盘一样高,横屏时也不会盖住大半个画面 private func setInputPage(_ page: Int) { guard inputPage.selected != page else { return } inputPage.selected = page - if page == 1 { shortcutModel.reload() } - accessory.view.frame.size.height = session.os.isPhone ? 54 : 90 + if page == 1 { + let h = systemKeyboardHeight > 0 ? systemKeyboardHeight - view.safeAreaInsets.bottom : 300 + shortcutsInputView.frame.size.height = min(max(h, 220), view.bounds.height * 0.6) + } + accessory.view.frame.size.height = 54 accessory.view.invalidateIntrinsicContentSize() keyField.inputAccessoryView = page == 1 ? nil : accessory.view keyField.inputView = page == 1 ? shortcutsInputView : nil if keyField.isFirstResponder { keyField.reloadInputViews() } } + /// 在快捷键面板上添加 / 编辑:编辑页要打字,先收起键盘;关掉之后直接回到快捷键面板(先换面板再打开,不会闪一下系统键盘) private func editShortcut(_ item: SavedShortcut) { + let os = session.os setKeyboard(false) let host = UIHostingController(rootView: ShortcutEditor( - shortcut: item, os: session.os, - save: { [weak self] changed in self?.shortcutModel.upsert(changed) }, + shortcut: item, os: os, + save: { changed in ShortcutStore.shared.upsert(changed, for: os) }, close: { [weak self] in - guard let self else { return } - self.dismiss(animated: true) { [weak self] in - self?.setKeyboard(true) + self?.dismiss(animated: true) { [weak self] in self?.setInputPage(1) + self?.setKeyboard(true) } } )) @@ -909,6 +914,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract let local = view.convert(f, from: nil) h = max(0, view.bounds.maxY - local.minY) } + if inputPage.selected == 0, h > 0 { systemKeyboardHeight = h } if h == keyboardHeight { return } keyboardHeight = h // 打字的时候游戏按键收起来(画面缩到键盘上面了,按钮挤在一起也按不准) diff --git a/ios/Airhand/Session/SessionMenu.swift b/ios/Airhand/Session/SessionMenu.swift index a838c32d..a553bfed 100644 --- a/ios/Airhand/Session/SessionMenu.swift +++ b/ios/Airhand/Session/SessionMenu.swift @@ -187,21 +187,18 @@ struct SessionMenu: View { // ───────────────────────────── 快捷键 ───────────────────────────── +/// 快捷键页:控制手机时是对方支持的系统操作;控制电脑时是按对方系统的快捷键,可以添加、改(铅笔)、 +/// 点“编辑”后拖动排序、删自己加的。和键盘的快捷键面板是同一份列表(`ShortcutStore`) struct ShortcutsPage: View { let session: RemoteSession @Environment(\.dismiss) private var dismiss - @State private var shortcuts: [SavedShortcut] @State private var editor: SavedShortcut? - private var editable: Bool { !session.os.isPhone && session.os != .unknown } - - init(session: RemoteSession) { - self.session = session - _shortcuts = State(initialValue: ShortcutProfiles.load(for: session.os)) - } - - private func persist() { ShortcutProfiles.save(shortcuts, for: session.os) } var body: some View { + let os = session.os + let store = ShortcutStore.shared + let shortcuts = store.list(for: os) + let editable = ShortcutProfiles.supports(os) List { if let actions = session.hello?.actions, !actions.isEmpty { Section { @@ -226,15 +223,17 @@ struct ShortcutsPage: View { .buttonStyle(.borderless) .accessibilityLabel(L.t("shortcut_edit")) } - .deleteDisabled(!item.id.hasPrefix("custom:")) + .deleteDisabled(!item.isCustom) } .onMove { source, destination in - shortcuts.move(fromOffsets: source, toOffset: destination) - persist() + var items = shortcuts + items.move(fromOffsets: source, toOffset: destination) + store.save(items, for: os) } .onDelete { offsets in - shortcuts.remove(atOffsets: offsets) - persist() + var items = shortcuts + items.remove(atOffsets: IndexSet(offsets.filter { shortcuts[$0].isCustom })) + store.save(items, for: os) } } } @@ -248,7 +247,7 @@ struct ShortcutsPage: View { ToolbarItemGroup(placement: .topBarTrailing) { if editable { EditButton() - Button { editor = SavedShortcut(id: "custom:\(UUID().uuidString)", title: "", codes: []) } label: { + Button { editor = SavedShortcut.custom() } label: { Image(systemName: "plus") } .accessibilityLabel(L.t("shortcut_add")) @@ -256,16 +255,8 @@ struct ShortcutsPage: View { } } .sheet(item: $editor) { item in - ShortcutEditor(shortcut: item, os: session.os) { changed in - if let index = shortcuts.firstIndex(where: { $0.id == changed.id }) { - shortcuts[index] = changed - } else { - shortcuts.append(changed) - } - persist() - } + ShortcutEditor(shortcut: item, os: os) { changed in store.upsert(changed, for: os) } } - .onChange(of: session.os) { _, os in shortcuts = ShortcutProfiles.load(for: os) } } } diff --git a/ios/Airhand/Session/SessionViews.swift b/ios/Airhand/Session/SessionViews.swift index 5a0e13de..51405819 100644 --- a/ios/Airhand/Session/SessionViews.swift +++ b/ios/Airhand/Session/SessionViews.swift @@ -141,9 +141,11 @@ struct NavKeysBar: View { } } -/// 软键盘上面的一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12 +/// 键盘那里现在是系统键盘(0)还是快捷键面板(1) @Observable final class InputPageState { var selected = 0 } +/// 软键盘上面的一排特殊键:Esc、Tab、Ctrl、Alt、Shift、Win(Mac 上是 ⌘)、方向键、Home / End、PgUp / PgDn、Del、F1–F12。 +/// 控制电脑时右边多一个“快捷键”:点了把系统键盘换成快捷键面板(`ShortcutInputPanel`),这时它变成“键盘”,再点换回来 struct KeyBar: View { let state: KeyboardState let os: OsKind @@ -151,8 +153,6 @@ struct KeyBar: View { let switchPage: (Int) -> Void let hide: () -> Void - private var hasShortcuts: Bool { os == .mac || os == .windows || os == .linux } - private let keys: [String] = ["Escape", "Tab", "MOD:ControlLeft", "MOD:AltLeft", "MOD:ShiftLeft", "MOD:MetaLeft", "ArrowLeft", "ArrowUp", "ArrowDown", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Delete"] + (1...12).map { "F\($0)" } @@ -165,77 +165,46 @@ struct KeyBar: View { .background(Theme.c2.opacity(0.5), in: Capsule()) .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 8).padding(.bottom, 4) } - if hasShortcuts { - HStack(spacing: 0) { - tab(L.t("menu_keyboard"), index: 0).frame(maxWidth: .infinity) - tab(L.t("menu_shortcuts"), index: 1).frame(maxWidth: .infinity) - hideButton.frame(width: 46) - } - .frame(height: 40) - .contentShape(Rectangle()) - .simultaneousGesture(DragGesture(minimumDistance: 25).onEnded { value in - if value.translation.width > 40 { switchPage(1) } - if value.translation.width < -40 { switchPage(0) } - }) - .background(.ultraThinMaterial) - } - if page.selected == 0 || !hasShortcuts { - HStack(spacing: 0) { - ScrollView(.horizontal, showsIndicators: false) { - HStack(spacing: 6) { - ForEach(keys, id: \.self) { k in - if k.hasPrefix("MOD:") { - let m = String(k.dropFirst(4)) - let st = state.state(m) - keyButton(KeyMap.label(m, os: os), highlight: st) { - UIImpactFeedbackGenerator(style: .light).impactOccurred() - state.toggle(m) - } - } else { - keyButton(KeyMap.label(k, os: os), highlight: .off) { - UIImpactFeedbackGenerator(style: .light).impactOccurred(intensity: 0.6) - state.press(k) - } + HStack(spacing: 0) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(keys, id: \.self) { k in + if k.hasPrefix("MOD:") { + let m = String(k.dropFirst(4)) + let st = state.state(m) + keyButton(KeyMap.label(m, os: os), highlight: st) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + state.toggle(m) + } + } else { + keyButton(KeyMap.label(k, os: os), highlight: .off) { + UIImpactFeedbackGenerator(style: .light).impactOccurred(intensity: 0.6) + state.press(k) } } } - .padding(.horizontal, 8) } - if !hasShortcuts { hideButton.frame(width: 46) } + .padding(.horizontal, 8) + } + if ShortcutProfiles.supports(os) { + keyButton(L.t(page.selected == 1 ? "menu_keyboard" : "menu_shortcuts"), highlight: .off) { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + switchPage(page.selected == 1 ? 0 : 1) + } + .padding(.leading, 6) } - .frame(height: 50) - .background(.ultraThinMaterial) + Button(action: hide) { + Image(systemName: "keyboard.chevron.compact.down").font(.system(size: 17, weight: .semibold)) + .foregroundStyle(.white).frame(width: 46, height: 40) + } + .accessibilityLabel(L.t("hide_keyboard")) } + .frame(height: 50) + .background(.ultraThinMaterial) } .preferredColorScheme(.dark) } - private func tab(_ label: String, index: Int) -> some View { - Button { switchPage(index) } label: { - Text(label) - .font(.caption.weight(page.selected == index ? .bold : .medium)) - .foregroundStyle(page.selected == index ? .white : .white.opacity(0.6)) - .frame(maxWidth: .infinity, minHeight: 40) - .contentShape(Rectangle()) - .overlay(alignment: .bottom) { - if page.selected == index { Capsule().fill(Theme.c2).frame(height: 2) } - } - } - .buttonStyle(.plain) - } - - private var hideButton: some View { - Button(action: hide) { - Image(systemName: "keyboard.chevron.compact.down") - .font(.system(size: 17, weight: .semibold)) - .foregroundStyle(.white) - .frame(maxWidth: .infinity, minHeight: 40) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityLabel(L.t("hide_keyboard")) - } - private func keyButton(_ label: String, highlight: KeyboardState.Sticky, _ f: @escaping () -> Void) -> some View { Button(action: f) { Text(label).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white) @@ -252,29 +221,33 @@ struct KeyBar: View { } } -/// Replaces the system keyboard while the shortcut tab is selected. +/// 快捷键面板:选了“快捷键”时代替系统键盘(`SessionController` 把它设成输入框的 inputView)。 +/// 上面还是那排特殊键,下面一格格的快捷键,点了就发;“编辑”时可以改、上下移、删自己加的。 +/// 和菜单的快捷键页看同一份列表(`ShortcutStore`) struct ShortcutInputPanel: View { let state: KeyboardState let os: OsKind let page: InputPageState - let model: ShortcutPanelModel let switchPage: (Int) -> Void let hide: () -> Void let edit: (SavedShortcut) -> Void + @State private var editing = false @State private var flashedShortcut: String? @State private var flashGeneration = 0 var body: some View { + let store = ShortcutStore.shared + let items = store.list(for: os) VStack(spacing: 0) { KeyBar(state: state, os: os, page: page, switchPage: switchPage, hide: hide) HStack { - Button { edit(SavedShortcut(id: "custom:\(UUID().uuidString)", title: "", codes: [])) } label: { + Button { edit(SavedShortcut.custom()) } label: { Label(L.t("shortcut_add"), systemImage: "plus") } Spacer() - Button(model.editing ? L.t("done") : L.t("shortcut_reorder")) { - model.editing.toggle() + Button(editing ? L.t("done") : L.t("shortcut_manage")) { + editing.toggle() } } .font(.subheadline.weight(.medium)) @@ -284,22 +257,24 @@ struct ShortcutInputPanel: View { ScrollView { Group { - if model.editing { + if editing { LazyVStack(spacing: 6) { - ForEach(Array(model.items.indices), id: \.self) { index in - let item = model.items[index] + ForEach(Array(items.indices), id: \.self) { index in + let item = items[index] HStack(spacing: 4) { Text(item.label()).font(.subheadline).lineLimit(1) .frame(maxWidth: .infinity, alignment: .leading) action("pencil", L.t("shortcut_edit")) { edit(item) } - action("arrow.up", L.t("shortcut_reorder"), disabled: index == 0) { - model.move(index, by: -1) + action("arrow.up", L.t("shortcut_move_up"), disabled: index == 0) { + store.move(index, by: -1, for: os) } - action("arrow.down", L.t("shortcut_reorder"), disabled: index == model.items.count - 1) { - model.move(index, by: 1) + action("arrow.down", L.t("shortcut_move_down"), disabled: index == items.count - 1) { + store.move(index, by: 1, for: os) } - if item.id.hasPrefix("custom:") { - action("trash", L.t("delete")) { model.delete(item) } + if item.isCustom { + action("trash", L.t("delete")) { store.delete(item, for: os) } + } else { + Color.clear.frame(width: 36, height: 40) } } .foregroundStyle(.white) @@ -311,7 +286,7 @@ struct ShortcutInputPanel: View { } } else { LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) { - ForEach(model.items) { item in + ForEach(items) { item in Button { UIImpactFeedbackGenerator(style: .medium).impactOccurred() state.chord(item.codes) @@ -339,12 +314,6 @@ struct ShortcutInputPanel: View { .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .background(Theme.bg) .ignoresSafeArea(.container, edges: .top) - .onAppear { model.reload() } - .simultaneousGesture(DragGesture(minimumDistance: 35).onEnded { value in - if value.translation.width < -60 && abs(value.translation.width) > abs(value.translation.height) { - switchPage(0) - } - }) .preferredColorScheme(.dark) } diff --git a/ios/Airhand/Session/Shortcuts.swift b/ios/Airhand/Session/Shortcuts.swift index 1f839e25..3602996e 100644 --- a/ios/Airhand/Session/Shortcuts.swift +++ b/ios/Airhand/Session/Shortcuts.swift @@ -1,17 +1,43 @@ import SwiftUI import Observation -/// A shortcut is local to the controller. The wire protocol still receives ordinary key edges. +/// 快捷键(控制电脑时):只存在控制端,按的是 W3C `KeyboardEvent.code`,用现有的按键协议发,被控端不用改。 +/// 内置的 `id` 是它的文字键(`combo_copy`),`title` 为空时显示内置的名字(跟着语言变);自己加的 `id` 以 `custom:` 开头 struct SavedShortcut: Codable, Identifiable, Equatable { var id: String var title: String? var codes: [String] + /// 一个快捷键最多几个键 + static let maxKeys = 4 + private static let modifiers: Set = ["ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight", + "AltLeft", "AltRight", "MetaLeft", "MetaRight"] + + /// 自己加的(只有这些能删) + var isCustom: Bool { id.hasPrefix("custom:") } + + /// 存得下来的:1–4 个键盘上的键 + var isValid: Bool { !codes.isEmpty && codes.count <= Self.maxKeys && codes.allSatisfy(Self.isKey) } + func label() -> String { title ?? L.t(id) } + + static func custom() -> SavedShortcut { SavedShortcut(id: "custom:\(UUID().uuidString)", title: nil, codes: []) } + + /// 键盘上的键(W3C code 只有字母数字):鼠标键、滚轮、手柄的按钮(`mouse:left`、`pad:a`)不行 + static func isKey(_ code: String) -> Bool { + (1...32).contains(code.count) && code.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber) } + } + + /// 修饰键放在前面:按顺序按下、倒序松开,先选了 C 再选 Ctrl 也是 Ctrl+C + static func ordered(_ codes: [String]) -> [String] { + codes.filter { modifiers.contains($0) } + codes.filter { !modifiers.contains($0) } + } } +/// 内置的快捷键:按被控端的系统(Mac 的复制是 ⌘C,Windows / Linux 是 Ctrl+C) enum ShortcutProfiles { - private static let file = "shortcuts.json" + /// 有快捷键的系统:电脑。手机那边是系统操作(通知栏、截屏……) + static func supports(_ os: OsKind) -> Bool { os == .mac || os == .windows || os == .linux } static func defaults(for os: OsKind) -> [SavedShortcut] { let items: [(String, [String])] @@ -31,63 +57,72 @@ enum ShortcutProfiles { ("combo_copy", ["ControlLeft", "KeyC"]), ("combo_paste", ["ControlLeft", "KeyV"]), ("combo_undo", ["ControlLeft", "KeyZ"]), ("combo_print_screen", ["PrintScreen"])] case .linux: - items = [("combo_alt_tab", ["AltLeft", "Tab"]), ("combo_copy", ["ControlLeft", "KeyC"]), - ("combo_paste", ["ControlLeft", "KeyV"]), ("combo_undo", ["ControlLeft", "KeyZ"])] + // 和 Windows 一样,去掉 Linux 上没有对应功能的 Win 系列和任务管理器 + items = [("combo_ctrl_alt_del", ["ControlLeft", "AltLeft", "Delete"]), ("combo_alt_tab", ["AltLeft", "Tab"]), + ("combo_alt_f4", ["AltLeft", "F4"]), ("combo_copy", ["ControlLeft", "KeyC"]), + ("combo_paste", ["ControlLeft", "KeyV"]), ("combo_undo", ["ControlLeft", "KeyZ"]), + ("combo_print_screen", ["PrintScreen"])] case .android, .ios, .unknown: items = [] } return items.map { SavedShortcut(id: $0.0, title: nil, codes: $0.1) } } - static func load(for os: OsKind) -> [SavedShortcut] { - let profiles = SharedStore.read(file, as: [String: [SavedShortcut]].self) ?? [:] - return profiles[os.rawValue] ?? defaults(for: os) - } - - static func save(_ shortcuts: [SavedShortcut], for os: OsKind) { - var profiles = SharedStore.read(file, as: [String: [SavedShortcut]].self) ?? [:] - profiles[os.rawValue] = shortcuts - SharedStore.write(file, profiles) + /// 保存过的列表 + 后来新加的内置快捷键:内置的删不掉,保存的列表里没有的就是新版本加的,放在最后; + /// 新版本去掉了的内置快捷键也不再显示。没保存过(`saved` 为 nil)就是内置的 + static func merge(_ saved: [SavedShortcut]?, for os: OsKind) -> [SavedShortcut] { + let presets = defaults(for: os) + guard let saved else { return presets } + let ids = Set(presets.map(\.id)) + let kept = saved.filter { ($0.isCustom || ids.contains($0.id)) && $0.isValid } + let have = Set(kept.map(\.id)) + return kept + presets.filter { !have.contains($0.id) } } } -@Observable final class ShortcutPanelModel { - let os: OsKind - var items: [SavedShortcut] - var editing = false +/// 快捷键列表:按被控端的系统分开存(改 Mac 的不影响 Windows 的),只存改过的系统。 +/// 菜单的快捷键页和键盘的快捷键面板都看这一份,一处改了另一处跟着变 +@Observable final class ShortcutStore { + static let shared = ShortcutStore() + private static let file = "shortcuts.json" - init(os: OsKind) { - self.os = os - items = ShortcutProfiles.load(for: os) + /// 系统(`OsKind.rawValue`)→ 保存的列表 + private(set) var profiles: [String: [SavedShortcut]] + + init() { + profiles = SharedStore.read(Self.file, as: [String: [SavedShortcut]].self) ?? [:] } - func reload() { items = ShortcutProfiles.load(for: os) } + func list(for os: OsKind) -> [SavedShortcut] { ShortcutProfiles.merge(profiles[os.rawValue], for: os) } - func upsert(_ item: SavedShortcut) { - if let index = items.firstIndex(where: { $0.id == item.id }) { - items[index] = item - } else { - items.append(item) - } - persist() + func save(_ items: [SavedShortcut], for os: OsKind) { + profiles[os.rawValue] = items + SharedStore.write(Self.file, profiles) } - func move(_ index: Int, by offset: Int) { - let destination = index + offset - guard items.indices.contains(index), items.indices.contains(destination) else { return } - items.swapAt(index, destination) - persist() + /// 改一个;新加的放在最后 + func upsert(_ item: SavedShortcut, for os: OsKind) { + var items = list(for: os) + if let i = items.firstIndex(where: { $0.id == item.id }) { items[i] = item } else { items.append(item) } + save(items, for: os) } - func delete(_ item: SavedShortcut) { - guard item.id.hasPrefix("custom:") else { return } - items.removeAll { $0.id == item.id } - persist() + func move(_ index: Int, by offset: Int, for os: OsKind) { + var items = list(for: os) + let to = index + offset + guard items.indices.contains(index), items.indices.contains(to) else { return } + items.swapAt(index, to) + save(items, for: os) } - private func persist() { ShortcutProfiles.save(items, for: os) } + /// 只能删自己加的 + func delete(_ item: SavedShortcut, for os: OsKind) { + guard item.isCustom else { return } + save(list(for: os).filter { $0.id != item.id }, for: os) + } } +/// 添加 / 编辑一个快捷键:名字和按键(选键时名字还空着就先填上按键)。名字和内置的一样时不存,换了语言跟着变 struct ShortcutEditor: View { let original: SavedShortcut let os: OsKind @@ -104,10 +139,16 @@ struct ShortcutEditor: View { self.os = os self.save = save self.close = close - _title = State(initialValue: shortcut.title ?? (shortcut.id.hasPrefix("custom:") ? "" : L.t(shortcut.id))) + _title = State(initialValue: shortcut.title ?? (shortcut.isCustom ? "" : L.t(shortcut.id))) _codes = State(initialValue: shortcut.codes) } + private var name: String { title.trimmingCharacters(in: .whitespacesAndNewlines) } + + private func keysLabel(_ codes: [String]) -> String { + codes.map { GameItem.keyLabel($0, os: os) }.joined(separator: " + ") + } + var body: some View { NavigationStack { Form { @@ -118,32 +159,35 @@ struct ShortcutEditor: View { HStack { Text(L.t("shortcut_keys")) Spacer() - Text(codes.isEmpty ? L.t("shortcut_pick") : codes.map { GameItem.keyLabel($0, os: os) }.joined(separator: " + ")) + Text(codes.isEmpty ? L.t("shortcut_pick") : keysLabel(codes)) .foregroundStyle(Theme.sub) } } } .scrollContentBackground(.hidden) .background(Theme.bg) - .navigationTitle(L.t("shortcut_edit")) + .navigationTitle(L.t(original.codes.isEmpty ? "shortcut_add" : "shortcut_edit")) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { Button(L.t("cancel")) { finish() } } ToolbarItem(placement: .confirmationAction) { Button(L.t("ok")) { var item = original - let name = title.trimmingCharacters(in: .whitespacesAndNewlines) - item.title = name == L.t(original.id) && !original.id.hasPrefix("custom:") ? nil : name + item.title = !original.isCustom && name == L.t(original.id) ? nil : name item.codes = codes save(item) finish() } - .disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || codes.isEmpty) + .disabled(name.isEmpty || codes.isEmpty) } } } .sheet(isPresented: $picking) { - KeyPicker(initial: codes, os: os, keyboardOnly: true, maxKeys: 4) { codes = $0 } + KeyPicker(initial: codes, os: os, keyboardOnly: true, maxKeys: SavedShortcut.maxKeys) { picked in + let ordered = SavedShortcut.ordered(picked) + codes = ordered + if name.isEmpty { title = keysLabel(ordered) } + } } .preferredColorScheme(.dark) } diff --git a/ios/Shared/L10n.swift b/ios/Shared/L10n.swift index 7b437550..a1fe0e51 100644 --- a/ios/Shared/L10n.swift +++ b/ios/Shared/L10n.swift @@ -173,8 +173,9 @@ enum L { "game_mouse_left": "左键", "game_mouse_right": "右键", "game_mouse_middle": "中键", "game_wheel_up": "滚轮↑", "game_wheel_down": "滚轮↓", "game_duplicate_item": "复制", "game_empty_layout_hint": "还没有按钮,点上面的 + 添加", "game_tip": "按住按钮就是按着那个键;空白处拖动在游戏隐藏光标时转视角。菜单 → 游戏按键 → 编辑布局可以自己摆。", // 快捷键 - "shortcut_add": "添加快捷键", "shortcut_edit": "编辑快捷键", "shortcut_reorder": "调整顺序", "shortcut_name": "名称", "shortcut_keys": "按键", "shortcut_pick": "选择按键", - "shortcut_pick_hint": "按顺序选择最多 4 个键;先选修饰键,最后选主键", + "shortcut_add": "添加快捷键", "shortcut_edit": "编辑快捷键", "shortcut_manage": "编辑", "shortcut_name": "名称", "shortcut_keys": "按键", "shortcut_pick": "选择按键", + "shortcut_move_up": "上移", "shortcut_move_down": "下移", + "shortcut_pick_hint": "最多选 4 个键,一起按下(Ctrl、⌘ 这些修饰键会自动放在前面)", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab 切换窗口", "combo_win": "Win 开始菜单", "combo_win_d": "Win + D 显示桌面", "combo_win_e": "Win + E 文件资源管理器", "combo_win_l": "Win + L 锁屏", "combo_alt_f4": "Alt + F4 关闭窗口", "combo_task_manager": "Ctrl + Shift + Esc 任务管理器", "combo_copy": "Ctrl + C 复制", @@ -367,8 +368,9 @@ enum L { "game_group_function": "Function keys", "game_group_nav": "Navigation & editing", "game_group_symbols": "Symbols", "game_group_pad": "Gamepad (Xbox)", "game_mouse_left": "Left", "game_mouse_right": "Right", "game_mouse_middle": "Middle", "game_wheel_up": "Wheel ↑", "game_wheel_down": "Wheel ↓", "game_duplicate_item": "Duplicate", "game_empty_layout_hint": "No buttons yet — tap + above to add one", "game_tip": "Hold a button to hold its key; drag on empty space to turn the view when a game hides the cursor. Menu → Game controls → Edit layout to arrange them.", - "shortcut_add": "Add shortcut", "shortcut_edit": "Edit shortcut", "shortcut_reorder": "Reorder", "shortcut_name": "Name", "shortcut_keys": "Keys", "shortcut_pick": "Choose keys", - "shortcut_pick_hint": "Choose up to 4 keys in order: modifiers first, main key last", + "shortcut_add": "Add shortcut", "shortcut_edit": "Edit shortcut", "shortcut_manage": "Edit", "shortcut_name": "Name", "shortcut_keys": "Keys", "shortcut_pick": "Choose keys", + "shortcut_move_up": "Move up", "shortcut_move_down": "Move down", + "shortcut_pick_hint": "Choose up to 4 keys to press together (modifiers such as Ctrl and ⌘ go first automatically)", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab switch windows", "combo_win": "Win Start menu", "combo_win_d": "Win + D show desktop", "combo_win_e": "Win + E File Explorer", "combo_win_l": "Win + L lock", "combo_alt_f4": "Alt + F4 close window", "combo_task_manager": "Ctrl + Shift + Esc Task Manager", "combo_copy": "Ctrl + C copy", diff --git a/ios/Tests/ShortcutTests.swift b/ios/Tests/ShortcutTests.swift index 50d0aa6f..c14359c5 100644 --- a/ios/Tests/ShortcutTests.swift +++ b/ios/Tests/ShortcutTests.swift @@ -7,4 +7,33 @@ final class ShortcutTests: XCTestCase { XCTAssertEqual(ShortcutProfiles.defaults(for: .windows).first { $0.id == "combo_copy" }?.codes, ["ControlLeft", "KeyC"]) XCTAssertEqual(ShortcutProfiles.defaults(for: .linux).first { $0.id == "combo_copy" }?.codes, ["ControlLeft", "KeyC"]) } + + func testOnlyKeyboardKeys() { + XCTAssertTrue(SavedShortcut.isKey("MetaLeft")) + XCTAssertTrue(SavedShortcut.isKey("PrintScreen")) + XCTAssertFalse(SavedShortcut.isKey("mouse:left")) + XCTAssertFalse(SavedShortcut.isKey("wheel:up")) + XCTAssertFalse(SavedShortcut.isKey("pad:a")) + XCTAssertFalse(SavedShortcut(id: "custom:x", title: "X", codes: ["ControlLeft", "AltLeft", "ShiftLeft", "MetaLeft", "KeyA"]).isValid) + } + + func testModifiersArePressedFirst() { + XCTAssertEqual(SavedShortcut.ordered(["KeyC", "ControlLeft", "ShiftLeft"]), ["ControlLeft", "ShiftLeft", "KeyC"]) + XCTAssertEqual(SavedShortcut.ordered(["MetaLeft", "Tab"]), ["MetaLeft", "Tab"]) + } + + func testSavedListKeepsOrderAndPicksUpNewPresets() { + let defaults = ShortcutProfiles.merge(nil, for: .linux) + XCTAssertEqual(defaults.map(\.id), ShortcutProfiles.defaults(for: .linux).map(\.id)) + + // 用户把复制挪到最前、加了一个自己的;保存的列表里少了一个内置的(新版本加的)、多了一个已经去掉的内置的 + let custom = SavedShortcut(id: "custom:1", title: "Find", codes: ["ControlLeft", "KeyF"]) + let saved = [defaults.first { $0.id == "combo_copy" }!, custom, SavedShortcut(id: "combo_gone", title: nil, codes: ["KeyG"])] + + defaults.filter { $0.id != "combo_copy" && $0.id != "combo_undo" } + let merged = ShortcutProfiles.merge(saved, for: .linux) + XCTAssertEqual(merged.first?.id, "combo_copy") + XCTAssertEqual(merged[1], custom) + XCTAssertEqual(merged.last?.id, "combo_undo") + XCTAssertEqual(merged.count, defaults.count + 1) + } }