Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions android/app/src/main/java/app/airhand/android/AirhandApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down
143 changes: 143 additions & 0 deletions android/app/src/main/java/app/airhand/android/data/Shortcuts.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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 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

/**
* 快捷键(控制电脑时):只存在控制端,按的是 W3C `KeyboardEvent.code`,用现有的按键协议发,被控端不用改。
* 内置的 [id] 是它的字符串资源名,[title] 为空时显示内置的名字(跟着语言变);自己加的 [id] 以 `custom:` 开头
*/
data class SavedShortcut(val id: String, val title: String?, val codes: List<String>) {
/** 自己加的(只有这些能删) */
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 {
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<String>): List<String> = 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 > MAX_KEYS || !codes.all(::isKey)) 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<String>) {
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<ShortcutPreset> = 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")),
)
// 和 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<SavedShortcut>?): List<SavedShortcut> {
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)
}
}

/** 快捷键列表:按被控端的系统分开存(改 Mac 的不影响 Windows 的),只存改过的系统。菜单和键盘的快捷键面板都看这一份 */
class ShortcutStore(context: Context) {
private val file = File(context.filesDir, "shortcuts.json")
private val _flow = MutableStateFlow(load())

/** 系统([OsKind.wire])→ 保存的列表 */
val flow: StateFlow<Map<String, List<SavedShortcut>>> = _flow.asStateFlow()

private fun load(): Map<String, List<SavedShortcut>> {
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<String, List<SavedShortcut>> = _flow.value): List<SavedShortcut> =
ShortcutDefaults.merge(os, saved[os.wire])

@Synchronized
fun save(os: OsKind, items: List<SavedShortcut>) {
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())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -431,12 +431,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,
Expand Down
36 changes: 26 additions & 10 deletions android/app/src/main/java/app/airhand/android/ui/session/GameUi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -725,19 +726,24 @@ 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
private fun KeyPicker(
internal fun KeyPicker(
initial: List<String>,
onStick: ((keys: List<String>, analog: PadStick?) -> Unit)?,
onPick: (List<String>) -> 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<String>().apply { if (initial.size > 1) addAll(initial) } }
fun keyName(code: String) = keyLabel(code, macKeys, text)
var combo by remember { mutableStateOf(keyboardOnly || initial.size > 1) }
val chosen = remember { mutableStateListOf<String>().apply { if (keyboardOnly || initial.size > 1) addAll(initial) } }
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
Expand All @@ -755,7 +761,7 @@ private fun KeyPicker(
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f),
)
FilterChip(
if (!keyboardOnly) FilterChip(
selected = combo,
onClick = {
combo = !combo
Expand All @@ -766,13 +772,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),
)
Expand All @@ -790,20 +796,20 @@ private fun KeyPicker(
KeyCap(stringResource(R.string.game_pad_right_stick)) { onStick(GameBind.WASD, PadStick.RIGHT) }
}
}
GameKeys.groups.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 ->
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
}
}
}
Expand All @@ -813,6 +819,16 @@ private fun KeyPicker(
}
}

/** 键名;控制 Mac 时 Win 键写成 ⌘、Alt 写成 ⌥(和键盘上方的特殊键一样) */
internal fun keyLabel(code: String, mac: Boolean, text: (Int) -> String): String = when {
!mac -> GameKeys.label(code, text)
code == "MetaLeft" -> "⌘"
code == "MetaRight" -> "R-⌘"
code == "AltLeft" -> "⌥"
code == "AltRight" -> "R-⌥"
else -> GameKeys.label(code, text)
}

@Composable
private fun GroupTitle(text: String) {
Text(
Expand Down
Loading