From 020c1ff0d96a94687799a9cb38c4ad7fe6faea94 Mon Sep 17 00:00:00 2001 From: sqlpxc Date: Wed, 2 Dec 2026 22:24:00 +0800 Subject: [PATCH 1/3] feat(input): plug the controller's gamepads into Windows and Linux hosts Gamepads connected to the controller are plugged into the host as wired Xbox 360 controllers through airhand-dock 0.2.0 (usbip-win2 on Windows; vhci-hcd as root or uinput otherwise on Linux), so every game sees a real gamepad, and the game's rumble comes back to the controller's gamepad. - proto: InputEvent::Gamepad (the whole XINPUT_GAMEPAD state of one pad) and GamepadRemoved; HostMsg::Gamepad (whether the host can take gamepads, and why not) and HostMsg::Rumble. Adjacent states of one pad with the same buttons coalesce, never across a button change. - link: rumble keeps the latest value per pad on the host's outbox; the controller queue coalesces gamepad states; SessionEvent::Gamepad / Rumble. - desktop host: virtual pads belong to the controller (its handshake identity), survive a reconnect within 30 s and are unplugged at once on a normal disconnect; plugging runs on one worker thread; status is probed at session start and while a driver or permission is missing. - console (desktop and web): Gamepad API hub, toolbar menu, rumble through vibrationActuator, a notice when the host can't take gamepads. - Android (phones and TVs) and iOS: gamepad capture, rumble, menu entries. - docs, protocol fixtures and tests on every side. --- README.md | 1 + README.zh-CN.md | 1 + android/app/src/main/AndroidManifest.xml | 2 + .../airhand/android/controller/Gamepads.kt | 392 ++++++++++ .../app/airhand/android/controller/Input.kt | 21 +- .../android/controller/RemoteSession.kt | 62 +- .../java/app/airhand/android/core/Model.kt | 24 + .../java/app/airhand/android/ui/Messages.kt | 14 + .../android/ui/session/PhoneSession.kt | 45 ++ .../android/ui/session/SessionActivity.kt | 58 +- .../airhand/android/ui/session/TvSession.kt | 35 +- .../app/src/main/res/values-zh/strings.xml | 16 + android/app/src/main/res/values/strings.xml | 16 + .../android/controller/ProtocolTest.kt | 42 ++ client/src-tauri/Cargo.lock | 11 + client/src-tauri/Cargo.toml | 4 + client/src-tauri/src/e2e.rs | 16 +- client/src-tauri/src/host/gamepad.rs | 706 ++++++++++++++++++ client/src-tauri/src/host/input/macos.rs | 7 +- client/src-tauri/src/host/input/windows.rs | 7 +- client/src-tauri/src/host/input/x11.rs | 7 +- client/src-tauri/src/host/mod.rs | 1 + client/src-tauri/src/host/session.rs | 84 ++- client/src/components/Icons.tsx | 11 + client/src/components/SessionView.tsx | 77 +- client/src/lib/api.ts | 30 +- client/src/lib/gamepad.ts | 352 +++++++++ client/src/lib/input.ts | 10 +- client/src/lib/messages.ts | 33 +- client/src/lib/session.ts | 89 ++- client/src/locales/en.ts | 15 + client/src/locales/zh.ts | 17 + client/tests/gamepad.test.ts | 125 ++++ client/tests/protocol-contract.ts | 15 + client/tests/protocol.test.ts | 10 +- client/tests/session.test.ts | 64 ++ crates/airhand-link/src/controller/mod.rs | 7 + crates/airhand-link/src/controller/queue.rs | 45 +- crates/airhand-link/src/controller/session.rs | 28 +- crates/airhand-link/src/host/queue.rs | 59 +- crates/airhand-link/tests/protocol.json | 15 + crates/airhand-link/tests/protocol.rs | 12 + crates/airhand-proto/src/session.rs | 247 +++++- crates/airhand-proto/tests/v10.rs | 41 + docs/android.md | 5 + docs/android.zh-CN.md | 5 + docs/architecture.md | 12 + docs/architecture.zh-CN.md | 12 + docs/development.md | 2 + docs/development.zh-CN.md | 2 + docs/ios.md | 4 + docs/ios.zh-CN.md | 4 + docs/limitations.md | 1 + docs/limitations.zh-CN.md | 1 + docs/usage.md | 16 + docs/usage.zh-CN.md | 16 + ios/Airhand/Controller/Gamepads.swift | 302 ++++++++ ios/Airhand/Controller/RemoteSession.swift | 44 +- ios/Airhand/Core/Protocol.swift | 15 +- ios/Airhand/Session/SessionController.swift | 37 + ios/Airhand/Session/SessionMenu.swift | 61 ++ ios/Shared/L10n.swift | 18 + ios/Shared/Model.swift | 19 + ios/Tests/ProtocolTests.swift | 22 + ios/project.yml | 2 + 65 files changed, 3424 insertions(+), 50 deletions(-) create mode 100644 android/app/src/main/java/app/airhand/android/controller/Gamepads.kt create mode 100644 client/src-tauri/src/host/gamepad.rs create mode 100644 client/src/lib/gamepad.ts create mode 100644 client/tests/gamepad.test.ts create mode 100644 ios/Airhand/Controller/Gamepads.swift diff --git a/README.md b/README.md index f82a16d5..819c831e 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ See [How it works → Video](docs/architecture.md#video) for details. - **Android**: control computers and phones from a phone as a trackpad or touchscreen, or share your own screen to get help (a device needs the pairing code shown on the phone the first time, and you're notified whenever one connects); watch on a TV with the remote - **iPhone / iPad**: the same remote control as on Android (trackpad / touch gestures, keyboard, mouse with pointer lock on iPad, game controls), or share the screen through the system screen broadcast (view only: iOS doesn't let apps be controlled) - **Audio**: the host's system audio plays on the controller (Opus + adaptive jitter buffer), with optional A/V sync for watching videos. The other way, the controller can send its microphone to meeting apps and voice typing on Windows, macOS 14.2+ and Linux (PipeWire) hosts. Mac and Linux hosts publish **Airhand Microphone** while forwarding is on +- **Gamepads**: gamepads on the controller (desktop and web consoles, Android phones and TVs, iPhone / iPad) are plugged into Windows and Linux hosts as wired Xbox 360 controllers through [airhand-dock](https://github.com/sqlpxc/airhand-dock), so every game sees a real gamepad, and games make your gamepad vibrate. Windows hosts need [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases) installed once. [Details](docs/usage.md#gamepads) - **Handy tools**: two-way clipboard sync (text, plus files and folders, sent when you paste), typing the clipboard as keystrokes, system shortcuts (Win, Alt+Tab, Ctrl+Shift+Esc…), multiple monitors (switch between them, show and control several at once, or give each its own window to put on your own screens in full screen), keyboard lock in fullscreen, quality presets - **Secure by default**: sessions are end-to-end encrypted, so the relay server can't see the screen or keystrokes; the first connection needs the pairing code from the other computer's tray (it never goes through the server), and its identity is recognized afterwards; TLS 1.3 with certificate pinning, brute-force protection for control codes; the host always sees who is connected and can disconnect them with one click - **Leaves nothing behind**: the host is just a tray icon and doesn't start a WebView; everything worth keeping is in one `config.toml`, other runtime files are deleted on exit, and nothing is left after [uninstalling](docs/usage.md#uninstalling) (Windows has an uninstaller, where you choose whether the virtual display driver goes too; macOS has "Uninstall Airhand…" in the menu, Linux takes two commands) diff --git a/README.zh-CN.md b/README.zh-CN.md index eac6d062..e892b192 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -43,6 +43,7 @@ Airhand 是一个**高性能、低延迟**的远程桌面:画面用 GPU 硬件 - **Android**:在手机上用触控板或触屏的方式控制电脑、手机,也能共享自己的屏幕让别人协助(对方第一次连接时要输入手机上显示的配对码,有设备连上来时会提醒你);在电视上用遥控器看画面 - **iPhone / iPad**:和 Android 一样控制电脑、手机(触控板 / 触屏手势、键盘、外接鼠标,iPad 上可以锁定指针、游戏按键),也能用系统的屏幕广播共享自己的屏幕(只能被看:iOS 不允许别的应用操作本机) - **声音**:被控端的系统声音同步到控制端(Opus + 自适应抖动缓冲),看视频时可以打开音画同步。反过来,控制端的麦克风可以转发给 Windows、macOS 14.2+ 和 Linux(PipeWire)被控端,供那里的会议软件和语音输入使用。Mac 和 Linux 会在转发期间提供一个 **Airhand Microphone** 录音设备 +- **手柄**:控制端接着的手柄(桌面和网页控制台、Android 手机和电视、iPhone / iPad)经 [airhand-dock](https://github.com/sqlpxc/airhand-dock) 作为有线 Xbox 360 手柄插到 Windows、Linux 被控端上,所有游戏看到的都是真手柄,游戏的震动也传回你的手柄。Windows 被控端要先装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases)。[详情](docs/usage.zh-CN.md#手柄) - **实用工具**:剪贴板双向同步(文字,以及文件、文件夹:粘贴时才传)、以键盘输入方式发送剪贴板、系统快捷键(Win、Alt+Tab、Ctrl+Shift+Esc……)、多显示器(可以同时显示、同时操作对方的几个显示器,也可以每个显示器单独一个窗口,放到本机的各个显示器上全屏)、全屏时锁定键盘、画质预设 - **默认安全**:会话端到端加密,中转服务器看不到画面和键盘输入;第一次连接要输入对方托盘里的配对码(不经过服务器),之后认得出对方的身份;TLS 1.3 + 证书指纹固定,控制码防暴力猜测;被控端随时能看到谁连着,一键断开 - **不留痕迹**:被控端只有一个托盘图标,不启动 WebView;要保存的东西都在一个 `config.toml` 里,其余运行时文件退出时删除;[卸载](docs/usage.zh-CN.md#卸载)后什么都不剩(Windows 用卸载程序,虚拟显示器驱动删不删由你选;macOS 在菜单里选“卸载 Airhand…”,Linux 两条命令) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index b97d6b57..0a5f52f9 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -12,6 +12,8 @@ + + diff --git a/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt b/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt new file mode 100644 index 00000000..9c8ce52b --- /dev/null +++ b/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt @@ -0,0 +1,392 @@ +package app.airhand.android.controller + +import android.content.Context +import android.hardware.input.InputManager +import android.os.Build +import android.os.CombinedVibration +import android.os.Handler +import android.os.Looper +import android.os.VibrationEffect +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.roundToInt + +/** 一个手柄现在的样子:XInput 的格式(同 Rust 的 `InputEvent::Gamepad`:扳机 0-255,摇杆 -32768..32767、Y 向上为正) */ +data class PadState( + val buttons: Int = 0, + val leftTrigger: Int = 0, + val rightTrigger: Int = 0, + val leftX: Int = 0, + val leftY: Int = 0, + val rightX: Int = 0, + val rightY: Int = 0, +) { + /** 和上次发的比,值不值得再发:按钮、扳机变了,或者摇杆动了至少 [STICK_STEP](回到正中间也算)。和控制台的 gamepad.ts 一样 */ + fun differs(o: PadState?): Boolean { + if (o == null || buttons != o.buttons || leftTrigger != o.leftTrigger || rightTrigger != o.rightTrigger) return true + return listOf(leftX to o.leftX, leftY to o.leftY, rightX to o.rightX, rightY to o.rightY) + .any { (a, b) -> abs(a - b) >= STICK_STEP || (a == 0) != (b == 0) } + } + + companion object { + /** 摇杆变化不到这么多不算(-32768..32767 里约 0.2%):放着不动时读数也在跳 */ + const val STICK_STEP = 64 + + /** -1..1 → -32768..32767 */ + fun stick(v: Float): Int { + val x = v.coerceIn(-1f, 1f) + return (if (x < 0) x * 32768f else x * 32767f).roundToInt() + } + + /** 0..1 → 0..255 */ + fun trigger(v: Float): Int = (v.coerceIn(0f, 1f) * 255f).roundToInt() + } +} + +/** XInput 的按钮位(`airhand_proto::session::gamepad_buttons`) */ +object XInput { + const val DPAD_UP = 0x0001 + const val DPAD_DOWN = 0x0002 + const val DPAD_LEFT = 0x0004 + const val DPAD_RIGHT = 0x0008 + const val START = 0x0010 + const val BACK = 0x0020 + const val LEFT_THUMB = 0x0040 + const val RIGHT_THUMB = 0x0080 + const val LEFT_SHOULDER = 0x0100 + const val RIGHT_SHOULDER = 0x0200 + const val GUIDE = 0x0400 + const val A = 0x1000 + const val B = 0x2000 + const val X = 0x4000 + const val Y = 0x8000 + + /** Android 的手柄按键 → XInput 的按钮(L2 / R2 是扳机,另外处理) */ + val KEYS: Map = mapOf( + KeyEvent.KEYCODE_BUTTON_A to A, + KeyEvent.KEYCODE_BUTTON_B to B, + KeyEvent.KEYCODE_BUTTON_X to X, + KeyEvent.KEYCODE_BUTTON_Y to Y, + KeyEvent.KEYCODE_BUTTON_L1 to LEFT_SHOULDER, + KeyEvent.KEYCODE_BUTTON_R1 to RIGHT_SHOULDER, + KeyEvent.KEYCODE_BUTTON_THUMBL to LEFT_THUMB, + KeyEvent.KEYCODE_BUTTON_THUMBR to RIGHT_THUMB, + KeyEvent.KEYCODE_BUTTON_START to START, + KeyEvent.KEYCODE_BUTTON_SELECT to BACK, + KeyEvent.KEYCODE_BUTTON_MODE to GUIDE, + KeyEvent.KEYCODE_DPAD_UP to DPAD_UP, + KeyEvent.KEYCODE_DPAD_DOWN to DPAD_DOWN, + KeyEvent.KEYCODE_DPAD_LEFT to DPAD_LEFT, + KeyEvent.KEYCODE_DPAD_RIGHT to DPAD_RIGHT, + ) +} + +/** 这台设备接着的一个手柄(界面列出来) */ +data class LocalPad(val pad: Int, val name: String, val rumble: Boolean) + +/** + * 这台设备接着的手柄(蓝牙、USB、掌机自带的):变成发给被控端的手柄输入,被控端插成虚拟的 Xbox 360 手柄 + * (见 Rust 的 `airhand_proto::session` 的"手柄"),游戏让它震动时这里跟着震。和控制台的 `gamepad.ts` 是同一套规则: + * + * * 手柄的编号(pad,0..[MAX_PADS]-1):先用到(按了键、动了摇杆)的用小的,拔掉之后空出来给下一个;拔掉时告诉对方 + * ([Input.gamepadRemoved])。只是接着、没用过的手柄不插到对方那里; + * * 按键(`KEYCODE_BUTTON_*`、方向键)和轴(摇杆 `AXIS_X/Y`、`AXIS_Z/RZ`,没有时 `AXIS_RX/RY`;扳机 `AXIS_LTRIGGER/RTRIGGER` + * 或 `AXIS_BRAKE/GAS`,只有 L2 / R2 键的当作按到底;方向键也可能是 `AXIS_HAT_X/Y`)合成 XInput 的格式, + * Y 轴反过来(Android 向下为正)。只在变了的时候发,按钮变了马上发,只是摇杆动了合并着发(见 [InputSender]); + * * 交出去的事件不再给系统(方向键不会变成画面上的方向键,B 不会变成返回)。[paused] 时不拦(电视上打开菜单时用手柄选), + * 返回键、主页键从来不拦; + * * 震动:手柄自己的震动马达(Android 12 起每个马达单独控制,大马达是第一个),震着的时候每 [RUMBLE_REFRESH_MS] 重新放一次 + * (网页一样:一次只能放一段时间)。 + * + * 在主线程上用(按键、轴从窗口来);[rumble] 可以从会话的线程来。 + */ +class Gamepads(context: Context, private val send: (events: List, now: Boolean) -> Unit) : + InputManager.InputDeviceListener { + private val input = context.getSystemService(Context.INPUT_SERVICE) as InputManager + private val main = Handler(Looper.getMainLooper()) + + /** 每个编号的手柄是哪个设备([InputDevice.getId]);null = 空着 */ + private val slots = arrayOfNulls(MAX_PADS) + + /** 每个手柄现在的按键(方向键可能来自按键也可能来自轴,分开记)、轴、扳机键 */ + private val keyButtons = IntArray(MAX_PADS) + private val hatButtons = IntArray(MAX_PADS) + private val digitalTriggers = IntArray(MAX_PADS) + private val axes = arrayOfNulls(MAX_PADS) + + /** 最近发出去的([resync] 清掉:重新发完整的) */ + private val sent = arrayOfNulls(MAX_PADS) + + /** 对方要的震动(大、小马达 0-255) */ + private val rumbles = arrayOfNulls>(MAX_PADS) + + private val _pads = MutableStateFlow>(emptyList()) + + /** 这里接着的、用过的手柄(按编号) */ + val pads: StateFlow> = _pads.asStateFlow() + + /** 把手柄交给对方(会话 Live、对方能接、开关打开)。不是的时候手柄照常给系统 */ + @Volatile + var active = false + set(v) { + if (field == v) return + field = v + if (v) resync() else stopRumble() + } + + /** 暂时不拦(电视上开着菜单、对话框:用手柄选) */ + var paused = false + + /** 拦下来了、但对方接不了手柄时(按下按钮):界面说一声为什么 */ + var onRefused: (() -> Unit)? = null + + /** 对方接不了手柄(缺驱动、不支持……):照样拦下来(不变成方向键),不发,按下按钮时说一声([onRefused]) */ + @Volatile + var refuse = false + set(v) { + if (field == v) return + field = v + if (!v) resync() + } + + /** 同时按下 Select + Start:电视上打开菜单(只用手柄的人也能出来) */ + var onMenuChord: (() -> Unit)? = null + + private val refresh = object : Runnable { + override fun run() { + for (pad in 0 until MAX_PADS) rumbles[pad]?.let { (l, s) -> vibrate(pad, l, s) } + if (rumbles.any { it != null }) main.postDelayed(this, RUMBLE_REFRESH_MS) + } + } + + init { + input.registerInputDeviceListener(this, main) + } + + fun release() { + input.unregisterInputDeviceListener(this) + stopRumble() + } + + /** 对方把手柄放回了原位(释放所有按键)、刚能接手柄:下次有输入时把完整的状态发一遍 */ + fun resync() { + sent.fill(null) + val events = ArrayList() + for (pad in 0 until MAX_PADS) { + if (slots[pad] == null) events += Input.gamepadRemoved(pad) else state(pad).let { s -> + sent[pad] = s + events += Input.gamepad(pad, s) + } + } + if (active && !refuse) send(events, true) + } + + /** 窗口收到的按键:手柄的就拦下来(返回 true) */ + fun key(e: KeyEvent): Boolean { + if (!active || paused) return false + val device = e.device ?: return false + if (!isPad(device)) return false + val code = e.keyCode + val trigger = code == KeyEvent.KEYCODE_BUTTON_L2 || code == KeyEvent.KEYCODE_BUTTON_R2 + val bit = XInput.KEYS[code] + if (bit == null && !trigger) return false + val pad = assign(device.id) ?: return true + val down = e.action == KeyEvent.ACTION_DOWN + if (e.action != KeyEvent.ACTION_DOWN && e.action != KeyEvent.ACTION_UP) return true + if (trigger) { + val mask = if (code == KeyEvent.KEYCODE_BUTTON_L2) 1 else 2 + digitalTriggers[pad] = if (down) digitalTriggers[pad] or mask else digitalTriggers[pad] and mask.inv() + } else { + keyButtons[pad] = if (down) keyButtons[pad] or bit!! else keyButtons[pad] and bit!!.inv() + } + val s = state(pad) + val chord = XInput.START or XInput.BACK + if (down && (s.buttons and chord) == chord) onMenuChord?.let { + // 不是给对方的:手柄放回原位,交给界面 + keyButtons[pad] = 0 + update(pad, true) + it() + return true + } + update(pad, true) + return true + } + + /** 窗口收到的摇杆、扳机、方向键(轴):手柄的就拦下来 */ + fun motion(e: MotionEvent): Boolean { + if (!active || paused) return false + if (!e.isFromSource(InputDevice.SOURCE_JOYSTICK) || e.action != MotionEvent.ACTION_MOVE) return false + val device = e.device ?: return false + if (!isPad(device)) return false + val pad = assign(device.id) ?: return true + fun has(axis: Int) = device.getMotionRange(axis, e.source) != null + val rx = if (has(MotionEvent.AXIS_Z)) MotionEvent.AXIS_Z else MotionEvent.AXIS_RX + val ry = if (has(MotionEvent.AXIS_RZ)) MotionEvent.AXIS_RZ else MotionEvent.AXIS_RY + axes[pad] = PadState( + leftTrigger = PadState.trigger(max(e.getAxisValue(MotionEvent.AXIS_LTRIGGER), e.getAxisValue(MotionEvent.AXIS_BRAKE))), + rightTrigger = PadState.trigger(max(e.getAxisValue(MotionEvent.AXIS_RTRIGGER), e.getAxisValue(MotionEvent.AXIS_GAS))), + leftX = PadState.stick(e.getAxisValue(MotionEvent.AXIS_X)), + leftY = PadState.stick(-e.getAxisValue(MotionEvent.AXIS_Y)), + rightX = PadState.stick(e.getAxisValue(rx)), + rightY = PadState.stick(-e.getAxisValue(ry)), + ) + val hx = e.getAxisValue(MotionEvent.AXIS_HAT_X) + val hy = e.getAxisValue(MotionEvent.AXIS_HAT_Y) + hatButtons[pad] = (if (hx < -0.5f) XInput.DPAD_LEFT else 0) or (if (hx > 0.5f) XInput.DPAD_RIGHT else 0) or + (if (hy < -0.5f) XInput.DPAD_UP else 0) or (if (hy > 0.5f) XInput.DPAD_DOWN else 0) + update(pad, false) + return true + } + + /** 被控端让第 `pad` 个手柄震动(会话的线程上来) */ + fun rumble(pad: Int, large: Int, small: Int) { + if (pad !in 0 until MAX_PADS) return + main.post { + if (!active) return@post + rumbles[pad] = if (large == 0 && small == 0) null else large to small + vibrate(pad, large, small) + main.removeCallbacks(refresh) + if (rumbles.any { it != null }) main.postDelayed(refresh, RUMBLE_REFRESH_MS) + } + } + + /** 第 `pad` 个手柄现在的样子 */ + private fun state(pad: Int): PadState { + val a = axes[pad] ?: PadState() + val t = digitalTriggers[pad] + return a.copy( + buttons = keyButtons[pad] or hatButtons[pad], + leftTrigger = if (t and 1 != 0) 255 else a.leftTrigger, + rightTrigger = if (t and 2 != 0) 255 else a.rightTrigger, + ) + } + + private fun update(pad: Int, urgent: Boolean) { + val s = state(pad) + val prev = sent[pad] + if (!s.differs(prev)) return + if (refuse) { + if (s.buttons != 0 && s.buttons != prev?.buttons) onRefused?.invoke() + sent[pad] = s + return + } + sent[pad] = s + send(listOf(Input.gamepad(pad, s)), urgent || prev == null || prev.buttons != s.buttons) + } + + /** 这个设备的编号(新的就分一个空着的)。满了是 null */ + private fun assign(id: Int): Int? { + slots.indexOf(id).takeIf { it >= 0 }?.let { return it } + val free = slots.indexOf(null).takeIf { it >= 0 } ?: return null + slots[free] = id + keyButtons[free] = 0 + hatButtons[free] = 0 + digitalTriggers[free] = 0 + axes[free] = null + sent[free] = null + publish() + return free + } + + private fun publish() { + _pads.value = slots.mapIndexedNotNull { pad, id -> + val d = id?.let { InputDevice.getDevice(it) } ?: return@mapIndexedNotNull null + LocalPad(pad, d.name, hasRumble(d)) + } + } + + override fun onInputDeviceAdded(deviceId: Int) {} + + override fun onInputDeviceChanged(deviceId: Int) = publish() + + override fun onInputDeviceRemoved(deviceId: Int) { + val pad = slots.indexOf(deviceId).takeIf { it >= 0 } ?: return + slots[pad] = null + rumbles[pad] = null + val wasSent = sent[pad] != null + sent[pad] = null + publish() + if (active && !refuse && wasSent) send(listOf(Input.gamepadRemoved(pad)), true) + } + + private fun stopRumble() { + main.removeCallbacks(refresh) + for (pad in 0 until MAX_PADS) { + if (rumbles[pad] != null) { + rumbles[pad] = null + vibrate(pad, 0, 0) + } + } + } + + private fun device(pad: Int): InputDevice? = slots[pad]?.let { InputDevice.getDevice(it) } + + private fun vibrate(pad: Int, large: Int, small: Int) { + val d = device(pad) ?: return + runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + val vm = d.vibratorManager + val ids = vm.vibratorIds + if (ids.isEmpty()) return + if (large == 0 && small == 0) { + vm.cancel() + return + } + val c = CombinedVibration.startParallel() + if (ids.size >= 2) { + if (large > 0) c.addVibrator(ids[0], oneShot(large)) + if (small > 0) c.addVibrator(ids[1], oneShot(small)) + } else { + c.addVibrator(ids[0], oneShot(max(large, small))) + } + vm.vibrate(c.combine()) + } else { + @Suppress("DEPRECATION") + val v = d.vibrator + if (!v.hasVibrator()) return + if (large == 0 && small == 0) { + v.cancel() + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + v.vibrate(oneShot(max(large, small))) + } else { + @Suppress("DEPRECATION") + v.vibrate(RUMBLE_MS) + } + } + } + } + + private fun oneShot(amplitude: Int): VibrationEffect = VibrationEffect.createOneShot(RUMBLE_MS, amplitude.coerceIn(1, 255)) + + companion object { + /** 最多同时接几个手柄(`airhand_proto::session::MAX_GAMEPADS`) */ + const val MAX_PADS = 4 + + /** 一次震动放多久;震着的时候提前重新放 */ + const val RUMBLE_MS = 5000L + const val RUMBLE_REFRESH_MS = 4000L + + /** 是手柄(不是遥控器、键盘):有手柄的按键或者摇杆,不是系统虚拟出来的 */ + fun isPad(d: InputDevice?): Boolean { + if (d == null || d.isVirtual) return false + val s = d.sources + return s and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD || + s and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK + } + + private fun hasRumble(d: InputDevice): Boolean = runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + d.vibratorManager.vibratorIds.isNotEmpty() + } else { + @Suppress("DEPRECATION") + d.vibrator.hasVibrator() + } + }.getOrDefault(false) + } +} diff --git a/android/app/src/main/java/app/airhand/android/controller/Input.kt b/android/app/src/main/java/app/airhand/android/controller/Input.kt index 94adb9b7..0adaacca 100644 --- a/android/app/src/main/java/app/airhand/android/controller/Input.kt +++ b/android/app/src/main/java/app/airhand/android/controller/Input.kt @@ -43,9 +43,19 @@ object Input { /** 系统操作(被控端在 Hello 里列出的) */ fun system(action: SystemAction): JSONObject = event("system").put("action", action.wire) - /** 松开所有按着的键和鼠标按钮 */ + /** 松开所有按着的键和鼠标按钮(对方也把手柄放回原位) */ fun releaseAll(): JSONObject = event("releaseAll") + /** + * 第 `pad` 个手柄现在的样子(XInput 的格式:按钮位、扳机 0-255、摇杆 -32768..32767 且 Y 向上为正,见 [Gamepads]) + */ + fun gamepad(pad: Int, s: PadState): JSONObject = event("gamepad").put("pad", pad) + .put("buttons", s.buttons).put("leftTrigger", s.leftTrigger).put("rightTrigger", s.rightTrigger) + .put("leftX", s.leftX).put("leftY", s.leftY).put("rightX", s.rightX).put("rightY", s.rightY) + + /** 第 `pad` 个手柄拔掉了:对方拔掉对应的虚拟手柄 */ + fun gamepadRemoved(pad: Int): JSONObject = event("gamepadRemoved").put("pad", pad) + const val DOWN = "down" const val MOVE = "move" const val UP = "up" @@ -58,8 +68,8 @@ object Input { const val FORWARD = "forward" /** - * 把一个事件加到待发的一批里:紧挨着的绝对移动只留最后一个,相对移动加起来(不越过点击、按键)。 - * 和 Rust 的 `InputEvent::coalesce` 一样 + * 把一个事件加到待发的一批里:紧挨着的绝对移动只留最后一个,相对移动加起来(不越过点击、按键); + * 同一个手柄紧挨着的、按钮没变的状态只留最后一个。和 Rust 的 `InputEvent::coalesce` 一样 */ fun append(pending: MutableList, e: Any) { val last = pending.lastOrNull() @@ -67,6 +77,11 @@ object Input { val lastType = (last as? JSONObject)?.optString("type") if (type == "mouseMove" && lastType == "mouseMove") { pending[pending.size - 1] = e + } else if (type == "gamepad" && lastType == "gamepad" && + (last as JSONObject).optInt("pad") == (e as JSONObject).optInt("pad") && + last.optInt("buttons") == e.optInt("buttons") + ) { + pending[pending.size - 1] = e } else if (type == "mouseDelta" && lastType == "mouseDelta") { val a = last as JSONObject val b = e as JSONObject diff --git a/android/app/src/main/java/app/airhand/android/controller/RemoteSession.kt b/android/app/src/main/java/app/airhand/android/controller/RemoteSession.kt index 48f0c6ef..b1916378 100644 --- a/android/app/src/main/java/app/airhand/android/controller/RemoteSession.kt +++ b/android/app/src/main/java/app/airhand/android/controller/RemoteSession.kt @@ -11,6 +11,7 @@ import app.airhand.android.core.Codec import app.airhand.android.core.DecoderStats import app.airhand.android.core.DisplayInfo import app.airhand.android.core.EncoderInfo +import app.airhand.android.core.GamepadSupport import app.airhand.android.core.HostHello import app.airhand.android.core.Native import app.airhand.android.core.Notice @@ -132,6 +133,29 @@ class RemoteSession( /** 要防窥模式(开关):重连时在连接选项里带上,对方就一直保持着。跟着对方说的状态变 */ @Volatile private var privacyWanted = false + + /** + * 对方能不能接这里的手柄(Hello 之后对方会说,见 [Gamepads])。对方不能接(手机、旧版本)、还没说、重连的间隙里为 null: + * 手柄照常给系统(不拦) + */ + val gamepadState = MutableStateFlow(null) + + /** 对方插不上虚拟手柄的原因(英文技术信息) */ + val gamepadDetail = MutableStateFlow(null) + + /** 把这里的手柄插到对方电脑上(开关,默认开) */ + val gamepadEnabled = MutableStateFlow(true) + + /** 这里用过的手柄(界面列出来;由会话界面的 [Gamepads] 更新) */ + val localPads = MutableStateFlow>(emptyList()) + + /** 让对方释放了所有按键(对方也把手柄放回了原位):界面让 [Gamepads] 重新发一遍手柄现在的样子 */ + @Volatile + var onReleaseAll: (() -> Unit)? = null + + /** 游戏让第 pad 个手柄震动(大、小马达 0-255,在会话的线程上):界面交给 [Gamepads.rumble] */ + @Volatile + var onRumble: ((pad: Int, large: Int, small: Int) -> Unit)? = null val quality = MutableStateFlow( Preset.of(app.settings.value.preset).quality( VideoDecoder.decodable.firstOrNull { it in Codec.PRIORITY } ?: Codec.H264, @@ -207,9 +231,8 @@ class RemoteSession( private var sentAudio = false @Volatile private var audio: AudioPlayer? = null private var audioToken = 0L - private val sender = InputSender { events -> - if (!viewOnly) command { Commands.input(it, events) } - } + // 只看画面的会话(电视)也发手柄:在电视上用手柄玩电脑上的游戏(别的输入在 [input] 里就不要了) + private val sender = InputSender { events -> command { Commands.input(it, events) } } fun start() { // 等的被控端上线了 / 与服务器重新连上了:叫醒等待中的连接线程 @@ -271,6 +294,7 @@ class RemoteSession( val end = pump(h, ok.getInt("sid")) ?: break sid = -1 resetPrivacy() + resetGamepads() decoder.resetStream() stats.value = null stopAudio() @@ -355,8 +379,9 @@ class RemoteSession( sid = ok.getInt("sid") // 光标的槽位是被控端为一个会话分配的:新的会话从头开始 cursorSlots.clear() - // 防窥模式:对方在 Hello 之后重新说(要不要开着已经在握手里告诉它了) + // 防窥模式:对方在 Hello 之后重新说(要不要开着已经在握手里告诉它了);手柄也是 resetPrivacy() + resetGamepads() resume = Resume.fromJson(ok.optJSONArray("resume")) ?: resume // 端到端握手确认过的对方公钥:之后重连只认它;配对码用过了 ok.optString("hostKey").takeIf { it.isNotBlank() }?.let { hostKey = it } @@ -550,7 +575,32 @@ class RemoteSession( privacyDetail.value = e.optStringOrNull("detail") privacyState.value = s } + "gamepad" -> { + gamepadDetail.value = e.optStringOrNull("detail") + gamepadState.value = GamepadSupport.fromWire(e.optStringOrNull("state")) + } + "rumble" -> onRumble?.invoke(e.optInt("pad"), e.optInt("large"), e.optInt("small")) + } + } + + /** 新的会话、会话断了:对方还没说它能不能接手柄(手柄照常给系统) */ + private fun resetGamepads() { + gamepadState.value = null + gamepadDetail.value = null + } + + /** 这里的手柄的输入([Gamepads] 拼好的):只看画面的会话也发;`now=false` 的和后面的合并 */ + fun gamepad(events: List, now: Boolean) { + if (_phase.value == Phase.Live && gamepadEnabled.value) sender.send(events, now) + } + + /** 把这里的手柄插到对方电脑上(开关):关掉时对方拔掉它们 */ + fun setGamepadEnabled(on: Boolean) { + if (gamepadEnabled.value == on) return + if (!on && _phase.value == Phase.Live && gamepadState.value != null) { + sender.send((0 until Gamepads.MAX_PADS).map { Input.gamepadRemoved(it) }, true) } + gamepadEnabled.value = on } /** 新的会话、会话断了:对方还没说它的防窥模式(不显示开关)。要不要开着([privacyWanted])留着,重连时告诉对方 */ @@ -634,7 +684,9 @@ class RemoteSession( /** 输入事件(触控、键盘)。`now=false` 的会和后面的鼠标移动合并 */ fun input(events: List, now: Boolean = true) { - if (!viewOnly && _phase.value == Phase.Live) sender.send(events, now) + if (viewOnly || _phase.value != Phase.Live) return + sender.send(events, now) + if (events.any { (it as? JSONObject)?.optString("type") == "releaseAll" }) onReleaseAll?.invoke() } fun setQuality(q: Quality) { diff --git a/android/app/src/main/java/app/airhand/android/core/Model.kt b/android/app/src/main/java/app/airhand/android/core/Model.kt index 9f13f4e1..bfdc80b8 100644 --- a/android/app/src/main/java/app/airhand/android/core/Model.kt +++ b/android/app/src/main/java/app/airhand/android/core/Model.kt @@ -246,6 +246,30 @@ enum class PrivacyState(val wire: String) { } } +/** 被控端能不能接本机的手柄(`airhand_proto::session::GamepadSupport`,见 [app.airhand.android.controller.Gamepads]) */ +enum class GamepadSupport(val wire: String) { + /** 对方的平台不支持(macOS) */ + UNSUPPORTED("unsupported"), + + /** 缺驱动:Windows 没装 usbip-win2,Linux 没有 vhci-hcd / uinput */ + NO_DRIVER("noDriver"), + + /** Linux 上对方的 Airhand 不能用 /dev/uinput */ + NO_PERMISSION("noPermission"), + READY("ready"), + + /** 插不上虚拟手柄(detail 是原因),对方在用到时重试 */ + FAILED("failed"); + + /** 手柄的输入发得过去(插不上的也发:对方在用到时重试) */ + val usable get() = this == READY || this == FAILED + + companion object { + /** 不认识的(对方版本新增的;Rust 那边已经报成 unsupported)当作不支持 */ + fun fromWire(s: String?): GamepadSupport = entries.firstOrNull { it.wire == s } ?: UNSUPPORTED + } +} + object Code { /** 用户输入的控制码 → 6 位数字(允许空格 / 短横线),不合法返回 null。规则与 `airhand_proto::parse_code` 相同 */ fun parse(input: String): String? { diff --git a/android/app/src/main/java/app/airhand/android/ui/Messages.kt b/android/app/src/main/java/app/airhand/android/ui/Messages.kt index 51ed3308..35d754a2 100644 --- a/android/app/src/main/java/app/airhand/android/ui/Messages.kt +++ b/android/app/src/main/java/app/airhand/android/ui/Messages.kt @@ -4,6 +4,7 @@ import android.content.Context import android.text.format.DateUtils import androidx.annotation.StringRes import app.airhand.android.R +import app.airhand.android.core.GamepadSupport import app.airhand.android.core.Notice import app.airhand.android.core.OsKind import app.airhand.android.core.Problem @@ -21,6 +22,19 @@ import app.airhand.android.core.Updater * Rust 端新增变体时要在这里补上,否则测试失败。 */ object Messages { + /** 对方能不能接手柄、为什么不能(和控制台的 gamepadHint 一样):怎么装驱动、给权限按对方的平台说 */ + fun gamepadHint(ctx: Context, state: GamepadSupport, os: OsKind, detail: String?): String = when (state) { + GamepadSupport.READY -> ctx.getString(R.string.gamepad_ready) + GamepadSupport.NO_DRIVER -> ctx.getString( + if (os == OsKind.LINUX) R.string.gamepad_no_driver_linux else R.string.gamepad_no_driver_windows, + ) + GamepadSupport.NO_PERMISSION -> ctx.getString(R.string.gamepad_no_permission) + GamepadSupport.FAILED -> ctx.getString(R.string.gamepad_failed, detail ?: "—") + GamepadSupport.UNSUPPORTED -> ctx.getString( + if (os == OsKind.MAC) R.string.gamepad_unsupported_mac else R.string.gamepad_unsupported, + ) + } + /** * 问题对应的文案。带 `detail` 的问题,文案里用 `%1$s` 显示它(不带的文案会忽略这个参数)。 * 不认识的类型返回 null(显示成通用的"出错了") 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..c6bec38b 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 @@ -107,6 +107,7 @@ import app.airhand.android.controller.RemoteSession import app.airhand.android.controller.VideoDecoder import app.airhand.android.core.Code import app.airhand.android.core.Codec +import app.airhand.android.core.GamepadSupport import app.airhand.android.core.OsKind import app.airhand.android.core.Preset import app.airhand.android.core.PrivacyState @@ -1153,6 +1154,50 @@ private fun KeyboardCategoryPage( if (os == OsKind.MAC) SwapCtrlCommand(session) Shortcuts(os, onSendCombo) } + + GamepadSection(session, os) +} + +/** + * 手柄:对方说了它能不能接才显示(和桌面版工具栏的手柄菜单一样):开关、现在怎么样(接不了的话为什么)、 + * 这里用过的手柄 + */ +@Composable +private fun GamepadSection(session: RemoteSession, os: OsKind) { + val state by session.gamepadState.collectAsState() + val detail by session.gamepadDetail.collectAsState() + val enabled by session.gamepadEnabled.collectAsState() + val pads by session.localPads.collectAsState() + val s = state ?: return + val ctx = LocalContext.current + MenuSection(stringResource(R.string.gamepads)) + ListItem( + headlineContent = { Text(stringResource(R.string.gamepad_toggle)) }, + supportingContent = { + Text( + Messages.gamepadHint(ctx, s, os, detail), + color = if (s == GamepadSupport.READY) Color.Unspecified else MaterialTheme.colorScheme.error, + ) + }, + trailingContent = { Switch(checked = enabled, onCheckedChange = session::setGamepadEnabled) }, + colors = ListItemDefaults.colors(containerColor = Color.Transparent), + modifier = Modifier + .fillMaxWidth() + .clickable { session.setGamepadEnabled(!enabled) } + .padding(horizontal = 8.dp), + ) + Text( + if (pads.isEmpty()) { + stringResource(R.string.gamepad_none) + } else { + pads.joinToString("\n") { + ctx.getString(if (it.rumble) R.string.gamepad_item else R.string.gamepad_no_rumble, it.pad + 1, it.name) + } + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp), + ) } /** 菜单二级页里的一节:分隔线加标题 */ diff --git a/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt b/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt index 7cc1c1e9..a99be678 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt @@ -7,6 +7,7 @@ import android.media.AudioManager import android.os.Build import android.os.Bundle import android.view.KeyEvent +import android.view.MotionEvent import android.view.Surface import android.view.WindowManager import android.widget.Toast @@ -56,12 +57,14 @@ import androidx.core.view.WindowInsetsControllerCompat import androidx.lifecycle.lifecycleScope import app.airhand.android.AirhandApp import app.airhand.android.R +import app.airhand.android.controller.Gamepads import app.airhand.android.controller.RemoteSession import app.airhand.android.core.Code import app.airhand.android.core.DisplayInfo import app.airhand.android.core.OsKind import app.airhand.android.ui.Messages import app.airhand.android.ui.theme.AirhandTheme +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch @@ -84,6 +87,12 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { private var autoRotate = true private var manualLandscape: Boolean? = null + /** 这台设备接着的手柄:对方能接时插到对方电脑上(见 [Gamepads]) */ + private var gamepads: Gamepads? = null + + /** 界面在前台(手柄的输入只在这时候来) */ + private val started = MutableStateFlow(false) + override val keyboard = KeyboardController( swapCtrlCommand = { session?.let { it.os == OsKind.MAC && it.swapCtrlCommand.value } == true }, ) { events -> session?.input(events, true) } @@ -143,10 +152,11 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { lifecycleScope.launch { s.clipboardIn.collect { Toast.makeText(this@SessionActivity, R.string.clipboard_received, Toast.LENGTH_SHORT).show() } } + val pads = startGamepads(s) setContent { AirhandTheme(dark = true) { if (tv) { - TvSession(s, view, onExit = ::exit) + TvSession(s, view, pads, onExit = ::exit) } else { PhoneSession(s, view, keyboard, keyboardOpen, landscape.value, onRotate = ::rotate, onExit = ::exit) } @@ -154,6 +164,37 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { } } + /** + * 手柄:会话连着、对方说了它能不能接、开关打开、界面在前台时拦下手柄的输入:对方能接就发给它, + * 接不了就在按下按钮时说一声为什么(每次对方的说法变了只说一次)。游戏让它震动时这里跟着震 + */ + private fun startGamepads(s: RemoteSession): Gamepads { + val pads = Gamepads(this) { events, now -> s.gamepad(events, now) } + gamepads = pads + s.onRumble = pads::rumble + s.onReleaseAll = { runOnUiThread { pads.resync() } } + var told = false + pads.onRefused = { + val st = s.gamepadState.value + if (!told && st != null) { + told = true + val hint = Messages.gamepadHint(this, st, s.os, s.gamepadDetail.value) + Toast.makeText(this, getString(R.string.gamepad_refused, hint), Toast.LENGTH_LONG).show() + } + } + lifecycleScope.launch { + combine(s.phase, s.gamepadState, s.gamepadEnabled, started) { phase, st, on, fg -> + Triple(phase == RemoteSession.Phase.Live && st != null && on && fg, st, on) + }.collect { (active, st, _) -> + pads.refuse = st?.usable != true + pads.active = active + if (st == null) told = false + } + } + lifecycleScope.launch { pads.pads.collect { s.localPads.value = it } } + return pads + } + /** 对方画面的尺寸:收到的画面;还没收到时用对方当前显示器的尺寸 */ private fun remoteSize(video: Pair?, displays: List, current: Int): Pair? = video ?: displays.firstOrNull { it.index == current }?.let { it.width to it.height } @@ -200,11 +241,13 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { override fun onStart() { super.onStart() session?.setBackground(false) + started.value = true } override fun onStop() { super.onStop() session?.setBackground(true) + started.value = false } /** @@ -215,6 +258,11 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { */ override fun onDestroy() { val s = session + gamepads?.release() + if (s != null && s.onRumble != null) { + s.onRumble = null + s.onReleaseAll = null + } if (s != null && isFinishing && !isChangingConfigurations && app.session.value === s) { android.util.Log.i("airhand", "the session screen went away (task removed), disconnecting") app.endSession(s) @@ -231,10 +279,18 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { */ @SuppressLint("RestrictedApi") override fun dispatchKeyEvent(event: KeyEvent): Boolean { + // 手柄的按键先给手柄(对方能接时):方向键不要变成键盘的方向键 + if (gamepads?.key(event) == true) return true if (::view.isInitialized && session?.phase?.value == RemoteSession.Phase.Live && view.hardwareKey(event)) return true return super.dispatchKeyEvent(event) } + /** 手柄的摇杆、扳机(对方能接时);别的(鼠标、触控板)照常给画面 */ + override fun dispatchGenericMotionEvent(ev: MotionEvent): Boolean { + if (gamepads?.motion(ev) == true) return true + return super.dispatchGenericMotionEvent(ev) + } + override fun onSurface(surface: Surface?) { session?.setSurface(surface) } diff --git a/android/app/src/main/java/app/airhand/android/ui/session/TvSession.kt b/android/app/src/main/java/app/airhand/android/ui/session/TvSession.kt index 153e4a3a..b925fef3 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/TvSession.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/TvSession.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.AspectRatio +import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material.icons.outlined.VideoSettings import androidx.compose.material.icons.outlined.HighQuality import androidx.compose.material.icons.outlined.Sync @@ -40,6 +41,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue @@ -66,8 +68,10 @@ import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView import app.airhand.android.AirhandApp import app.airhand.android.R +import app.airhand.android.controller.Gamepads import app.airhand.android.controller.RemoteSession import app.airhand.android.core.Code +import app.airhand.android.core.GamepadSupport import app.airhand.android.core.Codec import app.airhand.android.core.OsKind import app.airhand.android.core.Preset @@ -84,9 +88,12 @@ import kotlin.math.roundToInt * * 确认键 / 菜单键:打开右侧菜单(声音、音画同步、显示器、画质、编码格式、画面缩放、信息、断开) * * 左 / 右:切换对方的显示器(有多个时) * * 返回:关菜单;没开菜单时确认断开 + * + * 手柄(对方能接时)插到对方电脑上,可以在电视上玩电脑里的游戏;同时按手柄的 Select + Start 打开菜单, + * 菜单、对话框开着时手柄用来选(见 [Gamepads.paused]) */ @Composable -fun TvSession(session: RemoteSession, view: RemoteView, onExit: () -> Unit) { +fun TvSession(session: RemoteSession, view: RemoteView, pads: Gamepads?, onExit: () -> Unit) { val ctx = LocalContext.current val video by session.videoSize.collectAsState() val phase by session.phase.collectAsState() @@ -121,6 +128,12 @@ fun TvSession(session: RemoteSession, view: RemoteView, onExit: () -> Unit) { } } LaunchedEffect(menu, confirmExit) { if (!menu && !confirmExit) runCatching { root.requestFocus() } } + // 菜单、对话框开着时手柄用来选;只有手柄的人用 Select + Start 打开菜单 + LaunchedEffect(pads, menu, confirmExit) { pads?.paused = menu || confirmExit } + DisposableEffect(pads) { + pads?.onMenuChord = { menu = true } + onDispose { pads?.onMenuChord = null } + } fun switchDisplay(step: Int) { if (displays.size < 2) return @@ -344,6 +357,26 @@ private fun TvMenu( app.updateSettings { it.copy(tvScale = next) } } TvMenuItem(Icons.Outlined.Info, stringResource(R.string.tv_info), stringResource(if (info) R.string.on else R.string.off)) { onInfo() } + // 手柄:对方说了它能不能接才显示(电脑能接,手机不能) + val gamepad by session.gamepadState.collectAsState() + val gamepadOn by session.gamepadEnabled.collectAsState() + gamepad?.let { st -> + TvMenuItem( + Icons.Outlined.SportsEsports, + stringResource(R.string.gamepads), + when { + !gamepadOn -> stringResource(R.string.off) + st == GamepadSupport.READY -> stringResource(R.string.on) + else -> Messages.gamepadHint(LocalContext.current, st, session.os, session.gamepadDetail.value) + }, + ) { session.setGamepadEnabled(!gamepadOn) } + Text( + stringResource(R.string.gamepad_tv_hint), + color = Color.White.copy(alpha = 0.6f), + fontSize = 14.sp, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } TvMenuItem(Icons.Outlined.LinkOff, stringResource(R.string.disconnect), null, danger = true) { onDisconnect() } } } diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml index 80cc5366..06c88863 100644 --- a/android/app/src/main/res/values-zh/strings.xml +++ b/android/app/src/main/res/values-zh/strings.xml @@ -344,6 +344,22 @@ 对方电脑的设置不允许防窥模式(config.toml 里的 privacy_mode) 对方电脑前的人可以断开它的网络或者重启它来结束防窥模式 + + 手柄 + 把手柄插到对方电脑上 + 这里接着的每个手柄都会作为一个 Xbox 360 手柄插到对方电脑上,游戏可以让它震动 + 对方电脑要先装 usbip-win2(免费、有签名的驱动)才能插虚拟手柄:在那台电脑上从 github.com/vadimgrn/usbip-win2/releases 下载安装,不用重启 Airhand + 对方电脑既没有 uinput 也没有 vhci-hcd:在那台电脑上运行 sudo modprobe uinput + 对方电脑上的 Airhand 不能用 /dev/uinput:装上 Steam 的手柄规则(steam-devices),或者照 Airhand 文档加一条 udev 规则 + 对方电脑没能插上虚拟手柄(%1$s),再用手柄时会重试 + 对方电脑不能接手柄 + 对方是 Mac:macOS 不允许插虚拟手柄 + 在这台设备接着的手柄上按一下按键就开始用它 + %1$d. %2$s + %1$d. %2$s(不能震动) + 手柄没有发给对方:%1$s + 在手柄上同时按 Select 和 Start 打开这个菜单 + 在画面上显示 按住按钮就是按着对应的键;其他地方照常操作,游戏隐藏了光标时拖动就是转视角 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index d42196d7..0d6ef7e4 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -351,6 +351,22 @@ The remote computer\'s settings don\'t allow privacy mode (privacy_mode in config.toml) Someone at the remote computer can end privacy mode by disconnecting it from the network or restarting it + + Gamepads + Plug gamepads into the remote computer + Each gamepad connected here shows up on the remote computer as an Xbox 360 controller. Games can make it vibrate + The remote computer needs usbip-win2 (a free, signed driver) for virtual gamepads: install it there from github.com/vadimgrn/usbip-win2/releases, no need to restart Airhand + The remote computer has neither uinput nor vhci-hcd: run sudo modprobe uinput there + Airhand on the remote computer can\'t use /dev/uinput: install Steam\'s controller rules (steam-devices) or add the udev rule from the Airhand docs + The remote computer couldn\'t plug in a virtual gamepad (%1$s). It tries again when you use the gamepad + The remote computer can\'t take gamepads + The remote is a Mac: macOS doesn\'t allow virtual gamepads + Press a button on a gamepad connected to this device to use it + %1$d. %2$s + %1$d. %2$s (can\'t vibrate) + The gamepad isn\'t sent to the remote computer: %1$s + Select + Start on the gamepad opens this menu + Show on the screen Hold a button to hold its key. Everywhere else works as usual; when a game hides the cursor, dragging turns the view diff --git a/android/app/src/test/java/app/airhand/android/controller/ProtocolTest.kt b/android/app/src/test/java/app/airhand/android/controller/ProtocolTest.kt index 91f721d6..4fbf96a0 100644 --- a/android/app/src/test/java/app/airhand/android/controller/ProtocolTest.kt +++ b/android/app/src/test/java/app/airhand/android/controller/ProtocolTest.kt @@ -1,12 +1,14 @@ package app.airhand.android.controller import app.airhand.android.core.Codec +import app.airhand.android.core.GamepadSupport import app.airhand.android.core.PrivacyState import app.airhand.android.core.Quality import app.airhand.android.core.SystemAction import org.json.JSONArray import org.json.JSONObject import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -96,6 +98,8 @@ class ProtocolTest { Input.releaseAll(), Input.touch(1, Input.DOWN, 0.25f, 0.75f), Input.system(SystemAction.BACK), + Input.gamepad(1, PadState(buttons = XInput.A or XInput.DPAD_UP, rightTrigger = 255, leftX = -32768, leftY = 32767, rightY = -1)), + Input.gamepadRemoved(1), ) assertEquals(want.length(), have.size) for (i in have.indices) assertSame(want.get(i), have[i]) @@ -139,6 +143,44 @@ class ProtocolTest { ) } + /** 会话事件 `gamepad` 的状态(Rust 的 `GamepadSupport`,camelCase);不认识的当作不支持 */ + @Test + fun gamepadStatesMatchRust() { + assertEquals( + listOf("unsupported", "noDriver", "noPermission", "ready", "failed"), + GamepadSupport.entries.map { it.wire }, + ) + for (s in GamepadSupport.entries) assertEquals(s, GamepadSupport.fromWire(s.wire)) + assertEquals(GamepadSupport.UNSUPPORTED, GamepadSupport.fromWire("somethingNew")) + assertEquals(listOf(GamepadSupport.READY, GamepadSupport.FAILED), GamepadSupport.entries.filter { it.usable }) + } + + /** 手柄:-1..1 换成 XInput 的范围,摇杆的小抖动不算变了,按钮变了的不和前面的合并(和控制台的 gamepad.ts 一样) */ + @Test + fun gamepadStatesConvertAndCoalesce() { + assertEquals(-32768, PadState.stick(-1f)) + assertEquals(32767, PadState.stick(1f)) + assertEquals(16384, PadState.stick(0.5f)) + assertEquals(255, PadState.trigger(2f)) + val rest = PadState() + assertTrue(rest.differs(null)) + assertTrue(PadState(leftX = 1).differs(rest)) + assertFalse(PadState(leftX = 1000 + PadState.STICK_STEP - 1).differs(PadState(leftX = 1000))) + assertTrue(PadState(buttons = XInput.B).differs(rest)) + val pending = ArrayList() + for (e in listOf( + Input.gamepad(0, PadState(leftX = 1)), Input.gamepad(0, PadState(leftX = 2)), + Input.gamepad(0, PadState(buttons = XInput.A, leftX = 3)), Input.gamepad(1, PadState(buttons = XInput.A)), + )) { + Input.append(pending, e) + } + assertSame( + JSONArray().put(Input.gamepad(0, PadState(leftX = 2))).put(Input.gamepad(0, PadState(buttons = XInput.A, leftX = 3))) + .put(Input.gamepad(1, PadState(buttons = XInput.A))), + JSONArray(pending), + ) + } + /** connect:控制码加上连接选项(和桌面版、网页版一样的 ConnectOptions) */ @Test fun connectOptionsMatchRust() { diff --git a/client/src-tauri/Cargo.lock b/client/src-tauri/Cargo.lock index 5ee7012c..7e6f1287 100644 --- a/client/src-tauri/Cargo.lock +++ b/client/src-tauri/Cargo.lock @@ -56,6 +56,7 @@ dependencies = [ name = "airhand" version = "0.4.1" dependencies = [ + "airhand-dock", "airhand-link", "airhand-proto", "anyhow", @@ -110,6 +111,16 @@ dependencies = [ "zip", ] +[[package]] +name = "airhand-dock" +version = "0.2.0" +source = "git+https://github.com/sqlpxc/airhand-dock?tag=v0.2.0#3b3cc9291a819fdbe9d808f12d5985da6b1754f4" +dependencies = [ + "libc", + "log", + "windows-sys 0.61.2", +] + [[package]] name = "airhand-link" version = "0.4.1" diff --git a/client/src-tauri/Cargo.toml b/client/src-tauri/Cargo.toml index 2ac732f2..8f893528 100644 --- a/client/src-tauri/Cargo.toml +++ b/client/src-tauri/Cargo.toml @@ -113,6 +113,10 @@ windows = { version = "0.62", features = [ [target.'cfg(not(windows))'.dependencies] dirs = "7" +# 控制端的手柄插成本机的虚拟 Xbox 360 手柄(见 src/host/gamepad.rs):Windows 经 usbip-win2,Linux 经 vhci-hcd 或 uinput +[target.'cfg(any(windows, target_os = "linux"))'.dependencies] +airhand-dock = { git = "https://github.com/sqlpxc/airhand-dock", tag = "v0.2.0" } + # Linux 被控端:X11(MIT-SHM 采集 + DAMAGE 变化检测 + XFIXES 光标/剪贴板 + XTEST 注入), # 声音用 PulseAudio(PipeWire 的 pipewire-pulse 同样适用)监听默认输出设备。 # x11rb 是纯 Rust 实现的 X11 协议,不依赖 libX11/libxcb;arboard 已经在用同一版本。 diff --git a/client/src-tauri/src/e2e.rs b/client/src-tauri/src/e2e.rs index c0331cdb..25e19e52 100644 --- a/client/src-tauri/src/e2e.rs +++ b/client/src-tauri/src/e2e.rs @@ -18,8 +18,8 @@ use airhand_link::wire::{read_msg, write_msg}; use airhand_proto::handshake::SEAL_OVERHEAD; use airhand_proto::media::{self, AudioHeader, VideoHeader}; use airhand_proto::session::{ - ByeReason, Codec, ControllerDatagram, ControllerMsg, HostMsg, InputEvent, MicState, Notice, - QualitySettings, + ByeReason, Codec, ControllerDatagram, ControllerMsg, GamepadSupport, HostMsg, InputEvent, + MicState, Notice, QualitySettings, }; use airhand_proto::signal::{ClientMsg, ConnectError, ServerMsg, connect_outcome}; use airhand_proto::{MAX_SIGNAL_MSG, Role}; @@ -91,6 +91,8 @@ struct Report { audio_failed: u32, /// 被控端说的麦克风状态(同一个版本:都懂麦克风) mic: Option, + /// 被控端说的手柄状态(桌面被控端都会说,macOS 是不支持) + gamepad: Option, } /// 用配对码连上被控端 `code`(请求编号 `req_id`),做完端到端握手。和真正的控制端一样:开始时的画质和声音在握手里 @@ -264,6 +266,7 @@ async fn e2e_roundtrip() { capture_failed: 0, audio_failed: 0, mic: None, + gamepad: None, }; // 被控端在同一进程里,可以直接读它的时钟:画面和声音的采集时间戳都应落在"刚刚" let age_ms = |capture_us: u64| { @@ -434,6 +437,12 @@ async fn e2e_roundtrip() { } // 防窥模式(装了虚拟显示器驱动的 Windows、有辅助功能权限的 macOS 被控端能开):这个测试不开 HostMsg::Privacy { state, detail } => println!("防窥模式: {state:?} {detail:?}"), + HostMsg::Gamepad { state, detail } => { + println!("手柄: {state:?} {detail:?}"); + rep.gamepad = Some(state); + } + // 这个测试不插手柄,不会有震动 + HostMsg::Rumble { .. } => panic!("rumble without a gamepad"), HostMsg::Notice(notice) => { println!("提示: {notice:?}"); match notice.expect("同一个版本的提示都认识") { @@ -522,6 +531,9 @@ async fn e2e_roundtrip() { // 同一个版本的两端都懂麦克风:被控端会说它能不能接(Windows 看有没有 Steam Streaming Microphone) let mic = rep.mic.expect("被控端没有说麦克风的状态"); assert_eq!(mic, crate::host::mic::probe(0).await.0); + // 手柄也是:被控端会说它能不能接(Windows 看有没有 usbip-win2,Linux 看 vhci-hcd / uinput) + let gamepad = rep.gamepad.expect("被控端没有说手柄的状态"); + assert_eq!(gamepad, crate::host::gamepad::probe().0); if capture { assert!(rep.frames >= 2, "收到的视频帧太少"); assert!(rep.keyframes >= 1); diff --git a/client/src-tauri/src/host/gamepad.rs b/client/src-tauri/src/host/gamepad.rs new file mode 100644 index 00000000..f1848df7 --- /dev/null +++ b/client/src-tauri/src/host/gamepad.rs @@ -0,0 +1,706 @@ +//! 控制端的手柄(见 `airhand_proto::session` 的"手柄"):在本机插上虚拟的有线 Xbox 360 手柄,游戏看到的就是 +//! 一个插在 USB 上的真手柄(XInput、DirectInput、Windows.Gaming.Input、SDL、Steam、evdev……)。 +//! +//! 用的是 [airhand-dock](https://github.com/sqlpxc/airhand-dock):Windows 经 usbip-win2(要先装好,不用管理员权限, +//! 系统服务里的被控端也能用),Linux 是 root 时经 vhci-hcd,不是 root 时经 uinput(要能读写 `/dev/uinput`)。 +//! macOS 没有办法插虚拟手柄:告诉控制端不支持。 +//! +//! * 虚拟手柄属于控制端(按它在端到端握手里的身份),不属于某一个会话:同一个控制端断线重连之后接着用原来的 +//! 几个手柄,游戏不会以为手柄断开了。控制端的最后一个会话结束时:正常结束的(控制端断开、本机断开了它) +//! 马上拔掉([`ended`]);断掉的等 [`KEEP`],这期间连回来就接着用,等不到再拔掉; +//! * 会话收到手柄的状态就交给虚拟手柄([`Gamepads::handle`]:状态变了才给系统一个报告,很快),第一次收到某个手柄时 +//! 创建它、交给插拔线程去插(插一个要几十毫秒,usbip-win2 最多等 10 秒),插上之前收到的状态插上时一起给系统; +//! * 插拔都在一个线程上([`worker`]):拔掉要等系统放开设备(最多两秒),不能在会话的任务里等。插不上的手柄 +//! [`RETRY`] 之后再收到它的状态时再试; +//! * 游戏让手柄震动(airhand-dock 的回调,在 USB/IP 连接的线程上):发给这个控制端最新的会话(`HostMsg::Rumble`, +//! 每个手柄只留最新值); +//! * 能不能接是整台电脑的事([`status`]):会话开始时看一次(不插手柄),插不上时变成插不上的原因,插上了又变回 +//! 能接;每个会话把变化告诉自己的控制端。缺驱动、没有权限时会话定时再看([`probe`]),例如对方刚装好 usbip-win2。 + +use airhand_proto::session::{GamepadSupport, InputEvent}; +use tokio::sync::watch; + +/// 这台电脑能不能接手柄,以及出错时的技术信息(英文) +pub type Status = (GamepadSupport, Option); + +/// 控制端的身份(端到端握手里的公钥) +pub type Controller = [u8; 32]; + +/// 控制端的会话断掉之后(不是它自己断开的),它的虚拟手柄留这么久,等它重连(和远程控制结束的等待一样,见 `ending`) +pub const KEEP: std::time::Duration = std::time::Duration::from_secs(30); + +/// 插不上的手柄过这么久再试 +#[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))] +const RETRY: std::time::Duration = std::time::Duration::from_secs(5); + +/// 这台电脑现在能不能接手柄。还没看过时([`probe`])是不支持 +static STATUS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| watch::Sender::new((GamepadSupport::Unsupported, None))); + +/// 能不能接手柄变了(插不上、又插上了、装好了驱动……) +pub fn status_changes() -> watch::Receiver { + STATUS.subscribe() +} + +/// 现在能不能接手柄(上次 [`probe`] 或者插手柄时知道的) +pub fn status() -> Status { + STATUS.borrow().clone() +} + +#[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))] +fn set_status(s: Status) { + STATUS.send_if_modified(|now| { + let changed = *now != s; + *now = s; + changed + }); +} + +/// 看一下这台电脑能不能接手柄(不插手柄、没有副作用),记下来。会阻塞(Windows 上要打开 usbip-win2 的设备): +/// 不要在异步任务里直接调用 +pub fn probe() -> Status { + let s = imp::probe(); + set_status(s.clone()); + s +} + +/// 这个状态是缺了什么(驱动、权限):会话定时再看一下,装好了就能用 +pub fn missing(s: &Status) -> bool { + matches!(s.0, GamepadSupport::NoDriver | GamepadSupport::NoPermission) +} + +/// 一个会话里控制端的手柄。丢掉时(会话结束)离开:见模块说明 +pub struct Gamepads { + #[cfg(any(windows, target_os = "linux"))] + inner: imp::Session, +} + +impl Gamepads { + /// 控制端 `controller` 的会话 `session_id`:震动从 `out` 发给它 + #[allow(unused_variables)] + pub fn new(controller: Controller, session_id: u64, out: airhand_link::host::Outbox) -> Self { + Self { + #[cfg(any(windows, target_os = "linux"))] + inner: imp::Session::new(controller, session_id, out), + } + } + + /// 控制端确认了握手:从现在起这个控制端的手柄震动发给这个会话。确认之前(可能是重放的握手消息)不接手, + /// 第一次收到手柄的输入时也算 + pub fn confirmed(&mut self) { + #[cfg(any(windows, target_os = "linux"))] + self.inner.join(); + } + + /// 一批输入里和手柄有关的:手柄的状态、拔掉了,以及"释放所有按键"(手柄都放回原位)。别的不管 + #[allow(unused_variables)] + pub fn handle(&mut self, events: &[InputEvent]) { + #[cfg(any(windows, target_os = "linux"))] + self.inner.handle(events); + } +} + +/// 会话结束了:`normal` 是正常结束的(控制端断开、本机断开了它)。这个控制端没有别的会话了的话,马上拔掉它的 +/// 手柄,不等它重连(会话断掉的,丢掉 [`Gamepads`] 时已经开始等了) +#[allow(unused_variables)] +pub fn ended(session_id: u64, normal: bool) { + #[cfg(any(windows, target_os = "linux"))] + if normal { + imp::ended(session_id); + } +} + +/// 这批输入里有没有手柄的事件(没有的话不用交给 [`Gamepads`]) +pub fn involves_gamepads(events: &[InputEvent]) -> bool { + events.iter().any(|e| { + matches!( + e, + InputEvent::Gamepad { .. } | InputEvent::GamepadRemoved { .. } | InputEvent::ReleaseAll + ) + }) +} + +#[cfg(not(any(windows, target_os = "linux")))] +mod imp { + use super::Status; + use airhand_proto::session::GamepadSupport; + + /// macOS:没有虚拟 USB 设备(或者 uinput)这样的办法插手柄 + pub fn probe() -> Status { + (GamepadSupport::Unsupported, None) + } +} + +#[cfg(any(windows, target_os = "linux"))] +mod imp { + use std::collections::HashMap; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::{LazyLock, Mutex, MutexGuard, mpsc}; + use std::time::Instant; + + use airhand_dock::{BackendKind, Buttons, Dock, ErrorKind, GamepadState, Plugged, Xbox360}; + use airhand_link::host::Outbox; + use airhand_proto::session::{GamepadSupport, HostMsg, InputEvent, MAX_GAMEPADS}; + use tracing::{info, warn}; + + use super::{Controller, KEEP, RETRY, Status, set_status}; + + pub fn probe() -> Status { + let s = Dock::status(BackendKind::Auto); + if s.available { + (GamepadSupport::Ready, None) + } else { + (support(s.reason), s.problem) + } + } + + /// airhand-dock 说的原因 → 告诉控制端的 + fn support(reason: Option) -> GamepadSupport { + match reason { + Some(ErrorKind::BackendUnavailable) => GamepadSupport::NoDriver, + Some(ErrorKind::PermissionDenied) => GamepadSupport::NoPermission, + Some(ErrorKind::Unsupported) => GamepadSupport::Unsupported, + _ => GamepadSupport::Failed, + } + } + + /// 一个虚拟手柄 + struct Pad { + device: Xbox360, + /// 插拔线程插好之后放进来。丢掉它就是拔掉(会阻塞):只在插拔线程上丢([`discard`]) + plugged: Option, + /// 插拔线程正在插 + plugging: bool, + /// 插不上:这之前不再试 + retry_at: Option, + /// 认出插拔线程插好的是不是还是这一个(插的期间可能被拔掉、又换了一个) + generation: u64, + } + + /// 一个控制端(按身份)的虚拟手柄和会话 + struct Owner { + /// 它的会话和发给它的队列(震动发给最后一个) + sessions: Vec<(u64, Outbox)>, + pads: [Option; MAX_GAMEPADS as usize], + /// 最后离开的会话([`ended`] 据此认出它) + last_session: u64, + } + + impl Owner { + fn take_pads(&mut self) -> Vec { + self.pads.iter_mut().filter_map(Option::take).collect() + } + } + + static OWNERS: LazyLock>> = LazyLock::new(Mutex::default); + static GENERATION: AtomicU64 = AtomicU64::new(1); + + fn owners() -> MutexGuard<'static, HashMap> { + OWNERS.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// 插拔线程的活 + enum Job { + Plug { + controller: Controller, + index: u8, + generation: u64, + device: Xbox360, + }, + /// 拔掉(丢掉)这些 + Discard(Vec), + } + + static WORKER: Mutex>> = Mutex::new(None); + + /// 交给插拔线程(第一次用时启动它) + fn submit(job: Job) { + let mut w = WORKER.lock().unwrap_or_else(|e| e.into_inner()); + // 线程意外结束了(不会发生)就再起一个 + let job = match w.as_ref() { + Some(tx) => match tx.send(job) { + Ok(()) => return, + Err(mpsc::SendError(job)) => job, + }, + None => job, + }; + let (tx, rx) = mpsc::channel(); + match std::thread::Builder::new() + .name("airhand-gamepads".into()) + .spawn(move || worker(rx)) + { + Ok(_) => { + let _ = tx.send(job); + *w = Some(tx); + } + Err(e) => warn!("can't start the gamepad thread: {e}"), + } + } + + /// 拔掉这些手柄:在插拔线程上(拔掉会阻塞) + fn discard(pads: Vec) { + if pads.iter().any(|p| p.plugged.is_some()) { + submit(Job::Discard(pads)); + } + } + + /// 插拔线程:整个进程一个,插拔都在这里一个一个做。airhand-dock 的 [`Dock`] 也在这里,第一次插手柄时打开 + /// (Windows 上会顺便拔掉之前崩溃的进程留下的),之后一直留着 + fn worker(rx: mpsc::Receiver) { + let mut dock: Option = None; + for job in rx { + match job { + Job::Plug { + controller, + index, + generation, + device, + } => { + let result = match &dock { + Some(d) => Ok(d.clone()), + None => Dock::new().inspect(|d| { + info!(backend = %d.backend(), "opened the gamepad dock"); + dock = Some(d.clone()); + }), + } + .and_then(|d| d.plug(&device)); + let mut owners = owners(); + let pad = owners + .get_mut(&controller) + .and_then(|o| o.pads[index as usize].as_mut()) + .filter(|p| p.generation == generation); + match (result, pad) { + (Ok(plugged), Some(pad)) => { + info!(pad = index, ?plugged, "plugged a virtual gamepad"); + pad.plugged = Some(plugged); + pad.plugging = false; + drop(owners); + set_status((GamepadSupport::Ready, None)); + } + // 插的期间拔掉了(控制端拔掉了手柄、会话结束了) + (Ok(plugged), None) => { + drop(owners); + drop(plugged); + } + (Err(e), pad) => { + if let Some(pad) = pad { + pad.plugging = false; + pad.retry_at = Some(Instant::now() + RETRY); + } + drop(owners); + warn!(pad = index, "can't plug a virtual gamepad: {e}"); + set_status((support(Some(e.kind())), Some(e.to_string()))); + } + } + } + Job::Discard(pads) => drop(pads), + } + } + } + + /// 游戏让第 `index` 个手柄震动(airhand-dock 的回调,在 USB/IP 连接的线程上):发给这个控制端最新的会话 + fn rumble(controller: &Controller, index: u8, generation: u64, large: u8, small: u8) { + let out = { + let owners = owners(); + let Some(owner) = owners.get(controller) else { + return; + }; + // 已经换成另一个手柄了(这是旧的拔掉时的回调) + if owner.pads[index as usize] + .as_ref() + .is_none_or(|p| p.generation != generation) + { + return; + } + owner.sessions.last().map(|(_, out)| out.clone()) + }; + if let Some(out) = out { + let _ = out.send(&HostMsg::Rumble { + pad: index, + large, + small, + }); + } + } + + /// 一个会话:见 [`super::Gamepads`] + pub struct Session { + controller: Controller, + session_id: u64, + /// 还没接手时拿着(接手时放进 [`OWNERS`]) + out: Option, + } + + impl Session { + pub fn new(controller: Controller, session_id: u64, out: Outbox) -> Self { + Self { + controller, + session_id, + out: Some(out), + } + } + + /// 接手这个控制端的手柄:它的震动发给这个会话;在等它重连的手柄不再等了 + pub fn join(&mut self) { + let Some(out) = self.out.take() else { return }; + let mut owners = owners(); + let owner = owners.entry(self.controller).or_insert_with(|| Owner { + sessions: Vec::new(), + pads: Default::default(), + last_session: 0, + }); + if owner.sessions.is_empty() && owner.pads.iter().any(Option::is_some) { + info!( + session_id = self.session_id, + "the controller is back, it keeps its virtual gamepads" + ); + } + owner.sessions.push((self.session_id, out)); + } + + pub fn handle(&mut self, events: &[InputEvent]) { + for e in events { + match *e { + InputEvent::Gamepad { + pad, + buttons, + left_trigger, + right_trigger, + left_x, + left_y, + right_x, + right_y, + } => self.set( + pad, + GamepadState { + buttons: Buttons(buttons), + left_trigger, + right_trigger, + left_x, + left_y, + right_x, + right_y, + }, + ), + InputEvent::GamepadRemoved { pad } => self.remove(pad), + InputEvent::ReleaseAll => self.neutral(), + _ => {} + } + } + } + + /// 第 `index` 个手柄现在是 `state`:还没有就创建它、交给插拔线程去插 + fn set(&mut self, index: u8, state: GamepadState) { + if index >= MAX_GAMEPADS { + return; + } + self.join(); + let mut job = None; + let device = { + let mut owners = owners(); + let Some(owner) = owners.get_mut(&self.controller) else { + return; + }; + let pad = owner.pads[index as usize].get_or_insert_with(|| { + let generation = GENERATION.fetch_add(1, Ordering::Relaxed); + let device = Xbox360::new(); + let controller = self.controller; + // 刚创建的手柄还没有连接,设置回调不会等谁(见 Xbox360::on_output) + device.on_output(move |o| { + rumble(&controller, index, generation, o.large_motor, o.small_motor) + }); + Pad { + device, + plugged: None, + plugging: false, + retry_at: None, + generation, + } + }); + let now = Instant::now(); + if pad.plugged.is_none() && !pad.plugging && pad.retry_at.is_none_or(|t| now >= t) { + pad.plugging = true; + pad.retry_at = None; + job = Some(Job::Plug { + controller: self.controller, + index, + generation: pad.generation, + device: pad.device.clone(), + }); + } + pad.device.clone() + }; + // 不拿着锁:状态变了会马上给系统一个报告(经 USB/IP 连接写出去) + device.set_state(&state); + if let Some(job) = job { + submit(job); + } + } + + /// 控制端拔掉了第 `index` 个手柄 + fn remove(&mut self, index: u8) { + if index >= MAX_GAMEPADS { + return; + } + let pad = owners() + .get_mut(&self.controller) + .and_then(|o| o.pads[index as usize].take()); + if let Some(pad) = pad { + info!(pad = index, "the controller unplugged a gamepad"); + discard(vec![pad]); + } + } + + /// 所有手柄放回原位(不拔掉) + fn neutral(&mut self) { + let devices: Vec = owners() + .get(&self.controller) + .map(|o| o.pads.iter().flatten().map(|p| p.device.clone()).collect()) + .unwrap_or_default(); + for d in devices { + d.set_state(&GamepadState::default()); + } + } + } + + impl Drop for Session { + /// 会话结束:这个控制端没有别的会话了的话,手柄放回原位,等它 [`KEEP`] 重连(正常结束的由 [`ended`] 马上拔掉) + fn drop(&mut self) { + if self.out.is_some() { + // 没接手过:没有手柄 + return; + } + let mut owners = owners(); + let Some(owner) = owners.get_mut(&self.controller) else { + return; + }; + owner.sessions.retain(|(id, _)| *id != self.session_id); + if !owner.sessions.is_empty() { + return; + } + owner.last_session = self.session_id; + if owner.pads.iter().all(Option::is_none) { + owners.remove(&self.controller); + return; + } + let devices: Vec = owner + .pads + .iter() + .flatten() + .map(|p| p.device.clone()) + .collect(); + drop(owners); + for d in devices { + d.set_state(&GamepadState::default()); + } + let (controller, session_id) = (self.controller, self.session_id); + let spawned = std::thread::Builder::new() + .name("airhand-gamepads-keep".into()) + .spawn(move || { + std::thread::sleep(KEEP); + expire(&controller, session_id); + }); + if spawned.is_err() { + expire(&controller, self.session_id); + } + } + } + + /// 控制端在 [`KEEP`] 之内没有连回来:拔掉它的手柄(在调用的线程上) + fn expire(controller: &Controller, session_id: u64) { + let pads = { + let mut owners = owners(); + match owners.get(controller) { + Some(o) if o.sessions.is_empty() && o.last_session == session_id => { + owners.remove(controller).map(|mut o| o.take_pads()) + } + _ => None, + } + }; + if let Some(pads) = pads { + info!( + count = pads.len(), + "the controller didn't come back, unplugging its virtual gamepads" + ); + drop(pads); + } + } + + /// 会话 `session_id` 正常结束了:它是这个控制端的最后一个会话的话,马上拔掉手柄 + pub fn ended(session_id: u64) { + let pads: Vec = { + let mut owners = owners(); + let gone: Vec = owners + .iter() + .filter(|(_, o)| o.sessions.is_empty() && o.last_session == session_id) + .map(|(k, _)| *k) + .collect(); + gone.iter() + .filter_map(|k| owners.remove(k)) + .flat_map(|mut o| o.take_pads()) + .collect() + }; + if !pads.is_empty() { + info!( + count = pads.len(), + "the controller disconnected, unplugging its virtual gamepads" + ); + discard(pads); + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn reasons_become_what_the_controller_is_told() { + assert_eq!( + support(Some(ErrorKind::BackendUnavailable)), + GamepadSupport::NoDriver + ); + assert_eq!( + support(Some(ErrorKind::PermissionDenied)), + GamepadSupport::NoPermission + ); + assert_eq!( + support(Some(ErrorKind::Unsupported)), + GamepadSupport::Unsupported + ); + assert_eq!(support(Some(ErrorKind::Timeout)), GamepadSupport::Failed); + assert_eq!(support(None), GamepadSupport::Failed); + } + + /// 会话结束了,手柄等控制端重连:同一个控制端的新会话接着用;正常结束的马上没有了 + #[test] + fn pads_belong_to_the_controller() { + let controller = [7u8; 32]; + let (out, _control, _bulk) = airhand_link::host::queue::channel(); + let mut first = Session::new(controller, 101, out.clone()); + first.join(); + // 一个还没插上的手柄(插拔线程在后台插,这里不等它) + { + let mut owners = owners(); + let owner = owners.get_mut(&controller).unwrap(); + owner.pads[0] = Some(Pad { + device: Xbox360::new(), + plugged: None, + plugging: false, + retry_at: None, + generation: 1, + }); + } + drop(first); + assert!(owners().get(&controller).is_some(), "kept for a reconnect"); + let mut second = Session::new(controller, 102, out.clone()); + second.join(); + assert!(owners()[&controller].pads[0].is_some(), "the same pad"); + drop(second); + ended(102); + assert!( + owners().get(&controller).is_none(), + "gone after a normal end" + ); + } + + /// 游戏让手柄震动:发给这个控制端最新的会话;已经换成另一个手柄的(旧手柄拔掉时的回调)不发 + #[test] + fn rumble_goes_to_the_latest_session() { + let controller = [8u8; 32]; + let (old, mut old_rx, _b1) = airhand_link::host::queue::channel(); + let (new, mut new_rx, _b2) = airhand_link::host::queue::channel(); + let mut a = Session::new(controller, 301, old); + a.join(); + let mut b = Session::new(controller, 302, new); + b.join(); + owners().get_mut(&controller).unwrap().pads[1] = Some(Pad { + device: Xbox360::new(), + plugged: None, + plugging: false, + retry_at: None, + generation: 77, + }); + rumble(&controller, 1, 77, 200, 10); + rumble(&controller, 1, 76, 1, 1); + let got: Vec = std::iter::from_fn(|| new_rx.try_recv()) + .map(|f| { + airhand_proto::framing::decode_known(&f[airhand_proto::framing::PREFIX..]) + .unwrap() + }) + .collect(); + assert!( + matches!( + got[..], + [HostMsg::Rumble { + pad: 1, + large: 200, + small: 10 + }] + ), + "{got:?}" + ); + assert!(old_rx.try_recv().is_none()); + drop(b); + drop(a); + ended(301); + assert!(owners().get(&controller).is_none()); + } + + /// 真的插一个虚拟手柄、再拔掉(Windows 要装好 usbip-win2;Linux 要 root,或者能用 `/dev/uinput`): + /// `cargo test --lib plugs_a_virtual_gamepad -- --ignored --nocapture`,跑的时候开着 joy.cpl 或者 `evtest` 能看到它 + #[test] + #[ignore = "needs usbip-win2 (Windows) or vhci-hcd / uinput access (Linux)"] + fn plugs_a_virtual_gamepad() { + use std::time::Duration; + let status = super::super::probe(); + assert_eq!(status.0, GamepadSupport::Ready, "{status:?}"); + let controller = [9u8; 32]; + let (out, _control, _bulk) = airhand_link::host::queue::channel(); + let mut s = Session::new(controller, 201, out); + s.join(); + let pad = |buttons, left_x| InputEvent::Gamepad { + pad: 0, + buttons, + left_trigger: 0, + right_trigger: 0, + left_x, + left_y: 0, + right_x: 0, + right_y: 0, + }; + s.handle(&[pad(0x1000, 1000)]); + let wait = |what: &str, done: &dyn Fn() -> bool| { + let deadline = Instant::now() + Duration::from_secs(15); + while !done() { + assert!( + Instant::now() < deadline, + "{what}: {:?}", + super::super::status() + ); + std::thread::sleep(Duration::from_millis(20)); + } + }; + let device = || { + owners() + .get(&controller) + .and_then(|o| o.pads[0].as_ref()) + .filter(|p| p.plugged.is_some()) + .map(|p| p.device.clone()) + }; + wait("plugged", &|| device().is_some()); + let d = device().unwrap(); + wait("connected", &|| d.is_connected()); + println!("plugged: {d:?}"); + assert_eq!(d.state().left_x, 1000); + s.handle(&[pad(0, -2000)]); + assert_eq!(d.state().left_x, -2000); + s.handle(&[InputEvent::ReleaseAll]); + assert_eq!(d.state(), GamepadState::default()); + std::thread::sleep(Duration::from_secs(2)); + s.handle(&[InputEvent::GamepadRemoved { pad: 0 }]); + wait("unplugged", &|| !d.is_connected()); + drop(s); + ended(201); + } + } +} diff --git a/client/src-tauri/src/host/input/macos.rs b/client/src-tauri/src/host/input/macos.rs index f8a93134..6160040a 100644 --- a/client/src-tauri/src/host/input/macos.rs +++ b/client/src-tauri/src/host/input/macos.rs @@ -150,8 +150,11 @@ impl MacInjector { } InputEvent::Text { text } => self.type_text(text), InputEvent::ReleaseAll => self.release_all(), - // 桌面被控端不声明触摸和系统操作(HostHello),控制端不会发 - InputEvent::Touch { .. } | InputEvent::System { .. } => {} + // 桌面被控端不声明触摸和系统操作(HostHello),控制端不会发;手柄由会话交给虚拟手柄(见 gamepad),不到这里 + InputEvent::Touch { .. } + | InputEvent::System { .. } + | InputEvent::Gamepad { .. } + | InputEvent::GamepadRemoved { .. } => {} } } } diff --git a/client/src-tauri/src/host/input/windows.rs b/client/src-tauri/src/host/input/windows.rs index a030107c..f3b58d08 100644 --- a/client/src-tauri/src/host/input/windows.rs +++ b/client/src-tauri/src/host/input/windows.rs @@ -179,8 +179,11 @@ impl WinInjector { } } InputEvent::ReleaseAll => self.push_release_all(), - // 桌面被控端不声明触摸和系统操作(HostHello),控制端不会发 - InputEvent::Touch { .. } | InputEvent::System { .. } => {} + // 桌面被控端不声明触摸和系统操作(HostHello),控制端不会发;手柄由会话交给虚拟手柄(见 gamepad),不到这里 + InputEvent::Touch { .. } + | InputEvent::System { .. } + | InputEvent::Gamepad { .. } + | InputEvent::GamepadRemoved { .. } => {} } } self.flush(); diff --git a/client/src-tauri/src/host/input/x11.rs b/client/src-tauri/src/host/input/x11.rs index 47931ef2..5632b396 100644 --- a/client/src-tauri/src/host/input/x11.rs +++ b/client/src-tauri/src/host/input/x11.rs @@ -155,8 +155,11 @@ impl X11Injector { } self.wheel = (0, 0); } - // 桌面被控端不声明触摸和系统操作(HostHello),控制端不会发 - InputEvent::Touch { .. } | InputEvent::System { .. } => {} + // 桌面被控端不声明触摸和系统操作(HostHello),控制端不会发;手柄由会话交给虚拟手柄(见 gamepad),不到这里 + InputEvent::Touch { .. } + | InputEvent::System { .. } + | InputEvent::Gamepad { .. } + | InputEvent::GamepadRemoved { .. } => {} } } c.x.conn.flush()?; diff --git a/client/src-tauri/src/host/mod.rs b/client/src-tauri/src/host/mod.rs index a11b3d93..81350e20 100644 --- a/client/src-tauri/src/host/mod.rs +++ b/client/src-tauri/src/host/mod.rs @@ -8,6 +8,7 @@ mod cursor; pub(crate) mod desktop; pub mod encoder; pub(crate) mod ending; +pub(crate) mod gamepad; pub mod gate; mod input; #[cfg(target_os = "macos")] diff --git a/client/src-tauri/src/host/session.rs b/client/src-tauri/src/host/session.rs index f1719d1d..eb00541b 100644 --- a/client/src-tauri/src/host/session.rs +++ b/client/src-tauri/src/host/session.rs @@ -10,6 +10,9 @@ //! [`virtual_display`]:它改了显示设置就告诉会话,会话马上重新列出显示器(画面跟着换到虚拟显示器上、换回来)。 //! 会话怎么结束的(正常结束还是出了错)交给 [`ending`]:远程控制结束了就锁屏、退出防窥模式。 //! +//! 控制端的手柄插成本机的虚拟 Xbox 360 手柄([`gamepad`]):手柄的输入不经过注入线程,直接交给它; +//! 手柄属于控制端,会话断掉时等它重连,正常结束时马上拔掉。 +//! //! macOS:会话期间按"远程控制时暂停隔空投送"暂停 AWDL(见 `crate::awdl`);走 Wi-Fi、AWDL 又开着的话告诉控制端 //! (`Notice::Awdl`),它提示插网线或者打开这一项。 @@ -21,7 +24,8 @@ use airhand_link::host::{ }; use airhand_proto::MAX_STREAMS; use airhand_proto::session::{ - DisplayInfo, HostHello, HostMsg, MicState, Notice, QualitySettings, StreamView, stricter_short, + DisplayInfo, HostHello, HostMsg, InputEvent, MicState, Notice, QualitySettings, StreamView, + stricter_short, }; use anyhow::Result; use bytes::Bytes; @@ -33,6 +37,7 @@ use super::audio::{self, AudioSubscription}; use super::capture; use super::cursor::SharedCursor; use super::ending; +use super::gamepad::{self, Gamepads}; use super::gate::DesktopGate; use super::input::InjectorThread; use super::mic::{self, MicInput, MicLease}; @@ -63,6 +68,8 @@ const MIC_CHECK: Duration = Duration::from_secs(5); const WAKE_WAIT: Duration = Duration::from_secs(3); /// macOS:多久看一次是不是走 Wi-Fi、AWDL 开着(第一次在会话开始这么久之后:打开了暂停的话,先等它暂停上) const AWDL_CHECK: Duration = Duration::from_secs(5); +/// 接不了手柄(缺驱动、没有权限)时隔多久再看一次,例如对方刚装好 usbip-win2 +const GAMEPAD_CHECK: Duration = Duration::from_secs(5); /// 显示器列表变了之后,每一路画面看的显示器在新列表里的序号:按名字找(插拔别的显示器时序号可能变), /// 找不到(被拔掉了)的那一路不要了;一路都不剩就改看主显示器(新列表的第一个,见 [`resolve_view`])。 @@ -180,7 +187,7 @@ pub async fn run(inc: Incoming, gate: Arc) -> Result<()> { VIDEO_QUEUE, audio::QUEUE, |admitted, senders| { - let mut desktop = Desktop::new(session_id, senders, slot); + let mut desktop = Desktop::new(session_id, senders, slot, admitted.key); desktop.identity = Some((gate.clone(), ip, admitted.clone())); desktop }, @@ -189,6 +196,8 @@ pub async fn run(inc: Incoming, gate: Arc) -> Result<()> { // 控制端断开了、本机断开了它(`Ok`):远程控制马上算结束;失联、连接出错:等它重连(见 ending)。 // 任务在这之前被中止了的(与服务器的连接断了)也算出错 presence.end(result.is_ok()); + // 手柄也一样:正常结束的马上拔掉,断掉的等它重连(见 gamepad) + gamepad::ended(session_id, result.is_ok()); result } @@ -248,6 +257,14 @@ struct Desktop { awdl_told: bool, /// 控制端确认了握手就算一次远程控制,结束后锁屏、退出防窥(见 [`ending`]) presence: ending::Slot, + /// 控制端的手柄(见 [`gamepad`]) + gamepads: Gamepads, + /// 这台电脑能不能接手柄变了 + gamepad_changes: watch::Receiver, + /// 告诉过控制端的(一样的不再发) + gamepad_sent: Option, + /// 接不了手柄(缺驱动、没有权限)时定时再看看 + gamepad_tick: Interval, } /// 控制端的麦克风(见 [`super::mic`]) @@ -303,14 +320,27 @@ enum Tick { Privacy, /// 该看看是不是走 Wi-Fi、AWDL 开着了(macOS) Awdl, + /// 这台电脑能不能接手柄变了(插不上、又插上了) + Gamepad, + /// 该再看一下能不能接手柄了(装好驱动了没有) + GamepadCheck, } impl Desktop { - fn new(session_id: u64, senders: Senders, presence: ending::Slot) -> Self { + fn new( + session_id: u64, + senders: Senders, + presence: ending::Slot, + controller: gamepad::Controller, + ) -> Self { let screens = virtual_display::join(session_id); Self { session_id, identity: None, + gamepads: Gamepads::new(controller, session_id, senders.out.clone()), + gamepad_changes: gamepad::status_changes(), + gamepad_sent: None, + gamepad_tick: ticker(GAMEPAD_CHECK), out: senders.out, video: senders.video, audio: senders.audio, @@ -371,6 +401,18 @@ impl Desktop { Ok(()) } + /// 告诉控制端能不能接手柄(和上次说的一样就不说了) + fn send_gamepad(&mut self, status: gamepad::Status) -> Result<()> { + if self.gamepad_sent.as_ref() == Some(&status) { + return Ok(()); + } + let (state, detail) = status.clone(); + info!(session_id = self.session_id, ?state, ?detail, "gamepads"); + self.out.send(&HostMsg::Gamepad { state, detail })?; + self.gamepad_sent = Some(status); + Ok(()) + } + /// 告诉控制端麦克风现在怎么样(和上次说的一样就不说了) fn send_mic(&mut self, status: mic::Status) -> Result<()> { if self.mic.sent.as_ref() == Some(&status) { @@ -607,6 +649,10 @@ impl Platform for Desktop { let status = mic::probe(self.session_id).await; self.send_mic(status)?; self.send_privacy()?; + let status = tokio::task::spawn_blocking(gamepad::probe) + .await + .unwrap_or_else(|_| gamepad::status()); + self.send_gamepad(status)?; Ok(()) } @@ -617,6 +663,8 @@ impl Platform for Desktop { gate.admitted(self.session_id, ip, &admitted); } self.presence.confirmed(self.session_id); + // 这个控制端的手柄(断线重连的:还插着的那几个)从现在起归这个会话 + self.gamepads.confirmed(); if self.privacy_at_start { self.screens.set_privacy(true); } @@ -630,9 +678,21 @@ impl Platform for Desktop { match req { // 晚到太久的输入已经换成了"释放所有按键"。交给注入线程就返回:在这里等它注入完的话, // 这期间 Pong、画面的确认、本机用户的断开都处理不了(见 input::thread) - Request::Input(events) => { - let displays = self.stream_displays(); - self.injector.handle(events, &displays); + Request::Input(mut events) => { + // 手柄不经过注入线程(那里可能正慢慢地输入一长段文字),直接交给虚拟手柄;"释放所有按键"两边都要 + if gamepad::involves_gamepads(&events) { + self.gamepads.handle(&events); + events.retain(|e| { + !matches!( + e, + InputEvent::Gamepad { .. } | InputEvent::GamepadRemoved { .. } + ) + }); + } + if !events.is_empty() { + let displays = self.stream_displays(); + self.injector.handle(events, &displays); + } } Request::Settings(s) => { self.settings = s; @@ -705,6 +765,10 @@ impl Platform for Desktop { // 虚拟显示器改了显示设置:马上重新列出显示器,不等定时检查 _ = self.display_changes.changed() => Tick::Displays, () = awdl_due(&mut self.awdl_tick) => Tick::Awdl, + Ok(()) = self.gamepad_changes.changed() => Tick::Gamepad, + _ = self.gamepad_tick.tick(), if self.gamepad_sent.as_ref().is_some_and(gamepad::missing) => { + Tick::GamepadCheck + } } } @@ -773,6 +837,14 @@ impl Platform for Desktop { } Tick::Mic(status) => self.send_mic(status)?, Tick::Privacy => self.send_privacy()?, + Tick::Gamepad => { + let status = self.gamepad_changes.borrow_and_update().clone(); + self.send_gamepad(status)?; + } + // 装好了驱动的话,状态随之变成能接(Tick::Gamepad 再告诉控制端) + Tick::GamepadCheck => { + let _ = tokio::task::spawn_blocking(gamepad::probe).await; + } // 插上 / 拔掉网线、暂停 / 恢复了 AWDL:提示控制端,或者撤下提示 Tick::Awdl => { let active = tokio::task::spawn_blocking(super::awdl_hint) diff --git a/client/src/components/Icons.tsx b/client/src/components/Icons.tsx index 4b9f8470..2bf40b0c 100644 --- a/client/src/components/Icons.tsx +++ b/client/src/components/Icons.tsx @@ -44,6 +44,17 @@ export const IconGamepad = (p: P) => , ); +/** 本机的手柄插到对方电脑上(工具栏的手柄按钮):两个摇杆,和鼠标的游戏模式分开 */ +export const IconController = (p: P) => + base( + p, + <> + + + + + , + ); export const IconGrid = (p: P) => base( p, diff --git a/client/src/components/SessionView.tsx b/client/src/components/SessionView.tsx index 3624ce8d..2fdbf18e 100644 --- a/client/src/components/SessionView.tsx +++ b/client/src/components/SessionView.tsx @@ -1,9 +1,19 @@ -import { type ReactNode, type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { + type ReactNode, + type RefObject, + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + useSyncExternalStore, +} from "react"; import { closeTab, fmtCode, toggleFullscreen } from "../lib/actions"; import { api, MOUSE_MODES, type MouseMode, type Platform } from "../lib/api"; import { type MsgKey, t, useT } from "../lib/i18n"; import { LocalFiles } from "../lib/files"; -import { errorText, noticeText, problemText, sessionStateText } from "../lib/messages"; +import { gamepads } from "../lib/gamepad"; +import { errorText, gamepadHint, noticeText, problemText, sessionStateText } from "../lib/messages"; import { CODEC_LABEL } from "../lib/presets"; import { SCROLL_STYLES } from "../lib/scroll-style"; import { SCALE_MODES, ZOOM_LEVELS, type RemoteSession } from "../lib/session"; @@ -11,6 +21,7 @@ import { store, useSession, useSessionTitle, useStore } from "../lib/store"; import { IconChevron, IconClipboard, + IconController, IconCpu, IconExpand, IconFit, @@ -99,7 +110,19 @@ const combosFor = (platform: Platform | null, os: string) => { return os === "" || /windows/i.test(os) ? WINDOWS_COMBOS : /^macos/i.test(os) ? MAC_COMBOS : LINUX_COMBOS; }; -type Menu = null | "quality" | "mouse" | "scale" | "keys" | "display" | "clipboard" | "audio" | "mic" | "privacy" | "sessions"; +type Menu = + | null + | "quality" + | "mouse" + | "scale" + | "keys" + | "display" + | "clipboard" + | "audio" + | "mic" + | "privacy" + | "gamepad" + | "sessions"; /** 鼠标模式的图标(工具栏的鼠标按钮显示现在的) */ const MOUSE_ICONS: Record = { auto: IconMouse, desktop: IconPointer, game: IconGamepad }; @@ -168,6 +191,9 @@ export function SessionView({ s }: { s: RemoteSession }) { const title = useSessionTitle(s); const [menu, setMenu] = useState(null); const [toast, setToast] = useState(null); + // 这里接着的手柄(接上、拔掉时刷新) + useSyncExternalStore(gamepads.subscribe, gamepads.getVersion); + const pads = gamepads.pads; /** 正在往画面上拖文件 */ const [dropping, setDropping] = useState(false); // 对方要求配对码、或者对方的身份变了(要重新配对)时输入的配对码 @@ -607,6 +633,51 @@ export function SessionView({ s }: { s: RemoteSession }) { )} )} + {s.gamepadState !== null && pads.length > 0 && ( + // 手柄:对方说了它能不能接、这里也接着手柄(浏览器在手柄上按过键之后才说)时才显示 +
+ + {menu === "gamepad" && ( + + +
+
{t("gamepad.pads")}
+ {pads.map((p) => ( +
+ {t("gamepad.pad", { n: p.pad + 1, name: p.name })} + {!p.rumble && {t("gamepad.noRumble")}} +
+ ))} +
+
{t("gamepad.note")}
+ + )} +
+ )} {s.hostPlatform !== "android" && s.hostPlatform !== "ios" && ( // 鼠标:自动 / 桌面 / 游戏(见 input.ts),还有画面里有光标时显不显示本机光标。手机是点触屏的,没有这些
diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts index e186a351..5eb9e544 100644 --- a/client/src/lib/api.ts +++ b/client/src/lib/api.ts @@ -322,6 +322,13 @@ export type MicState = "unsupported" | "noDevice" | "ready" | "busy" | "failed" */ export type PrivacyState = "unavailable" | "notAllowed" | "off" | "starting" | "on" | "failed"; +/** + * 被控端能不能接本机的手柄(airhand_proto::session::GamepadSupport):unsupported = 那个平台不支持(macOS), + * noDriver = 缺驱动(Windows 没装 usbip-win2,Linux 没有 vhci-hcd / uinput),noPermission = Linux 上不能用 /dev/uinput, + * failed = 插不上(下次用手柄时再试)。 + */ +export type GamepadSupport = "unsupported" | "noDriver" | "noPermission" | "ready" | "failed"; + /** 系统操作(手机的导航键等),与 airhand_proto::session::SystemAction 对应 */ export type SystemAction = | "back" @@ -380,6 +387,10 @@ export type SessionEvent = | { type: "mic"; state: MicState; detail: string | null } /** 被控端的防窥模式:会话开始时一次,之后有变化再来;对方不支持(Linux、手机、版本旧)时没有。detail:没能打开的原因 */ | { type: "privacy"; state: PrivacyState; detail: string | null } + /** 被控端能不能接本机的手柄:会话开始时一次,之后有变化再来;对方不能接(手机、版本旧)时没有。detail:出错时的技术信息 */ + | { type: "gamepad"; state: GamepadSupport; detail: string | null } + /** 游戏让第 pad 个手柄震动:大马达、小马达 0-255,照着震到下一次;都是 0 是停下 */ + | { type: "rumble"; pad: number; large: number; small: number } /** 被控端复制了文件(只有网页版会收到;桌面版直接放进本机剪贴板):要内容时用 remoteList / remoteRead 取 */ | { type: "clipboardFiles"; clip: number; items: FileEntry[] } /** 剪贴板里的文件传不了(被控端那边的、这边的):哪个文件、为什么 */ @@ -403,7 +414,24 @@ export type InputEvent = /** 触摸点(只发给能接收触摸的被控端;控制台用鼠标,不发) */ | { type: "touch"; id: number; phase: TouchPhase; x: number; y: number } | { type: "system"; action: SystemAction } - | { type: "releaseAll" }; + | { type: "releaseAll" } + /** + * 第 pad 个手柄现在的样子(同 XInput 的 XINPUT_GAMEPAD):buttons 是 XInput 的位,扳机 0-255,摇杆 -32768..32767、 + * Y 向上为正。是 0 的可以不写。只发给说了能接手柄的被控端(见 gamepad.ts) + */ + | { + type: "gamepad"; + pad: number; + buttons?: number; + leftTrigger?: number; + rightTrigger?: number; + leftX?: number; + leftY?: number; + rightX?: number; + rightY?: number; + } + /** 第 pad 个手柄拔掉了:被控端拔掉对应的虚拟手柄 */ + | { type: "gamepadRemoved"; pad: number }; /** 对会话的操作,与 airhand_link::controller::Command 对应(JSON 以 cmd 区分) */ export type Command = diff --git a/client/src/lib/gamepad.ts b/client/src/lib/gamepad.ts new file mode 100644 index 00000000..db18da68 --- /dev/null +++ b/client/src/lib/gamepad.ts @@ -0,0 +1,352 @@ +// 本机的手柄:用浏览器的 Gamepad API 读,变成发给被控端的手柄输入(见 airhand_proto::session 的"手柄")。 +// 被控端为每个手柄插上一个虚拟的 Xbox 360 手柄,游戏让它震动时这里的手柄跟着震。 +// +// * 整个网页一个 GamepadHub(navigator.getGamepads 是全局的),手柄交给当前在操作的会话(正在查看、画面可以操作, +// 见 session.ts 的 syncGamepads):同一时刻只有一个会话收到手柄。换了会话时,新的会话先收到一遍所有手柄的完整状态 +// (之前那个会话失去焦点时已经让对方把手柄放回原位了),以及空着的编号的"拔掉了"(它可能还以为插着); +// * 手柄的编号(pad,0..MAX_PADS-1):先接上的用小的,拔掉之后它的编号空出来给下一个; +// * 按 W3C 的标准布局(mapping "standard")对应到 XInput:按钮的顺序、扳机是按钮 6 和 7 的 value、摇杆 Y 向下为正 +// (XInput 向上为正,要反过来)。不是标准布局的手柄照同样的顺序猜; +// * 只在变了的时候发,摇杆的变化不到 STICK_STEP 不算(摇杆放着不动时读数也在跳,不然就会一直发)。按钮变了马上发; +// 只是摇杆、扳机变了和鼠标移动一样合并着发(见 input.ts 的 enqueue)。浏览器只在网页可见时更新手柄, +// 每 POLL_MS 读一次(标签页在后台时定时器慢下来,那时也不是在操作的会话); +// * 震动:vibrationActuator.playEffect("dual-rumble")。网页的震动要给时长(Chrome 最多 5 秒),XInput 的震动一直持续到 +// 下一次设置,所以震着的时候每 RUMBLE_REFRESH_MS 重新放一次;换了会话、拔掉手柄时停下。 +import type { InputEvent } from "./api"; + +/** 最多同时接几个手柄(airhand_proto::session::MAX_GAMEPADS) */ +export const MAX_PADS = 4; +/** 多久读一次手柄(毫秒) */ +const POLL_MS = 4; +/** 摇杆变化不到这么多(-32768..32767 里)不算变了:约 0.2%,比手柄自己的噪声大,游戏也看不出 */ +export const STICK_STEP = 64; +/** 网页的一次震动放多久(毫秒;Chrome 最多 5000) */ +const RUMBLE_MS = 5000; +/** 震着的时候隔多久重新放一次(赶在上一次放完之前) */ +const RUMBLE_REFRESH_MS = 4000; + +/** XInput 的按钮位(airhand_proto::session::gamepad_buttons) */ +export const BUTTONS = { + dpadUp: 0x0001, + dpadDown: 0x0002, + dpadLeft: 0x0004, + dpadRight: 0x0008, + start: 0x0010, + back: 0x0020, + leftThumb: 0x0040, + rightThumb: 0x0080, + leftShoulder: 0x0100, + rightShoulder: 0x0200, + guide: 0x0400, + a: 0x1000, + b: 0x2000, + x: 0x4000, + y: 0x8000, +} as const; + +/** 标准布局里第 i 个按钮是 XInput 的哪个按钮(6、7 是扳机,不是按钮) */ +const STANDARD: (number | null)[] = [ + BUTTONS.a, BUTTONS.b, BUTTONS.x, BUTTONS.y, + BUTTONS.leftShoulder, BUTTONS.rightShoulder, + null, null, + BUTTONS.back, BUTTONS.start, + BUTTONS.leftThumb, BUTTONS.rightThumb, + BUTTONS.dpadUp, BUTTONS.dpadDown, BUTTONS.dpadLeft, BUTTONS.dpadRight, + BUTTONS.guide, +]; + +/** 一个手柄现在的样子(XInput 的格式,同 InputEvent 的 gamepad) */ +export interface PadState { + buttons: number; + leftTrigger: number; + rightTrigger: number; + leftX: number; + leftY: number; + rightX: number; + rightY: number; +} + +type ButtonLike = Pick; + +/** -1..1 → -32768..32767 */ +function stick(v: number | undefined): number { + const x = Math.max(-1, Math.min(1, Number.isFinite(v) ? (v as number) : 0)); + // 不要 -0(JSON 里一样,比较时却不一样) + return Math.round(x < 0 ? x * 32768 : x * 32767) || 0; +} + +/** 扳机:0..1 → 0..255(只报按下没有、没有 value 的当作按到底) */ +function trigger(b: ButtonLike | undefined): number { + if (!b) return 0; + const v = Number.isFinite(b.value) && b.value > 0 ? b.value : b.pressed ? 1 : 0; + return Math.round(Math.max(0, Math.min(1, v)) * 255); +} + +/** 按标准布局读一个手柄(见文件开头) */ +export function readPad(gp: { buttons: readonly ButtonLike[]; axes: readonly number[] }): PadState { + let buttons = 0; + STANDARD.forEach((bit, i) => { + if (bit !== null && gp.buttons[i]?.pressed) buttons |= bit; + }); + return { + buttons, + leftTrigger: trigger(gp.buttons[6]), + rightTrigger: trigger(gp.buttons[7]), + leftX: stick(gp.axes[0]), + // 网页的 Y 向下为正,XInput 向上为正;-(-32768) 超出范围,stick 里会截到 32767 + leftY: stick(-(gp.axes[1] ?? 0)), + rightX: stick(gp.axes[2]), + rightY: stick(-(gp.axes[3] ?? 0)), + }; +} + +const AXES = ["leftX", "leftY", "rightX", "rightY"] as const; + +/** 和上次发的比,值不值得再发一次:按钮、扳机变了,或者摇杆动了至少 STICK_STEP(回到正中间也算) */ +export function changed(prev: PadState | null, next: PadState): boolean { + if (!prev) return true; + if (prev.buttons !== next.buttons || prev.leftTrigger !== next.leftTrigger || prev.rightTrigger !== next.rightTrigger) { + return true; + } + return AXES.some((k) => Math.abs(prev[k] - next[k]) >= STICK_STEP || ((prev[k] === 0) !== (next[k] === 0))); +} + +/** 发给被控端的手柄输入(是 0 的字段不写) */ +export function padEvent(pad: number, s: PadState): InputEvent { + const e: InputEvent & { type: "gamepad" } = { type: "gamepad", pad }; + if (s.buttons) e.buttons = s.buttons; + if (s.leftTrigger) e.leftTrigger = s.leftTrigger; + if (s.rightTrigger) e.rightTrigger = s.rightTrigger; + for (const k of AXES) if (s[k]) e[k] = s[k]; + return e; +} + +/** 收手柄输入的会话 */ +export interface GamepadTarget { + /** 手柄的输入。urgent:按钮变了(马上发);不然和鼠标移动一样合并着发 */ + gamepadInput(events: InputEvent[], urgent: boolean): void; +} + +/** 这里接着的一个手柄(界面列出来) */ +export interface LocalPad { + /** 发给对方的编号 */ + pad: number; + /** 浏览器给的名字(多半带着厂商和型号) */ + name: string; + /** 能震动 */ + rumble: boolean; +} + +/** 浏览器的手柄(测试里是假的) */ +export interface Source { + getGamepads(): readonly (Gamepad | null)[]; +} + +type Actuator = { + playEffect?: (type: string, params: Record) => Promise; + reset?: () => Promise; +}; + +export class GamepadHub { + private readonly source: Source | null; + private target: GamepadTarget | null = null; + /** 每个编号的手柄是浏览器的第几个(Gamepad.index);null = 空着 */ + private readonly slots: (number | null)[] = Array(MAX_PADS).fill(null); + /** 最近发给 target 的状态(换了 target 时清掉:重新发完整的) */ + private readonly sent: (PadState | null)[] = Array(MAX_PADS).fill(null); + /** 对方要的震动(large、small 0-255)和上次放的时刻 */ + private readonly rumbles: ({ large: number; small: number; at: number } | null)[] = Array(MAX_PADS).fill(null); + private timer: ReturnType | undefined; + private readonly listeners = new Set<() => void>(); + /** 接着的手柄变了的计数(React useSyncExternalStore) */ + version = 0; + + constructor(source: Source | null = browserGamepads()) { + this.source = source; + if (typeof window !== "undefined" && source) { + // 浏览器在手柄上按过键之后才说它接上了 + // 拔掉了的要马上告诉正在收手柄的会话(poll 里会说) + const onChange = () => (this.target ? this.poll() : this.scan()); + window.addEventListener("gamepadconnected", onChange); + window.addEventListener("gamepaddisconnected", onChange); + } + } + + /** 这里接着的手柄(按编号) */ + get pads(): LocalPad[] { + const out: LocalPad[] = []; + const all = this.gamepads(); + this.slots.forEach((index, pad) => { + const gp = index === null ? undefined : all.find((g) => g.index === index); + if (gp) out.push({ pad, name: gp.id, rumble: !!this.actuator(gp)?.playEffect }); + }); + return out; + } + + subscribe = (fn: () => void) => { + this.listeners.add(fn); + return () => void this.listeners.delete(fn); + }; + getVersion = () => this.version; + + /** `t` 开始收手柄(同一时刻只有一个):它先收到所有手柄的完整状态,和空着的编号的"拔掉了" */ + claim(t: GamepadTarget) { + if (this.target === t) return; + this.stopRumble(); + this.target = t; + this.sent.fill(null); + this.scan(); + const removed: InputEvent[] = []; + this.slots.forEach((index, pad) => { + if (index === null) removed.push({ type: "gamepadRemoved", pad }); + }); + if (removed.length) t.gamepadInput(removed, true); + this.poll(); + this.syncTimer(); + } + + /** `t` 不再收手柄(不在前台了、断开了)。手柄放回原位由会话自己让对方做(releaseAll) */ + release(t: GamepadTarget) { + if (this.target !== t) return; + this.stopRumble(); + this.target = null; + this.syncTimer(); + } + + /** 读手柄的定时器只在有会话收手柄、这里也接着手柄时跑:没有手柄时不用每 POLL_MS 醒一次 */ + private syncTimer() { + const want = this.target !== null && this.source !== null && this.slots.some((s) => s !== null); + if (want && this.timer === undefined) { + this.timer = setInterval(() => this.poll(), POLL_MS); + // Node(测试)里不要因为它不退出 + (this.timer as { unref?: () => void }).unref?.(); + } else if (!want && this.timer !== undefined) { + clearInterval(this.timer); + this.timer = undefined; + } + } + + /** + * 对方把手柄放回了原位(releaseAll)、刚能接手柄了:下次读的时候把所有手柄的完整状态再发一遍(按着不动的不会自己变) + */ + resync(t: GamepadTarget) { + if (this.target !== t) return; + this.slots.forEach((index, pad) => { + if (index !== null) this.sent[pad] = null; + }); + } + + /** 被控端让第 pad 个手柄震动(只认现在收手柄的会话的) */ + rumble(from: GamepadTarget, pad: number, large: number, small: number) { + if (from !== this.target || pad < 0 || pad >= MAX_PADS) return; + this.rumbles[pad] = large || small ? { large, small, at: -Infinity } : null; + this.applyRumble(pad, performance.now()); + } + + /** 读一次所有手柄,变了的发给 target */ + poll() { + if (!this.target) return; + if (typeof document !== "undefined" && document.visibilityState === "hidden") return; + const all = this.gamepads(); + const events: InputEvent[] = []; + let urgent = false; + this.scan(all); + // 拔掉了的(这一次、或者浏览器的 gamepaddisconnected 时收回的):告诉对方 + this.slots.forEach((index, pad) => { + if (index === null && this.sent[pad]) { + this.sent[pad] = null; + this.rumbles[pad] = null; + events.push({ type: "gamepadRemoved", pad }); + urgent = true; + } + }); + const now = performance.now(); + this.slots.forEach((index, pad) => { + const gp = index === null ? undefined : all.find((g) => g.index === index); + if (!gp) return; + const state = readPad(gp); + const prev = this.sent[pad]; + if (changed(prev, state)) { + if (!prev || prev.buttons !== state.buttons) urgent = true; + this.sent[pad] = state; + events.push(padEvent(pad, state)); + } + const r = this.rumbles[pad]; + if (r && now - r.at >= RUMBLE_REFRESH_MS) this.applyRumble(pad, now); + }); + if (events.length) this.target.gamepadInput(events, urgent); + } + + private gamepads(): Gamepad[] { + let list: readonly (Gamepad | null)[] = []; + try { + list = this.source?.getGamepads() ?? []; + } catch { + // 权限策略不允许(例如 iframe 里) + } + return list.filter((g): g is Gamepad => !!g && g.connected !== false); + } + + /** 给新接上的手柄分配编号、收回拔掉的。返回有没有变化 */ + private scan(all = this.gamepads()): boolean { + let changedAny = false; + this.slots.forEach((index, pad) => { + if (index !== null && !all.some((g) => g.index === index)) { + this.slots[pad] = null; + changedAny = true; + } + }); + for (const gp of all) { + if (this.slots.includes(gp.index)) continue; + const free = this.slots.indexOf(null); + if (free < 0) break; + this.slots[free] = gp.index; + changedAny = true; + } + if (changedAny) { + this.version++; + for (const l of this.listeners) l(); + this.syncTimer(); + } + return changedAny; + } + + private actuator(gp: Gamepad): Actuator | null { + return ((gp as unknown as { vibrationActuator?: Actuator | null }).vibrationActuator ?? null); + } + + private applyRumble(pad: number, now: number) { + const index = this.slots[pad]; + const gp = index === null ? undefined : this.gamepads().find((g) => g.index === index); + const act = gp && this.actuator(gp); + if (!act?.playEffect) return; + const r = this.rumbles[pad]; + if (!r) { + void (act.reset?.() ?? act.playEffect("dual-rumble", { duration: 0, strongMagnitude: 0, weakMagnitude: 0 })).catch(() => {}); + return; + } + r.at = now; + // 新的一次会打断上一次(Chrome 让上一次的 Promise 以 preempted 结束) + void act + .playEffect("dual-rumble", { startDelay: 0, duration: RUMBLE_MS, strongMagnitude: r.large / 255, weakMagnitude: r.small / 255 }) + .catch(() => {}); + } + + private stopRumble() { + this.rumbles.forEach((r, pad) => { + if (!r) return; + this.rumbles[pad] = null; + this.applyRumble(pad, 0); + }); + } +} + +/** 浏览器的手柄(没有 Gamepad API 时为 null) */ +function browserGamepads(): Source | null { + if (typeof navigator === "undefined") return null; + const nav = navigator as Partial; + return typeof nav.getGamepads === "function" ? (navigator as Source) : null; +} + +/** 整个网页一个(见文件开头) */ +export const gamepads = new GamepadHub(); diff --git a/client/src/lib/input.ts b/client/src/lib/input.ts index be498475..beac7c04 100644 --- a/client/src/lib/input.ts +++ b/client/src/lib/input.ts @@ -166,6 +166,8 @@ export class RemoteInput { * 不设置时粘贴键和别的键一样直接发(桌面版的剪贴板由 Rust 端自己同步) */ onPaste: ((e: ClipboardEvent) => void) | null = null; + /** 让对方释放了所有按键(对方也把手柄放回了原位):会话据此把手柄现在的样子重新发一遍(见 gamepad.ts) */ + onReleaseAll: (() => void) | null = null; /** `locate`:指针在第几路画面上(多屏);不给就是整个元素都是第 0 路画面 */ constructor(canvas: HTMLElement, connected: () => boolean, send: (events: InputEvent[]) => void, locate?: Locate) { @@ -267,6 +269,7 @@ export class RemoteInput { this.buttons = 0; this.enqueue([{ type: "releaseAll" }], true); this.settleRemoteCursor(); + this.onReleaseAll?.(); } focus() { this.canvas.focus({ preventScroll: true }); } /** @@ -283,9 +286,14 @@ export class RemoteInput { if (!this.connected()) return; for (const event of events) { const last = this.queue[this.queue.length - 1]; - // 连续的绝对移动只留最后一个,连续的相对移动加起来(不越过点击和按键) + // 连续的绝对移动只留最后一个,连续的相对移动加起来(不越过点击和按键);同一个手柄连续几个按钮没变的状态只留最后一个 if (event.type === "mouseMove" && last?.type === "mouseMove") { this.queue[this.queue.length - 1] = event; + } else if ( + event.type === "gamepad" && last?.type === "gamepad" + && last.pad === event.pad && (last.buttons ?? 0) === (event.buttons ?? 0) + ) { + this.queue[this.queue.length - 1] = event; } else if (event.type === "mouseDelta" && last?.type === "mouseDelta") { this.queue[this.queue.length - 1] = { type: "mouseDelta", dx: last.dx + event.dx, dy: last.dy + event.dy }; } else this.queue.push(event); diff --git a/client/src/lib/messages.ts b/client/src/lib/messages.ts index bd2ec03b..1a76cd73 100644 --- a/client/src/lib/messages.ts +++ b/client/src/lib/messages.ts @@ -2,7 +2,15 @@ // // 只在显示时调用(组件渲染时),所以切换语言后已经显示的问题和提示也会跟着变。 // 词条在 i18n.ts 的 problem.* / notice.*;每种 kind 都必须有词条(下面的 `as const` 让 TypeScript 检查)。 -import { toProblem, type FileError, type Problem, type RemoteNotice, type UpdateProblem } from "./api"; +import { + toProblem, + type FileError, + type GamepadSupport, + type Platform, + type Problem, + type RemoteNotice, + type UpdateProblem, +} from "./api"; import { t } from "./i18n"; import type { RemoteSession } from "./session"; @@ -18,7 +26,9 @@ export type LocalNotice = /** 剪贴板里的文件传不了(对方那边的、这边的,见 files.ts) */ | { kind: "fileError"; name: string; error: FileError } /** 对方的版本旧,不支持剪贴板里的文件 */ - | { kind: "filesUnsupported" }; + | { kind: "filesUnsupported" } + /** 在这里的手柄上按了按钮,对方却接不了手柄(为什么见 gamepadHint) */ + | { kind: "gamepadUnavailable"; state: GamepadSupport; platform: Platform | null; detail: string | null }; /** 被控端发来的"已恢复":只用来撤下之前的提示,本身不显示 */ export type RecoveredNotice = Extract; @@ -43,8 +53,27 @@ export function updateProblemText(p: UpdateProblem): string { return t(`update.problem.${kind}` as const, params); } +/** 对方能不能接手柄、为什么不能(手柄菜单、提示)。怎么装驱动、给权限按对方的平台说 */ +export function gamepadHint(state: GamepadSupport, platform: Platform | null, detail: string | null): string { + switch (state) { + case "ready": + return t("gamepad.ready"); + case "noDriver": + return t(platform === "linux" ? "gamepad.noDriverLinux" : "gamepad.noDriverWindows"); + case "noPermission": + return t("gamepad.noPermission"); + case "failed": + return t("gamepad.failed", { detail: detail ?? "—" }); + case "unsupported": + return t(platform === "mac" ? "gamepad.unsupportedMac" : "gamepad.unsupported"); + } +} + export function noticeText(n: SessionNotice): string { if (n.kind === "fileError") return t("notice.fileError", { name: n.name, reason: t(`fileError.${n.error}` as const) }); + if (n.kind === "gamepadUnavailable") { + return t("notice.gamepadUnavailable", { reason: gamepadHint(n.state, n.platform, n.detail) }); + } const { kind, ...params } = n; return t(`notice.${kind}` as const, params); } diff --git a/client/src/lib/session.ts b/client/src/lib/session.ts index 6012d2d0..c7a448af 100644 --- a/client/src/lib/session.ts +++ b/client/src/lib/session.ts @@ -17,6 +17,7 @@ // * 画面增强(可选):要放大时在 Worker 里用显卡放大、锐化,canvas 就是显示的大小(见 enhance.ts); // * 只有当前正在查看的会话播放声音,其余会话通知被控端停止采集声音; // * 本机麦克风(可选,默认关):也只发给当前正在查看的会话,被控端放进它的虚拟麦克风(见 mic.ts); +// * 本机的手柄(对方说了能接时,默认开):只交给正在操作的会话,对方插成虚拟的 Xbox 360 手柄,游戏让它震动时这里跟着震(见 gamepad.ts); // * 防窥模式(可选,默认关,装了虚拟显示器驱动的 Windows、允许了辅助功能的 macOS 被控端):对方的显示器黑屏、键盘鼠标 // 不起作用(Windows 的画面换成一块虚拟显示器)。开关跟着这个标签走:断线重连时在连接选项里带上,对方一直保持防窥; // * 音画同步(可选):按采集时间把画面推迟到与声音对齐后再解码显示,见 avsync.ts(也在 Worker 里)。 @@ -36,6 +37,7 @@ import { type MicState, type Platform, type PrivacyState, + type GamepadSupport, type StreamView, type SystemAction, type FileEntry, @@ -47,6 +49,7 @@ import { AudioOutput } from "./audio"; import { MicCapture, type MicError } from "./mic"; import { ConnectionAttempt } from "./connection-attempt"; import { RemoteInput } from "./input"; +import { gamepads, MAX_PADS, type GamepadTarget } from "./gamepad"; import type { AvSyncStats } from "./avsync"; import { bestCodec, codecUsable } from "./codec"; import type { MediaView } from "./console"; @@ -114,7 +117,7 @@ type TipKind = "awdl" | "windowsToGo"; let nextId = 1; -export class RemoteSession { +export class RemoteSession implements GamepadTarget { readonly id = `s${nextId++}`; readonly code: string; /** 画面:包着每一路画面的 canvas(只看一个显示器时只有一个)。键盘焦点、鼠标事件、锁定指针都在它上面 */ @@ -173,6 +176,12 @@ export class RemoteSession { privacyDetail: string | null = null; /** 要防窥模式(开关):重连时在连接选项里带上,对方就一直保持防窥。跟着对方说的状态变 */ privacyWanted = false; + /** 对方能不能接本机的手柄(hello 之后对方会说);对方不能接(手机、版本旧)、还没说时为 null:不发手柄 */ + gamepadState: GamepadSupport | null = null; + /** 对方插不上虚拟手柄的原因(英文技术信息) */ + gamepadDetail: string | null = null; + /** 把本机的手柄插到对方电脑上(用户开关,默认开;实际只在正在操作的会话上) */ + gamepadEnabled = true; /** 对方复制的文件(网页版:等用户点下载,见 files.ts);没有时为 null */ remoteFiles: { clip: number; items: FileEntry[] } | null = null; /** 正在把对方复制的文件取下来:已经取了多少、一共多少(字节) */ @@ -243,6 +252,10 @@ export class RemoteSession { private micOn = false; /** 在采集本机的麦克风(打开中也算) */ private micCapturing = false; + /** 本机的手柄现在交给这个会话(GamepadHub 认它) */ + private gamepadClaimed = false; + /** 这次连接里已经提示过对方接不了手柄 */ + private gamepadTold = false; /** 音画同步是否生效 */ private syncOn = false; @@ -356,6 +369,10 @@ export class RemoteSession { this.emit(); }; input.shouldSwapCtrlCommand = () => this.hostPlatform === "mac" && this.swapCtrlCommand; + // 让对方"释放所有按键"时它也把手柄放回了原位:之后重新发一遍手柄现在的样子(按着不动的也得告诉它) + input.onReleaseAll = () => { + if (this.gamepadClaimed) gamepads.resync(this); + }; input.onMouseMode = (mode) => { for (const other of this.inputs) if (other !== input && other.mode !== mode) other.setMode(mode, false); this.pushSettings(); @@ -416,6 +433,11 @@ export class RemoteSession { // 防窥模式也一样:对方重新说。要不要在握手里就告诉它(下面的连接选项) this.privacyState = null; this.privacyDetail = null; + // 手柄也是:对方说了能接才发 + this.gamepadState = null; + this.gamepadDetail = null; + this.gamepadTold = false; + this.syncGamepads(); this.attemptAt = performance.now(); let info; // 开始时的画质、要不要声音、看哪几个显示器在端到端握手里就告诉对方:它一开始就按这个建编码器, @@ -528,6 +550,7 @@ export class RemoteSession { this.sid = null; this.syncAudio(); this.syncMic(); + this.syncGamepads(); this.closedReason = reason; clearTimeout(this.retryTimer); const kind = reason?.kind; @@ -609,6 +632,7 @@ export class RemoteSession { this.state = "closed"; this.audio.disable(); this.syncMic(); + this.syncGamepads(); this.detach(); for (const name of [...this.popouts.keys()]) this.dropPopout(name); for (const p of this.opening.values()) p.close(); @@ -677,6 +701,21 @@ export class RemoteSession { // 开关跟着对方说的变:别的控制端打开 / 关掉了、没能打开,都以对方的为准 this.privacyWanted = ev.state === "on" || ev.state === "starting"; break; + case "gamepad": { + const could = this.gamepadSendable; + this.gamepadState = ev.state; + this.gamepadDetail = ev.detail; + // 刚能接(例如对方刚装好驱动):把手柄现在的样子完整地发一遍,之前没发出去的也在里面 + if (!could && this.gamepadSendable) { + if (this.notice?.kind === "gamepadUnavailable") this.notice = null; + if (this.gamepadClaimed) gamepads.resync(this); + } + this.syncGamepads(); + break; + } + case "rumble": + gamepads.rumble(this, ev.pad, ev.large, ev.small); + return; case "clipboardFiles": this.remoteFiles = { clip: ev.clip, items: ev.items }; break; @@ -726,6 +765,7 @@ export class RemoteSession { this.sid = null; this.syncAudio(); this.syncMic(); + this.syncGamepads(); this.closedReason = ev.reason; // 对方换了控制码 / 断开了所有控制端:凭证作废了(断开所有控制端时对方换了密钥), // 之后手动重连就是普通的连接请求 @@ -1233,6 +1273,52 @@ export class RemoteSession { this.foreground = v; this.syncAudio(); this.syncMic(); + this.syncGamepads(); + } + + /** 把本机的手柄插到对方电脑上(开关)。关掉时对方拔掉它们,打开时重新发一遍手柄现在的样子 */ + setGamepadEnabled(v: boolean) { + if (this.gamepadEnabled === v) return; + this.gamepadEnabled = v; + if (!v && this.gamepadState !== null) { + this.enqueue(Array.from({ length: MAX_PADS }, (_, pad) => ({ type: "gamepadRemoved", pad }) as const), true); + } + if (v && this.gamepadClaimed) gamepads.resync(this); + this.emit(); + } + + /** 本机的手柄发得过去:开关打开着,对方能接(插不上的也发:对方在用到时再试) */ + get gamepadSendable(): boolean { + return this.gamepadEnabled && (this.gamepadState === "ready" || this.gamepadState === "failed"); + } + + /** + * 手柄:正在查看、画面可以操作、连着、对方说了它能不能接时,本机的手柄交给这个会话(接不了的也要:按下按钮时说一声为什么)。 + * 不再交给它时,对方的手柄在它失去焦点时已经放回了原位(releaseAll) + */ + private syncGamepads() { + const want = this.foreground && this.interactive && this.sid !== null && !this.disposed && this.gamepadState !== null; + if (want === this.gamepadClaimed) return; + this.gamepadClaimed = want; + if (want) gamepads.claim(this); + else gamepads.release(this); + } + + /** 本机手柄的输入(GamepadHub 只在这个会话是正在操作的那个时交过来) */ + gamepadInput(events: InputEvent[], urgent: boolean) { + if (this.gamepadSendable) { + this.enqueue(events, urgent); + return; + } + // 对方接不了:第一次按下按钮时说一声为什么(不盖住别的提示) + const pressed = events.some((e) => e.type === "gamepad" && (e.buttons ?? 0) !== 0); + if (pressed && this.gamepadEnabled && this.gamepadState !== null && !this.gamepadTold) { + this.gamepadTold = true; + if (!this.notice) { + this.notice = { kind: "gamepadUnavailable", state: this.gamepadState, platform: this.hostPlatform, detail: this.gamepadDetail }; + this.emit(); + } + } } /** 把本机麦克风发给对方(第一次打开时浏览器会问能不能用麦克风) */ @@ -1338,6 +1424,7 @@ export class RemoteSession { this.interactive = v; this.input.interactive = v; if (!v) this.releaseAll(); + this.syncGamepads(); this.layout(); } diff --git a/client/src/locales/en.ts b/client/src/locales/en.ts index 0adb4d97..dd924a57 100644 --- a/client/src/locales/en.ts +++ b/client/src/locales/en.ts @@ -223,6 +223,8 @@ const en: Record = { "session.micOn": "Microphone (sending to the remote computer)", "session.privacy": "Privacy mode", "session.privacyOn": "Privacy mode (the remote monitors are blank)", + "session.gamepad": "Gamepads", + "session.gamepadOn": "Gamepads (plugged into the remote computer)", "session.mouse": "Mouse: {mode}", "session.mouseLocked": "The mouse is locked to the picture. Hold Esc to free it", "session.clickToLock": "Click the picture to lock the mouse", @@ -316,6 +318,18 @@ const en: Record = { // The remote computer is a Mac: its displays are blanked and covered, no virtual display (see client/src-tauri/src/host/virtual_display/curtain.rs) "privacy.offMac": "Blanks all of the remote Mac's displays and disables its keyboard, mouse and trackpad, so only you can see and control it. Turns off by itself after you disconnect", "privacy.startingMac": "Turning on", + "gamepad.send": "Plug gamepads into the remote computer", + "gamepad.ready": "Each gamepad connected here shows up on the remote computer as an Xbox 360 controller while you're viewing this connection. Games can make it vibrate", + "gamepad.noDriverWindows": "The remote computer needs usbip-win2 (a free, signed driver) for virtual gamepads: install it there from github.com/vadimgrn/usbip-win2/releases, no need to restart Airhand", + "gamepad.noDriverLinux": "The remote computer has neither uinput nor vhci-hcd: run sudo modprobe uinput there", + "gamepad.noPermission": "Airhand on the remote computer can't use /dev/uinput: install Steam's controller rules (steam-devices) or add the udev rule from the Airhand docs", + "gamepad.failed": "The remote computer couldn't plug in a virtual gamepad ({detail}). It tries again when you use the gamepad", + "gamepad.unsupported": "The remote computer can't take gamepads", + "gamepad.unsupportedMac": "The remote is a Mac: macOS doesn't allow virtual gamepads", + "gamepad.pads": "Gamepads connected here", + "gamepad.pad": "{n}. {name}", + "gamepad.noRumble": "(can't vibrate)", + "gamepad.note": "Gamepads go to the connection you're viewing. Buttons of Xbox, PlayStation, Switch Pro and other gamepads map to the Xbox positions", "privacy.unavailableMac": "Not available on the remote Mac: someone at that Mac has to allow Airhand in System Settings → Privacy & Security → Accessibility first (it's needed to block its keyboard and mouse)", "combo.winStart": "Start menu (Win)", @@ -359,6 +373,7 @@ const en: Record = { "notice.noOpus": "This computer can't decode Opus, so remote sound can't be played", "notice.fileError": "Couldn't transfer “{name}”: {reason}", "notice.filesUnsupported": "The remote Airhand is too old to transfer files through the clipboard", + "notice.gamepadUnavailable": "The gamepad isn't sent to the remote computer: {reason}", "fileError.notFound": "it's gone (deleted or renamed)", "fileError.denied": "permission denied", "fileError.changed": "it changed after it was copied, copy it again", diff --git a/client/src/locales/zh.ts b/client/src/locales/zh.ts index 87865583..a2eb8c5b 100644 --- a/client/src/locales/zh.ts +++ b/client/src/locales/zh.ts @@ -233,6 +233,8 @@ export default { "session.micOn": "麦克风(正在发给对方)", "session.privacy": "防窥模式", "session.privacyOn": "防窥模式(对方的显示器黑屏)", + "session.gamepad": "手柄", + "session.gamepadOn": "手柄(插在对方电脑上)", "session.mouse": "鼠标:{mode}", "session.mouseLocked": "鼠标已锁定在画面上,长按 Esc 放开", "session.clickToLock": "点击画面锁定鼠标", @@ -330,6 +332,20 @@ export default { "privacy.startingMac": "正在打开", "privacy.unavailableMac": "对方 Mac 用不了:要先在那台 Mac 的“系统设置 → 隐私与安全性 → 辅助功能”里允许 Airhand(挡住它的键盘鼠标要用到)", + // 手柄:这里接着的手柄插到对方电脑上,成为虚拟的 Xbox 360 手柄(见 lib/gamepad.ts) + "gamepad.send": "把手柄插到对方电脑上", + "gamepad.ready": "这里接着的每个手柄都会作为一个 Xbox 360 手柄插到对方电脑上(正在查看这个连接时),游戏可以让它震动", + "gamepad.noDriverWindows": "对方电脑要先装 usbip-win2(免费、有签名的驱动)才能插虚拟手柄:在那台电脑上从 github.com/vadimgrn/usbip-win2/releases 下载安装,不用重启 Airhand", + "gamepad.noDriverLinux": "对方电脑既没有 uinput 也没有 vhci-hcd:在那台电脑上运行 sudo modprobe uinput", + "gamepad.noPermission": "对方电脑上的 Airhand 不能用 /dev/uinput:装上 Steam 的手柄规则(steam-devices),或者照 Airhand 文档加一条 udev 规则", + "gamepad.failed": "对方电脑没能插上虚拟手柄({detail}),再用手柄时会重试", + "gamepad.unsupported": "对方电脑不能接手柄", + "gamepad.unsupportedMac": "对方是 Mac:macOS 不允许插虚拟手柄", + "gamepad.pads": "这里接着的手柄", + "gamepad.pad": "{n}. {name}", + "gamepad.noRumble": "(不能震动)", + "gamepad.note": "手柄只给正在查看的连接;Xbox、PlayStation、Switch Pro 等手柄的按键都按 Xbox 的位置对应", + // 快捷键 "combo.winStart": "Win 开始菜单", "combo.altTab": "Alt + Tab 切换窗口", @@ -376,6 +392,7 @@ export default { "notice.androidNoInput": "对方手机没有开启 Airhand 的“远程操作”(无障碍服务),只能看不能操作。需要手机的主人在 Airhand 的“共享本机”页里开启", "notice.fileError": "“{name}”传不了:{reason}", "notice.filesUnsupported": "对方的 Airhand 版本较旧,不能通过剪贴板传文件", + "notice.gamepadUnavailable": "手柄没有发给对方:{reason}", "fileError.notFound": "文件不在了(被删除或改了名)", "fileError.denied": "没有权限读取", "fileError.changed": "复制之后文件变了,请重新复制", diff --git a/client/tests/gamepad.test.ts b/client/tests/gamepad.test.ts new file mode 100644 index 00000000..b3ecb65b --- /dev/null +++ b/client/tests/gamepad.test.ts @@ -0,0 +1,125 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { BUTTONS, changed, GamepadHub, padEvent, readPad, STICK_STEP, type GamepadTarget } from "../src/lib/gamepad.ts"; +import type { InputEvent } from "../src/lib/api.ts"; + +/** 假的标准布局手柄:17 个按钮、4 个轴 */ +function fakePad(index: number, id = `pad ${index}`) { + const buttons = Array.from({ length: 17 }, () => ({ pressed: false, value: 0 })); + const axes = [0, 0, 0, 0]; + const effects: { large: number; small: number }[] = []; + const pad: any = { + index, id, connected: true, mapping: "standard", buttons, axes, + vibrationActuator: { + playEffect: async (_type: string, p: any) => effects.push({ large: p.strongMagnitude, small: p.weakMagnitude }), + }, + press(i: number, down = true) { buttons[i] = { pressed: down, value: down ? 1 : 0 }; }, + effects, + }; + return pad; +} + +/** 收手柄输入的假会话 */ +function target() { + const got: [InputEvent[], boolean][] = []; + const t: GamepadTarget & { got: typeof got } = { got, gamepadInput: (e, urgent) => got.push([e, urgent]) }; + return t; +} + +test("标准布局按 XInput 读:按钮的位、扳机 0-255、Y 轴反过来", () => { + const p = fakePad(0); + p.press(0); // A + p.press(5); // RB + p.press(12); // 上 + p.press(16); // 西瓜键 + p.buttons[6] = { pressed: false, value: 0.5 }; + p.buttons[7] = { pressed: true, value: 0 }; // 只报按下了:当作按到底 + p.axes.splice(0, 4, -1, -1, 1, 1); + assert.deepEqual(readPad(p), { + buttons: BUTTONS.a | BUTTONS.rightShoulder | BUTTONS.dpadUp | BUTTONS.guide, + leftTrigger: 128, + rightTrigger: 255, + leftX: -32768, + leftY: 32767, // 向上推(网页里是 -1) + rightX: 32767, + rightY: -32768, + }); + // 少了按钮、轴的手柄(不是标准布局):没有的当作没按、在正中间 + assert.deepEqual(readPad({ buttons: [{ pressed: true, value: 1 }], axes: [] }), { + buttons: BUTTONS.a, leftTrigger: 0, rightTrigger: 0, leftX: 0, leftY: 0, rightX: 0, rightY: 0, + }); +}); + +test("变了才发:摇杆的小抖动不算,回到正中间算;是 0 的字段不写", () => { + const rest = readPad(fakePad(0)); + assert.equal(changed(null, rest), true); + assert.equal(changed(rest, { ...rest, leftX: STICK_STEP - 1 }), true, "离开正中间"); + const off = { ...rest, leftX: 1000 }; + assert.equal(changed(off, { ...off, leftX: 1000 + STICK_STEP - 1 }), false); + assert.equal(changed(off, { ...off, leftX: 1000 + STICK_STEP }), true); + assert.equal(changed(off, { ...off, leftTrigger: 1 }), true); + assert.equal(changed(off, { ...off, buttons: BUTTONS.b }), true); + assert.deepEqual(padEvent(2, { ...rest, buttons: BUTTONS.x, rightY: -5 }), { type: "gamepad", pad: 2, buttons: BUTTONS.x, rightY: -5 }); +}); + +test("交给正在操作的会话:编号按接上的先后,变了才发,按钮马上发;拔掉了告诉对方;换了会话重新发完整的", () => { + const pads: any[] = [fakePad(3), fakePad(0)]; + const hub = new GamepadHub({ getGamepads: () => pads }); + const a = target(); + hub.claim(a); + // 一开始:空着的编号是"拔掉了"(对方可能还以为插着),接着的手柄发完整的状态 + assert.deepEqual(a.got[0], [[{ type: "gamepadRemoved", pad: 2 }, { type: "gamepadRemoved", pad: 3 }], true]); + assert.deepEqual(a.got[1], [[{ type: "gamepad", pad: 0 }, { type: "gamepad", pad: 1 }], true]); + assert.deepEqual(hub.pads.map((p) => [p.pad, p.name]), [[0, "pad 3"], [1, "pad 0"]]); + hub.poll(); + assert.equal(a.got.length, 2, "没变不发"); + // 只动了摇杆:不急 + pads[0].axes[0] = 0.5; + hub.poll(); + assert.deepEqual(a.got[2], [[{ type: "gamepad", pad: 0, leftX: 16384 }], false]); + // 按钮:马上发 + pads[1].press(1); + hub.poll(); + assert.deepEqual(a.got[3], [[{ type: "gamepad", pad: 1, buttons: BUTTONS.b }], true]); + // 拔掉了:告诉对方;再接上一个,用空出来的编号 + pads.splice(0, 1); + hub.poll(); + assert.deepEqual(a.got[4], [[{ type: "gamepadRemoved", pad: 0 }], true]); + pads.push(fakePad(5)); + hub.poll(); + assert.deepEqual(a.got[5], [[{ type: "gamepad", pad: 0 }], true]); + // 换了会话:新的先收到完整的;旧的不再收到 + const b = target(); + hub.claim(b); + assert.deepEqual(b.got[0], [[{ type: "gamepadRemoved", pad: 2 }, { type: "gamepadRemoved", pad: 3 }], true]); + assert.deepEqual(b.got[1], [[{ type: "gamepad", pad: 0 }, { type: "gamepad", pad: 1, buttons: BUTTONS.b }], true]); + pads[0].press(0); + hub.poll(); + assert.equal(a.got.length, 6); + // 对方放回了原位:重新发 + hub.resync(b); + hub.poll(); + assert.deepEqual(b.got.at(-1), [[{ type: "gamepad", pad: 0 }, { type: "gamepad", pad: 1, buttons: BUTTONS.a | BUTTONS.b }], true]); + hub.release(b); + pads[0].press(2); + hub.poll(); + assert.equal(b.got.length, 4, "放开之后不再收"); +}); + +test("震动:只认正在操作的会话的;震着时定时重新放;换了会话、拔掉时停下", () => { + const pad = fakePad(0); + const hub = new GamepadHub({ getGamepads: () => [pad] }); + const a = target(); + const b = target(); + hub.claim(a); + hub.rumble(b, 0, 255, 0); + assert.deepEqual(pad.effects, [], "不是在操作的会话"); + hub.rumble(a, 0, 255, 51); + assert.deepEqual(pad.effects, [{ large: 1, small: 0.2 }]); + hub.rumble(a, 0, 0, 0); + assert.deepEqual(pad.effects.at(-1), { large: 0, small: 0 }); + hub.rumble(a, 0, 128, 0); + hub.claim(b); + assert.deepEqual(pad.effects.at(-1), { large: 0, small: 0 }, "换了会话:停下"); + hub.release(b); +}); diff --git a/client/tests/protocol-contract.ts b/client/tests/protocol-contract.ts index f16f18d0..01be52a4 100644 --- a/client/tests/protocol-contract.ts +++ b/client/tests/protocol-contract.ts @@ -163,6 +163,21 @@ export const contract = { { "action": "back", "type": "system" + }, + { + "buttons": 4097, + "leftTrigger": 0, + "leftX": -32768, + "leftY": 32767, + "pad": 1, + "rightTrigger": 255, + "rightX": 0, + "rightY": -1, + "type": "gamepad" + }, + { + "pad": 1, + "type": "gamepadRemoved" } ] } satisfies { input: InputEvent[]; commands: Command[]; connectOptions: ConnectOptions }; diff --git a/client/tests/protocol.test.ts b/client/tests/protocol.test.ts index 70f080b9..cdd7b6fb 100644 --- a/client/tests/protocol.test.ts +++ b/client/tests/protocol.test.ts @@ -4,6 +4,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import fs from "node:fs"; import * as media from "../src/lib/media.ts"; +import { padEvent } from "../src/lib/gamepad.ts"; import { contract } from "./protocol-contract.ts"; const fixture = JSON.parse( @@ -63,7 +64,14 @@ test("输入事件、命令和连接选项的 JSON 形状与 Rust 一致", () => const events = contract.input; const commands = contract.commands; const kinds = events.map((e) => e.type); - assert.deepEqual(kinds, ["mouseMove", "mouseDelta", "mouseButton", "wheel", "key", "text", "releaseAll", "touch", "system"]); + assert.deepEqual(kinds, [ + "mouseMove", "mouseDelta", "mouseButton", "wheel", "key", "text", "releaseAll", "touch", "system", "gamepad", "gamepadRemoved", + ]); + // 手柄:gamepad.ts 拼出来的(是 0 的字段不写)补上 0 之后和 Rust 的一样 + const pad = events.find((e) => e.type === "gamepad"); + const sent = padEvent(1, { buttons: 0x1001, leftTrigger: 0, rightTrigger: 255, leftX: -32768, leftY: 32767, rightX: 0, rightY: -1 }); + assert.deepEqual({ buttons: 0, leftTrigger: 0, rightTrigger: 0, leftX: 0, leftY: 0, rightX: 0, rightY: 0, ...sent }, pad); + assert.deepEqual(events.find((e) => e.type === "gamepadRemoved"), { type: "gamepadRemoved", pad: 1 }); const delta = { type: "mouseDelta", dx: -3, dy: 7 }; assert.deepEqual(events[1], delta); const button = { type: "mouseButton", button: "right", down: true }; diff --git a/client/tests/session.test.ts b/client/tests/session.test.ts index 3d4290d7..5bfe9c16 100644 --- a/client/tests/session.test.ts +++ b/client/tests/session.test.ts @@ -55,6 +55,14 @@ function sessionHarness(connect?: (code: string, resume: any, opts: any) => Prom fitSize, stricter, viewMaxShort, renderPlan, media, hitTest, layoutTiles, placeDisplays, RemoteInput, devicePixelRatio: 1, codecUsable: () => true, bestCodec: () => "h264", store: { get: () => storeState }, + // 手柄:记下交给了哪个会话、震动、要重发 + MAX_PADS: 4, + gamepads: { + claim: () => calls.push(["claim"]), + release: () => calls.push(["release"]), + resync: () => calls.push(["resync"]), + rumble: (_s: any, pad: number, large: number, small: number) => calls.push(["rumble", pad, large, small]), + }, toProblem: (e: any) => e, api: { connect: (c: any, o: any, _view: any, onEvent: any) => { @@ -617,6 +625,62 @@ test("光标画在画面里(对方拖动、缩放窗口):默认照样显 assert.deepEqual(hidden, [false, false, false, false], "一直没有改发相对移动"); }); +test("手柄:对方说了能不能接、正在查看并可以操作时才交给这个会话;能接时发,接不了时按下按钮说一声为什么;震动交给手柄", () => { + const h = sessionHarness(); + const s = h.session; + const sent: any[] = []; + Object.assign(s, { + sid: 7, foreground: false, interactive: false, gamepadState: null, gamepadDetail: null, gamepadEnabled: true, + gamepadClaimed: false, gamepadTold: false, notice: null, hostPlatform: "windows", + input: { enqueue: (events: any[], urgent: boolean) => sent.push([plain(events), urgent]), releaseAll() {}, interactive: false }, + layout() {}, + }); + const hub = () => h.calls.filter((c) => Array.isArray(c) && ["claim", "release", "resync"].includes(c[0])).map((c) => c[0]); + const press = [{ type: "gamepad", pad: 0, buttons: 0x1000 }]; + + // 对方还没说(手机、版本旧的不会说):就算在前台也不要手柄 + s.setForeground(true); + s.setInteractive(true); + assert.deepEqual(hub(), []); + // 对方缺驱动:交给这个会话(按下按钮时要说一声),但不发 + s.onEvent({ type: "gamepad", state: "noDriver", detail: null }); + assert.deepEqual(hub(), ["claim"]); + s.gamepadInput([{ type: "gamepad", pad: 0, leftX: 900 }], false); + assert.equal(s.notice, null, "只动了摇杆:不说"); + s.gamepadInput(press, true); + assert.deepEqual(plain(s.notice), { kind: "gamepadUnavailable", state: "noDriver", platform: "windows", detail: null }); + s.notice = null; + s.gamepadInput(press, true); + assert.equal(s.notice, null, "一次连接只说一次"); + assert.deepEqual(sent, []); + // 对方装好了驱动:重发手柄现在的样子,之后照常发(按钮马上发) + s.onEvent({ type: "gamepad", state: "ready", detail: null }); + assert.deepEqual(hub(), ["claim", "resync"]); + s.gamepadInput(press, true); + assert.deepEqual(sent, [[press, true]]); + // 插不上:照样发(对方在用到时重试) + s.onEvent({ type: "gamepad", state: "failed", detail: "timeout" }); + s.gamepadInput(press, true); + assert.equal(sent.length, 2); + // 震动交给手柄 + s.onEvent({ type: "rumble", pad: 1, large: 200, small: 10 }); + assert.deepEqual(h.calls.at(-1), ["rumble", 1, 200, 10]); + // 关掉开关:对方拔掉所有手柄,之后不发;打开时重发现在的样子 + s.setGamepadEnabled(false); + assert.deepEqual(sent.at(-1), [[0, 1, 2, 3].map((pad) => ({ type: "gamepadRemoved", pad })), true]); + s.gamepadInput(press, true); + assert.equal(sent.length, 3); + s.setGamepadEnabled(true); + assert.deepEqual(hub(), ["claim", "resync", "resync"]); + // 切走、断开:不再交给它 + s.setInteractive(false); + assert.deepEqual(hub(), ["claim", "resync", "resync", "release"]); + s.setInteractive(true); + s.sid = null; + s.syncGamepads(); + assert.deepEqual(hub(), ["claim", "resync", "resync", "release", "claim", "release"]); +}); + test("麦克风:对方说了能接、开关打开、正在查看时才告诉对方打开;对方 ready 才采集;切走、断开、本机不允许时关掉", async () => { const h = sessionHarness(); const s = h.session; diff --git a/crates/airhand-link/src/controller/mod.rs b/crates/airhand-link/src/controller/mod.rs index bd61f69e..abfe41f9 100644 --- a/crates/airhand-link/src/controller/mod.rs +++ b/crates/airhand-link/src/controller/mod.rs @@ -53,6 +53,13 @@ //! 界面打开麦克风([`Command::Mic`])之后自己采集、编码,把打好的声音包交给 [`ControllerService::mic`]: //! 这里带上之前几包的副本、加密,发成声音数据报(走画面来的那条路)。界面不知道有冗余、有几条路。 //! +//! # 手柄 +//! +//! 被控端用 [`SessionEvent::Gamepad`] 说明它能不能接手柄(见 `airhand_proto::session` 的"手柄"),能接时界面把本机 +//! 手柄的状态当作输入发过去(`{"type":"gamepad","pad":0,...}`、拔掉时 `gamepadRemoved`,和键盘鼠标在同一个 +//! [`Command::Input`] 里),游戏让手柄震动时收到 [`SessionEvent::Rumble`]。同一个手柄只有摇杆、扳机变了的相邻几个状态 +//! 在排队时合并(见 [`queue`])。 +//! //! # 防窥模式 //! //! 被控端用 [`SessionEvent::Privacy`] 说明它能不能开、开着没有(见 `airhand_proto::session` 的"防窥模式"), diff --git a/crates/airhand-link/src/controller/queue.rs b/crates/airhand-link/src/controller/queue.rs index 995028ea..382b4071 100644 --- a/crates/airhand-link/src/controller/queue.rs +++ b/crates/airhand-link/src/controller/queue.rs @@ -3,7 +3,7 @@ //! * 只关心最新值的画质设置不排队:它占一个槽位,只留最新的一个,写任务**先发它**,再按顺序发排着队的 //! 输入和其它命令。Ping、画面确认不在这里:它们是控制数据报(见 `super::session::Feedback`),不排在输入后面; //! * 连续的绝对移动只留最后一个,连续的相对移动加起来;移动只和紧挨着的移动合并, -//! 不会越过点击、按键(松开按键不会被合并掉); +//! 不会越过点击、按键(松开按键不会被合并掉)。手柄也一样:同一个手柄连续几个按钮没变的状态只留最后一个; //! * 排着的输入太旧了(网络卡了一阵子,[`INPUT_MAX_AGE`]),或者队列满了:丢掉排着的输入、 //! 补发一个"释放所有按键"(丢掉的里面可能有松开按键),会话照常继续——不在网络恢复时把一串过时的远程操作补发出去, //! 也不因为网络卡了一下就断开重连。真正失联由会话的超时处理。 @@ -40,6 +40,8 @@ enum Kind { Move, /// 只有相对移动:加起来 Delta, + /// 只有第几个手柄、按着哪些按钮的状态:按钮一样的只留最后一个(只是摇杆、扳机动了) + Pad(u8, u16), /// 不是输入的命令(切换显示器、请求关键帧、剪贴板……):不会过时,不丢 Command, } @@ -215,6 +217,7 @@ impl Sender { ControllerMsg::Input { t, events } => match events[..] { [InputEvent::MouseMove { .. }] => (Kind::Move, (0, 0), *t), [InputEvent::MouseDelta { dx, dy }] => (Kind::Delta, (dx, dy), *t), + [InputEvent::Gamepad { pad, buttons, .. }] => (Kind::Pad(pad, buttons), (0, 0), *t), _ => (Kind::Input, (0, 0), *t), }, _ => (Kind::Command, (0, 0), 0), @@ -237,8 +240,10 @@ impl Sender { at: Instant::now(), t, }; - // 移动只和紧挨着的移动合并(队尾只会是输入或命令,确认这类状态不在队列里) - if matches!(kind, Kind::Move | Kind::Delta) && m.back().is_some_and(|i| i.meta.kind == kind) + // 移动只和紧挨着的移动合并(队尾只会是输入或命令,确认这类状态不在队列里);手柄只和紧挨着的、 + // 同一个手柄按钮一样的状态合并 + if matches!(kind, Kind::Move | Kind::Delta | Kind::Pad(..)) + && m.back().is_some_and(|i| i.meta.kind == kind) { let old = m.pop_back().expect("checked above").meta; if kind == Kind::Delta { @@ -517,6 +522,40 @@ mod tests { assert_eq!(queued(&tx).len(), 5); } + /// 手柄:网络慢、排着的时候,只有摇杆、扳机变了的状态只留最新的;按钮变了的、别的手柄的不合并 + #[test] + fn gamepad_states_coalesce_until_a_button_changes() { + let (tx, _rx) = channel(); + let pad = |pad, buttons, left_x| { + input(vec![InputEvent::Gamepad { + pad, + buttons, + left_trigger: 0, + right_trigger: 0, + left_x, + left_y: 0, + right_x: 0, + right_y: 0, + }]) + }; + for x in 0..100 { + tx.send(pad(0, 0, x)).unwrap(); + } + tx.send(pad(0, 0x1000, 100)).unwrap(); + tx.send(pad(0, 0, 101)).unwrap(); + tx.send(pad(1, 0, 102)).unwrap(); + tx.send(pad(0, 0, 103)).unwrap(); + let x = |m: &ControllerMsg| match events(m) { + [InputEvent::Gamepad { left_x, .. }] => *left_x, + other => panic!("{other:?}"), + }; + let q = queued(&tx); + assert_eq!( + q.iter().map(x).collect::>(), + [99, 100, 101, 102, 103] + ); + } + /// 输入过时了:丢掉排着的输入、补一个"释放所有按键",其它命令照发,会话继续 #[tokio::test] async fn stale_input_is_dropped_and_keys_released() { diff --git a/crates/airhand-link/src/controller/session.rs b/crates/airhand-link/src/controller/session.rs index 96eb164a..af42116c 100644 --- a/crates/airhand-link/src/controller/session.rs +++ b/crates/airhand-link/src/controller/session.rs @@ -17,8 +17,9 @@ use crate::secure::Sealer; use crate::transport::write_lane; use airhand_proto::media::{self, VideoHeader}; use airhand_proto::session::{ - ByeReason, Codec, ControllerDatagram, ControllerMsg, DirectOffer, DisplayInfo, HostMsg, - MicState, Notice, Platform, PrivacyState, REPORT_EVERY, SystemAction, VideoReport, + ByeReason, Codec, ControllerDatagram, ControllerMsg, DirectOffer, DisplayInfo, GamepadSupport, + HostMsg, MAX_GAMEPADS, MicState, Notice, Platform, PrivacyState, REPORT_EVERY, SystemAction, + VideoReport, }; use airhand_proto::{MAX_STREAMS, datagram}; use anyhow::Result; @@ -304,6 +305,14 @@ pub enum SessionEvent { state: PrivacyState, detail: Option, }, + /// 被控端能不能接手柄(见 `airhand_proto::session` 的"手柄"):会话开始时一次,之后有变化再来。 + /// 被控端不能接(手机)时不会有,界面也就不发手柄的输入。`detail`:出错时给排查问题用的技术信息(英文) + Gamepad { + state: GamepadSupport, + detail: Option, + }, + /// 第 `pad` 个手柄该怎么震(大马达、小马达,0-255),直到下一次;都是 0 是停下 + Rumble { pad: u8, large: u8, small: u8 }, /// `retry=false` 表示对方主动断开,不应自动重连 Closed { reason: Problem, retry: bool }, } @@ -799,6 +808,21 @@ pub(super) async fn run( }; let _ = out.event(SessionEvent::Privacy { state, detail }); } + HostMsg::Gamepad { state, detail } => { + // 对方版本新增的状态:不知道能不能接,当作不支持(界面不发手柄的输入) + let state = if state.is_known() { + state + } else { + GamepadSupport::Unsupported + }; + let _ = out.event(SessionEvent::Gamepad { state, detail }); + } + HostMsg::Rumble { pad, large, small } if pad < MAX_GAMEPADS => { + let _ = out.event(SessionEvent::Rumble { pad, large, small }); + } + HostMsg::Rumble { pad, .. } => { + debug!(sid, pad, "ignoring rumble for an unknown pad") + } } } #[allow(unreachable_code)] diff --git a/crates/airhand-link/src/host/queue.rs b/crates/airhand-link/src/host/queue.rs index 2b526f37..d172a065 100644 --- a/crates/airhand-link/src/host/queue.rs +++ b/crates/airhand-link/src/host/queue.rs @@ -2,7 +2,7 @@ //! //! * **走哪条通道由消息决定**([`HostMsg::lane`]):发的一方只管 [`Outbox::send`],不用自己挑控制通道还是大块通道。 //! 大的消息(剪贴板、光标形状)在大块通道上排队,挡不住控制消息; -//! * **只关心最新值的状态不排队**:显示器列表、光标状态(控制通道)各占一个槽位、只留最新的一个, +//! * **只关心最新值的状态不排队**:显示器列表、光标状态、每个手柄的震动(控制通道)各占一个槽位、只留最新的一个, //! 写任务先发它们,再按顺序发排着队的; //! * 其它消息按顺序排队,有上限。满了怎么办由发的一方决定([`SendError::Full`]):控制消息排满了说明对方早就不收了, //! 会话结束;剪贴板丢掉这一次;光标图像下一轮再发那时最新的。 @@ -15,7 +15,7 @@ use std::sync::Arc; use airhand_proto::SessionLane; use airhand_proto::framing; use airhand_proto::handshake::SEAL_OVERHEAD; -use airhand_proto::session::HostMsg; +use airhand_proto::session::{HostMsg, MAX_GAMEPADS}; use bytes::Bytes; use crate::queue::{Item, Limit, Mailbox}; @@ -41,10 +41,11 @@ const LIMITS: [Limit; 2] = [ bytes: BULK_BYTES, }, ]; -/// 控制通道上只留最新值的槽位(写任务按这个先后发) +/// 控制通道上只留最新值的槽位(写任务按这个先后发):显示器列表、光标状态、第 `i` 个手柄的震动是 `RUMBLE + i` const DISPLAYS: usize = 0; const CURSOR: usize = 1; -const SLOTS: usize = 2; +const RUMBLE: usize = 2; +const SLOTS: usize = RUMBLE + MAX_GAMEPADS as usize; /// 一条消息在队列里怎么放 #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -67,15 +68,19 @@ impl Place { HostMsg::Displays { .. } => Place::Latest(DISPLAYS), HostMsg::Hello(_) => queued(Some(DISPLAYS)), HostMsg::Cursor { .. } => Place::Latest(CURSOR), + // 震动:游戏一秒钟可能改几十次,控制端只要照着最新的震 + HostMsg::Rumble { pad, .. } if *pad < MAX_GAMEPADS => Place::Latest(RUMBLE + *pad as usize), + HostMsg::Rumble { .. } => queued(None), HostMsg::Notice(_) | HostMsg::Encoder(_) | HostMsg::CursorImage { .. } | HostMsg::Clipboard { .. } | HostMsg::Bye(_) | HostMsg::Direct(_) - // 麦克风、防窥模式的状态很少变,跟在 Hello 后面按顺序发 + // 麦克风、防窥模式、手柄的状态很少变,跟在 Hello 后面按顺序发 | HostMsg::Mic { .. } | HostMsg::Privacy { .. } + | HostMsg::Gamepad { .. } | HostMsg::Files(_) => queued(None), } } @@ -438,6 +443,50 @@ mod tests { assert_eq!(shown(&out[0]), "fresh"); } + /// 震动每个手柄只留最新的一条,手柄之间互不覆盖;控制通道排满了也放得进 + #[test] + fn rumble_keeps_the_latest_per_pad() { + let (tx, mut control, _bulk) = channel(); + let rumble = |pad, large| HostMsg::Rumble { + pad, + large, + small: 0, + }; + for _ in 0..CONTROL_MESSAGES { + tx.send(¬ice()).unwrap(); + } + for large in 0..100 { + tx.send(&rumble(0, large)).unwrap(); + tx.send(&rumble(3, large + 1)).unwrap(); + } + let out = drain(&mut control); + assert!(matches!( + out[0], + HostMsg::Rumble { + pad: 0, + large: 99, + .. + } + )); + assert!(matches!( + out[1], + HostMsg::Rumble { + pad: 3, + large: 100, + .. + } + )); + assert_eq!(out.len(), CONTROL_MESSAGES + 2); + // 序号不对的(不会有)按顺序排队,不占别的槽位 + assert_eq!( + Place::of(&rumble(MAX_GAMEPADS, 1)), + Place::Queued { + lane: CONTROL, + before: None + } + ); + } + /// 光标状态只留最新的,走控制通道:大块通道排满了(剪贴板、光标图像)也挡不住它 #[test] fn cursor_state_bypasses_a_full_bulk_lane() { diff --git a/crates/airhand-link/tests/protocol.json b/crates/airhand-link/tests/protocol.json index 5b303993..f0028c93 100644 --- a/crates/airhand-link/tests/protocol.json +++ b/crates/airhand-link/tests/protocol.json @@ -162,6 +162,21 @@ { "action": "back", "type": "system" + }, + { + "buttons": 4097, + "leftTrigger": 0, + "leftX": -32768, + "leftY": 32767, + "pad": 1, + "rightTrigger": 255, + "rightX": 0, + "rightY": -1, + "type": "gamepad" + }, + { + "pad": 1, + "type": "gamepadRemoved" } ], "media": [ diff --git a/crates/airhand-link/tests/protocol.rs b/crates/airhand-link/tests/protocol.rs index 58e01989..fc387fa6 100644 --- a/crates/airhand-link/tests/protocol.rs +++ b/crates/airhand-link/tests/protocol.rs @@ -56,6 +56,18 @@ fn inputs() -> Vec { InputEvent::System { action: SystemAction::Back, }, + // 手柄的状态:按钮是 XInput 的位(A = 0x1000),Y 轴向上为正 + InputEvent::Gamepad { + pad: 1, + buttons: 0x1000 | 0x0001, + left_trigger: 0, + right_trigger: 255, + left_x: -32768, + left_y: 32767, + right_x: 0, + right_y: -1, + }, + InputEvent::GamepadRemoved { pad: 1 }, ] } diff --git a/crates/airhand-proto/src/session.rs b/crates/airhand-proto/src/session.rs index 910056d9..b18e99c0 100644 --- a/crates/airhand-proto/src/session.rs +++ b/crates/airhand-proto/src/session.rs @@ -101,6 +101,24 @@ //! 被控端只在打开着的时候接(同一时刻只给一个控制端,后来的是 [`MicState::Busy`]); //! * 被控端没有声音放进去的时候虚拟麦克风里是静音。 //! +//! # 手柄 +//! +//! 控制端接着的手柄(游戏手柄、手机的外接手柄)可以插到被控端上:被控端为每个手柄插上一个虚拟的有线 +//! Xbox 360 手柄(Windows 经 usbip-win2,Linux 经 vhci-hcd 或 uinput,见 airhand-dock),游戏看到的就是一个真手柄 +//! (XInput、DirectInput、SDL、Steam、evdev……);游戏让它震动,控制端的手柄跟着震。 +//! +//! * 被控端在 [`HostMsg::Hello`] 之后发 [`HostMsg::Gamepad`],说明它现在能不能接([`GamepadSupport`]:平台不支持、 +//! 缺驱动、没有权限、能接、出错了),之后有变化再发。不发的被控端(手机)不能接,控制端也就不发手柄的输入; +//! * 手柄的状态是输入([`InputEvent::Gamepad`]):和键盘鼠标一样走控制通道、成批发,过时了换成"释放所有按键" +//! (被控端把每个虚拟手柄放回原位,不拔掉)。每次发的是这个手柄所有按钮、扳机、摇杆现在的样子(同 XInput 的 +//! `XINPUT_GAMEPAD`),不是变化:中间的合并掉了,被控端照样知道现在怎么样; +//! * 被控端第一次收到第 `pad` 个手柄时插上虚拟手柄;控制端的手柄拔掉了发 [`InputEvent::GamepadRemoved`], +//! 被控端随之拔掉。会话结束时全部拔掉;会话是断掉的(不是控制端断开的)就等一会儿,同一个控制端重连上来接着用: +//! 网络抖一下,游戏不会弹出"手柄已断开"; +//! * 合并:只有摇杆、扳机变了的相邻几条只留最后一条;按钮变了的不合并(按下又松开不会被合并掉); +//! * 震动([`HostMsg::Rumble`])是被控端发给控制端的状态,每个手柄只留最新的一条,控制端照着震,直到下一条; +//! * 每个控制端插的是自己的虚拟手柄:几个控制端同时连着时各是各的。 +//! //! # 多屏 //! //! 被控端有好几个显示器时,控制端可以同时看、同时操作其中几个(默认只看一个)。每个显示器是一**路**画面: @@ -229,6 +247,65 @@ pub enum HostMsg { #[n(1)] detail: Option, }, + /// 被控端现在能不能接手柄(见模块说明的"手柄")。Hello 之后发一次,之后有变化再发;不发的被控端不能接。 + /// `detail`:出错时给排查问题用的技术信息(英文,同 [`Notice::CaptureFailed`]) + #[n(15)] + Gamepad { + #[n(0)] + state: GamepadSupport, + #[n(1)] + detail: Option, + }, + /// 第 `pad` 个手柄的震动:大马达(左,低频)、小马达(右,高频),0-255。照着震,直到下一条;都是 0 是停下。 + /// 走控制通道,每个手柄只留最新值 + #[n(16)] + Rumble { + #[n(0)] + pad: u8, + #[n(1)] + large: u8, + #[n(2)] + small: u8, + }, +} + +open_enum! { + /// 被控端能不能接手柄(见模块说明的"手柄")。不认识的值(对方版本新增的)控制端当作不支持 + pub enum GamepadSupport { + /// 这台被控端的平台不支持(例如 macOS) + Unsupported = 0 => "unsupported", + /// 缺驱动:Windows 没有装 usbip-win2;Linux 既没有 vhci-hcd 也没有 uinput + NoDriver = 1 => "noDriver", + /// 没有权限:Linux 上 Airhand 不能用 `/dev/uinput`(也不是 root,用不了 vhci-hcd) + NoPermission = 2 => "noPermission", + /// 能接 + Ready = 3 => "ready", + /// 插不上(detail 给出原因),下次用到手柄时被控端再试 + Failed = 4 => "failed", + } +} + +/// 控制端最多同时插这么多个手柄(XInput 只有 4 个位置) +pub const MAX_GAMEPADS: u8 = 4; + +/// 手柄的按钮:XInput 的 `XINPUT_GAMEPAD_*` 位([`InputEvent::Gamepad::buttons`]) +pub mod gamepad_buttons { + pub const DPAD_UP: u16 = 0x0001; + pub const DPAD_DOWN: u16 = 0x0002; + pub const DPAD_LEFT: u16 = 0x0004; + pub const DPAD_RIGHT: u16 = 0x0008; + pub const START: u16 = 0x0010; + pub const BACK: u16 = 0x0020; + pub const LEFT_THUMB: u16 = 0x0040; + pub const RIGHT_THUMB: u16 = 0x0080; + pub const LEFT_SHOULDER: u16 = 0x0100; + pub const RIGHT_SHOULDER: u16 = 0x0200; + /// 西瓜键(Xbox 键、PS 键、主页键) + pub const GUIDE: u16 = 0x0400; + pub const A: u16 = 0x1000; + pub const B: u16 = 0x2000; + pub const X: u16 = 0x4000; + pub const Y: u16 = 0x8000; } open_enum! { @@ -304,7 +381,9 @@ impl HostMsg { | HostMsg::Bye(_) | HostMsg::Direct(_) | HostMsg::Mic { .. } - | HostMsg::Privacy { .. } => SessionLane::Control, + | HostMsg::Privacy { .. } + | HostMsg::Gamepad { .. } + | HostMsg::Rumble { .. } => SessionLane::Control, } } } @@ -965,11 +1044,46 @@ pub enum InputEvent { #[n(0)] action: SystemAction, }, + /// 第 `pad` 个手柄(小于 [`MAX_GAMEPADS`])现在的样子,同 XInput 的 `XINPUT_GAMEPAD`(见模块说明的"手柄"): + /// 按钮是 [`gamepad_buttons`] 的位,扳机 0-255,摇杆 -32768..=32767、Y 轴向上为正。 + /// 只发给说了能接手柄([`HostMsg::Gamepad`])的被控端。界面的 JSON 里是 0 的可以不写 + #[n(9)] + Gamepad { + #[n(0)] + pad: u8, + #[n(1)] + #[serde(default)] + buttons: u16, + #[n(2)] + #[serde(default)] + left_trigger: u8, + #[n(3)] + #[serde(default)] + right_trigger: u8, + #[n(4)] + #[serde(default)] + left_x: i16, + #[n(5)] + #[serde(default)] + left_y: i16, + #[n(6)] + #[serde(default)] + right_x: i16, + #[n(7)] + #[serde(default)] + right_y: i16, + }, + /// 第 `pad` 个手柄拔掉了:被控端拔掉对应的虚拟手柄 + #[n(10)] + GamepadRemoved { + #[n(0)] + pad: u8, + }, } impl InputEvent { - /// 把一批输入里相邻的鼠标移动合并:绝对移动只留最后一个,相对移动相加。 - /// 按键、点击的先后顺序不变(移动不会越过点击) + /// 把一批输入里相邻的鼠标移动合并:绝对移动只留最后一个,相对移动相加;同一个手柄相邻的、按钮没变的状态 + /// 只留最后一个(见模块说明的"手柄")。按键、点击、按钮的先后顺序不变(移动不会越过点击) pub fn coalesce(events: &mut Vec) { let mut out: Vec = Vec::with_capacity(events.len()); for e in events.drain(..) { @@ -991,21 +1105,37 @@ impl InputEvent { *dx = dx.saturating_add(ndx); *dy = dy.saturating_add(ndy); } + (Some(last), e) if last.same_gamepad_buttons(&e) => *last = e, (_, e) => out.push(e), } } *events = out; } - /// 事件里的枚举值都认识(对方版本新增的按钮、触摸阶段、系统操作不认识)。不认识的事件被控端不执行 + /// 事件里的枚举值都认识(对方版本新增的按钮、触摸阶段、系统操作不认识),手柄的序号在范围里。 + /// 不认识的事件被控端不执行 pub fn understood(&self) -> bool { match self { InputEvent::MouseButton { button, .. } => button.is_known(), InputEvent::Touch { phase, .. } => phase.is_known(), InputEvent::System { action } => action.is_known(), + InputEvent::Gamepad { pad, .. } | InputEvent::GamepadRemoved { pad } => { + *pad < MAX_GAMEPADS + } _ => true, } } + + /// 同一个手柄、按钮一样的两个状态(只有摇杆、扳机不一样):后一个可以取代前一个 + pub fn same_gamepad_buttons(&self, next: &InputEvent) -> bool { + matches!( + (self, next), + ( + InputEvent::Gamepad { pad, buttons, .. }, + InputEvent::Gamepad { pad: p, buttons: b, .. }, + ) if pad == p && buttons == b + ) + } } #[cfg(test)] @@ -1050,6 +1180,115 @@ mod tests { ); } + /// 手柄:同一个手柄只有摇杆、扳机变了的相邻状态只留最后一个;按钮变了、换了手柄的不合并;序号超出范围的不执行 + #[test] + fn gamepads() { + let pad = |pad, buttons, left_x| InputEvent::Gamepad { + pad, + buttons, + left_trigger: 0, + right_trigger: 0, + left_x, + left_y: 0, + right_x: 0, + right_y: 0, + }; + let mut v = vec![ + pad(0, 0, 1), + pad(0, 0, 2), + pad(0, gamepad_buttons::A, 3), + pad(0, gamepad_buttons::A, 4), + pad(1, gamepad_buttons::A, 5), + pad(0, 0, 6), + InputEvent::GamepadRemoved { pad: 1 }, + pad(0, 0, 7), + ]; + InputEvent::coalesce(&mut v); + assert_eq!( + v, + [ + pad(0, 0, 2), + pad(0, gamepad_buttons::A, 4), + pad(1, gamepad_buttons::A, 5), + pad(0, 0, 6), + InputEvent::GamepadRemoved { pad: 1 }, + pad(0, 0, 7), + ] + ); + assert!(pad(MAX_GAMEPADS - 1, 0, 0).understood()); + assert!(!pad(MAX_GAMEPADS, 0, 0).understood()); + assert!(!InputEvent::GamepadRemoved { pad: MAX_GAMEPADS }.understood()); + + // CBOR:同一个状态进出一样;状态、震动走控制通道 + let full = InputEvent::Gamepad { + pad: 3, + buttons: 0xF7FF, + left_trigger: 255, + right_trigger: 1, + left_x: i16::MIN, + left_y: i16::MAX, + right_x: -2, + right_y: 3, + }; + let back: InputEvent = minicbor::decode(&minicbor::to_vec(&full).unwrap()).unwrap(); + assert_eq!(back, full); + let state = HostMsg::Gamepad { + state: GamepadSupport::Unknown(9), + detail: None, + }; + let back: HostMsg = minicbor::decode(&minicbor::to_vec(&state).unwrap()).unwrap(); + assert!(matches!( + back, + HostMsg::Gamepad { + state: GamepadSupport::Unknown(9), + detail: None + } + )); + let rumble = HostMsg::Rumble { + pad: 1, + large: 200, + small: 0, + }; + let back: HostMsg = minicbor::decode(&minicbor::to_vec(&rumble).unwrap()).unwrap(); + assert!(matches!( + back, + HostMsg::Rumble { + pad: 1, + large: 200, + small: 0 + } + )); + for m in [state, rumble] { + assert_eq!(m.lane(), SessionLane::Control); + } + + // 界面的 JSON:是 0 的可以不写 + assert_eq!( + serde_json::from_value::( + serde_json::json!({ "type": "gamepad", "pad": 1, "buttons": 4096, "leftX": -5 }) + ) + .unwrap(), + InputEvent::Gamepad { + pad: 1, + buttons: gamepad_buttons::A, + left_trigger: 0, + right_trigger: 0, + left_x: -5, + left_y: 0, + right_x: 0, + right_y: 0, + } + ); + assert_eq!( + serde_json::to_value(InputEvent::GamepadRemoved { pad: 2 }).unwrap(), + serde_json::json!({ "type": "gamepadRemoved", "pad": 2 }) + ); + assert_eq!( + serde_json::to_value([GamepadSupport::NoDriver, GamepadSupport::NoPermission]).unwrap(), + serde_json::json!(["noDriver", "noPermission"]) + ); + } + #[test] fn codec_codes_match_the_media_header() { for (c, id) in [(Codec::H264, 0), (Codec::H265, 1), (Codec::AV1, 2)] { diff --git a/crates/airhand-proto/tests/v10.rs b/crates/airhand-proto/tests/v10.rs index 0c22d8d7..f919e934 100644 --- a/crates/airhand-proto/tests/v10.rs +++ b/crates/airhand-proto/tests/v10.rs @@ -209,6 +209,47 @@ fn session_messages_layout() { "820e82056178", ); golden(ControllerMsg::Privacy { on: true }, "820d81f5"); + golden( + HostMsg::Gamepad { + state: GamepadSupport::Ready, + detail: None, + }, + "820f8103", + ); + golden( + HostMsg::Gamepad { + state: GamepadSupport::Failed, + detail: Some("x".into()), + }, + "820f82046178", + ); + golden( + HostMsg::Rumble { + pad: 1, + large: 200, + small: 0, + }, + "8210830118c800", + ); + golden( + ControllerMsg::Input { + t: 5, + events: vec![ + InputEvent::Gamepad { + pad: 0, + buttons: gamepad_buttons::A, + left_trigger: 255, + right_trigger: 0, + left_x: -1, + left_y: 1, + right_x: 0, + right_y: 0, + }, + InputEvent::GamepadRemoved { pad: 2 }, + ], + }, + "82018205828209880019100018ff0020010000820a8102", + ); } #[test] diff --git a/docs/android.md b/docs/android.md index d16730f5..425a34db 100644 --- a/docs/android.md +++ b/docs/android.md @@ -73,6 +73,10 @@ When controlling a computer, **Game keys** under On-screen keys in the menu lays - **Edit layout** (Game keys → Edit layout): the picture dims under a dot grid. Drag buttons to move them (they snap to other buttons and the middle of the screen, with an alignment line and a light tick), pinch with two fingers to resize the selected one, and tap a button to open its settings on the other side of the screen (key, text on the button, hold / tap to toggle, drag to turn the view, size; for the joystick: directions, key pressed past the edge, center where you touch, size), or duplicate / delete it. The toolbar has undo (every step can be undone), add (a key, or a joystick), layout settings (name, opacity, view turning speed, vibrate on press), cancel and done; drag it by the handle on its left when it covers a button. You edit a copy: nothing is saved until Done, and cancelling with changes asks first - A short explanation is shown the first time +### Gamepads + +Gamepads connected to the phone (Bluetooth, USB, the built-in controls of a handheld) are plugged into Windows and Linux computers as Xbox 360 controllers, and games make them vibrate (see [Usage → Gamepads](usage.md#gamepads)). Menu → **Keyboard & input** → **Gamepads** has the switch and says why when the computer can't take them (for example usbip-win2 isn't installed there). While they're sent, the gamepad's D-pad and buttons only go to the computer; Back and Home still work as usual. + ## Phone: Share screen (be controlled) On the "Share screen" tab, tap **Start sharing screen**: Airhand asks for notification and audio-recording permission (recording is only used to share **what the phone is playing**, never the microphone; the screen is shared even if you decline), then the system asks to confirm screen recording. Once sharing: @@ -118,6 +122,7 @@ Like on computers, Airhand checks GitHub Releases ([sqlpxc/airhand](https://gith - Enter the control code on the left with the remote's number keys or the on-screen keypad; recent devices are on the right (arrow keys to pick, OK to connect); to remove a device, use the delete button next to it, or hold OK / press Menu on it (asks first); Settings (server, fingerprint, device name, [updates](#updates)) is at the top right - The picture is full screen with sound on. **OK / Menu** opens the side menu: sound, A/V sync, displays, quality (each press picks the next preset), video format (auto / each format both sides support, each press picks the next one), picture size (fit / fill, cropping the edges / stretch), connection info, disconnect; video format and picture size are remembered for later connections; **left / right** switch the remote display; **Back** closes the menu, and asks before disconnecting +- **Gamepads** connected to the TV are plugged into Windows and Linux computers (play the computer's games on the TV, see [Usage → Gamepads](usage.md#gamepads)); press **Select + Start** on the gamepad to open the side menu, where it navigates as usual; the menu has a Gamepads switch - TVs only watch, so there's no warning when the other side hasn't allowed remote control (the phone's accessibility service, the Mac's Accessibility permission) ## Where the data is stored diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index dd1f92b6..176b0c3c 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -73,6 +73,10 @@ - **编辑布局**(游戏按键页 → 编辑布局):画面压暗、铺一层点阵,拖动按钮摆放(靠近别的按钮或者画面中线时吸过去,画出对齐线,轻振一下),双指捏合调选中的按钮的大小,点一下按钮在另一边弹出它的设置(按键、按钮上的文字、按住 / 点一下切换、拖动可以转视角、大小;摇杆是方向键、推出边缘加按、从按下的地方开始、大小),还可以复制、删除。工具栏:撤销(每一步都能撤销)、添加(选键,或者摇杆)、方案设置(名称、不透明度、转视角灵敏度、按下时振动)、取消、完成;工具栏挡住按钮时按着左边的把手拖开。改的是一份副本,点“完成”才保存,有改动时取消会先确认 - 第一次打开时有一页说明 +### 手柄 + +接在手机上的手柄(蓝牙、USB、掌机自带的按键)会作为 Xbox 360 手柄插到 Windows、Linux 电脑上,游戏也能让它震动(见[使用指南 → 手柄](usage.zh-CN.md#手柄))。菜单 → **键盘与输入** → **手柄**里有开关,电脑接不了时说明原因(例如那台电脑没装 usbip-win2)。发给电脑的时候,手柄的方向键和按键只给电脑;返回键、主页键照常是手机的。 + ## 手机:共享本机(被控) “共享本机”页点**开始共享屏幕**:先请求通知和录音权限(录音只用来共享**手机正在播放的声音**,不录麦克风;拒绝也能共享画面),然后是系统的录屏确认。开始后: @@ -118,6 +122,7 @@ - 左边输入控制码:遥控器的数字键直接输入,或者用屏幕上的数字键盘;右边是最近连接的设备,方向键选中、确认键连接;要删除某台设备,按它右边的删除按钮,或者在设备上长按确认键 / 按菜单键(会先确认);右上角是设置(服务器、指纹、本机名称、[更新](#更新)) - 画面全屏显示,默认打开声音。**确认键 / 菜单键**打开右侧菜单:声音、音画同步、显示器、画质(按一下换一档)、编码格式(自动 / 双方都支持的各种格式,按一下换一个)、画面缩放(完整显示 / 铺满(裁掉边缘)/ 拉伸全屏)、显示连接信息、断开;编码格式和画面缩放会记下来,以后的连接也用;**左 / 右**切换对方的显示器;**返回键**关闭菜单,再按一次确认断开 +- 接在电视上的**手柄**会插到 Windows、Linux 电脑上(在电视上玩电脑里的游戏,见[使用指南 → 手柄](usage.zh-CN.md#手柄));在手柄上同时按 **Select + Start** 打开侧边菜单,菜单里手柄照常用来选;菜单里有手柄的开关 - 电视只看不操作:对方没有开启远程操作(手机的无障碍服务、Mac 的“辅助功能”)时不会提示 ## 数据保存在哪里 diff --git a/docs/architecture.md b/docs/architecture.md index 2086f1f1..0558a317 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -249,6 +249,18 @@ The controller's microphone can go the other way, into a virtual microphone on t `e2e_mic` sends a 1 kHz tone from a protocol-level controller through a real relay, deliberately drops datagrams and checks the frequency and continuity recorded from the host’s audio device on each platform. `native_mic_cleanup` checks crash recovery, disconnect and uninstall on Mac and Linux. +## Gamepads + +Gamepads on the controller are plugged into the host as wired Xbox 360 controllers (see "Gamepads" in `airhand_proto::session`): + +| Stage | How | +|---|---| +| State | After `Hello` a desktop host says whether it can take gamepads (`HostMsg::Gamepad`: unsupported / no driver / no permission / ready / failed, with a technical detail) and again when that changes. Hosts that don't say (phones) take no gamepad input; the controllers don't send any | +| Capture | Console: the Gamepad API, polled every 4 ms by one hub for the whole page and handed to the session you're viewing (`client/src/lib/gamepad.ts`); Android: key and joystick events of gamepad input devices (`controller/Gamepads.kt`, TVs included); iOS: GameController (`Controller/Gamepads.swift`). All map to XInput's layout (buttons by position, triggers 0–255, sticks with Y up) | +| Transport | Input events on the control lane like keys and the mouse (`InputEvent::Gamepad` carries the whole state of one pad, `GamepadRemoved` unplugs it). Only changes are sent (stick noise below 1/1024 of the range isn't); consecutive states of one pad with the same buttons are coalesced at every queue, never across a button change. Stale input becomes "release all", which puts every remote pad back to rest; the controller then resends the current state | +| Virtual pad | [airhand-dock](https://github.com/sqlpxc/airhand-dock) (`client/src-tauri/src/host/gamepad.rs`): one dock per process, opened on first use; plugging and unplugging on one worker thread (plugging takes tens of milliseconds). Windows: usbip-win2 attaches the device served on a loopback USB/IP server, Windows binds its own `xusb22`. Linux: `vhci-hcd` as root, otherwise `uinput`, where airhand-dock plays the USB host and the `xpad` driver itself. macOS can't | +| Ownership | Pads belong to the controller (its identity from the end-to-end handshake), not to a session: a reconnect keeps them. When its last session ends normally they're unplugged at once; when it drops, after 30 s without a reconnect | +| Rumble | airhand-dock reports the motors the game set; the host sends `HostMsg::Rumble` to the controller's latest session (latest value per pad, ahead of queued messages). The console uses `vibrationActuator` (refreshed every 4 s while on), Android the input device's vibrators, iOS CoreHaptics on the pad's handles | ## A/V sync (optional, off by default) Audio goes through a jitter buffer while video is shown as soon as it arrives, so by default audio lags video slightly: about **70 ms** in our measurements (same machine, local relay, 4K output at 1080p; 49–78 ms per run). That's barely noticeable while working, but may be when watching video. diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index 07c52b12..ab9f9cfc 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -249,6 +249,18 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 `e2e_mic` 让协议级控制端通过真实中转发送 1 kHz 测试音,并故意丢弃一些数据报。测试从各平台的系统录音设备录回声音,检查频率和连续性。`native_mic_cleanup` 检查 Mac 和 Linux 的强退恢复、断开和卸载。 +## 手柄 + +控制端的手柄作为有线 Xbox 360 手柄插到被控端上(见 `airhand_proto::session` 的“手柄”): + +| 环节 | 怎么做 | +|---|---| +| 状态 | 桌面被控端在 `Hello` 之后说它能不能接手柄(`HostMsg::Gamepad`:不支持 / 缺驱动 / 没有权限 / 能接 / 出错了,带技术信息),之后有变化再说。不说的被控端(手机)不接手柄,控制端也就不发 | +| 采集 | 控制台:Gamepad API,整个网页一个轮询(每 4 ms),交给正在查看的会话(`client/src/lib/gamepad.ts`);Android:手柄设备的按键和摇杆事件(`controller/Gamepads.kt`,电视也是);iOS:GameController(`Controller/Gamepads.swift`)。都换成 XInput 的格式(按钮按位置、扳机 0–255、摇杆 Y 向上为正) | +| 传输 | 和键盘鼠标一样是控制通道上的输入(`InputEvent::Gamepad` 是一个手柄完整的状态,`GamepadRemoved` 拔掉它)。只在变了的时候发(摇杆不到量程 1/1024 的抖动不算);每个队列里同一个手柄、按钮一样的相邻状态只留最后一个,不会越过按钮的变化。过时的输入换成“释放所有按键”,对方把手柄都放回原位,控制端随后重发现在的状态 | +| 虚拟手柄 | [airhand-dock](https://github.com/sqlpxc/airhand-dock)(`client/src-tauri/src/host/gamepad.rs`):整个进程一个,第一次用时打开;插拔都在一个线程上(插一个要几十毫秒)。Windows:usbip-win2 把本机回环 USB/IP 服务器上的设备插上,系统用自带的 `xusb22` 驱动;Linux:root 时用 `vhci-hcd`,否则用 `uinput`,airhand-dock 自己当 USB 主机、做 `xpad` 驱动做的事。macOS 不行 | +| 归属 | 手柄属于控制端(端到端握手里的身份),不属于会话:断线重连接着用。它的最后一个会话正常结束时马上拔掉,断掉的等 30 秒没连回来再拔 | +| 震动 | airhand-dock 报告游戏设置的马达,被控端发 `HostMsg::Rumble` 给这个控制端最新的会话(每个手柄只留最新值,排在前面)。控制台用 `vibrationActuator`(震着时每 4 秒重放),Android 用手柄设备的振动器,iOS 用手柄两侧的 CoreHaptics | ## 音画同步(可选,默认关闭) 声音要经过抖动缓冲,画面则是一到就显示,所以默认声音会比画面晚一点:实测约 **70 ms**(同机、本地中转、4K 屏输出 1080p;单次 49~78 ms)。操作电脑时几乎察觉不到,看视频时可能会。 diff --git a/docs/development.md b/docs/development.md index 1a28db27..46e888d9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -29,6 +29,8 @@ cargo test --lib ltr_probe -- --ignored --nocapture cargo test --lib loopback_captures_tone -- --ignored --nocapture # Windows: the controller's microphone into Steam Streaming Microphone (needs it on this computer), recorded back as a 1 kHz tone cargo test --lib mic_reaches_steam_streaming_microphone -- --ignored --nocapture +# a virtual Xbox 360 gamepad plugged and unplugged through airhand-dock (Windows: needs usbip-win2; Linux: root or access to /dev/uinput) +cargo test --lib plugs_a_virtual_gamepad -- --ignored --nocapture # macOS 14.2+ / Linux with PipeWire and pactl: crash recovery, disconnect and uninstall during forwarding cargo test --lib native_mic_cleanup -- --ignored --nocapture # Windows: list the current displays, which ones are virtual, and the main monitor's mode (read-only, changes nothing) diff --git a/docs/development.zh-CN.md b/docs/development.zh-CN.md index f46cd6db..10dd81c9 100644 --- a/docs/development.zh-CN.md +++ b/docs/development.zh-CN.md @@ -29,6 +29,8 @@ cargo test --lib ltr_probe -- --ignored --nocapture cargo test --lib loopback_captures_tone -- --ignored --nocapture # Windows:控制端的麦克风写进 Steam Streaming Microphone(这台电脑上要有它),从它的录音端录回 1 kHz 的声音 cargo test --lib mic_reaches_steam_streaming_microphone -- --ignored --nocapture +# 经 airhand-dock 插上、拔掉一个虚拟的 Xbox 360 手柄(Windows 要装好 usbip-win2;Linux 要 root 或者能用 /dev/uinput) +cargo test --lib plugs_a_virtual_gamepad -- --ignored --nocapture # macOS 14.2+ / Linux(PipeWire、pactl):检查强退后的清理、断开和转发期间卸载 cargo test --lib native_mic_cleanup -- --ignored --nocapture # Windows:列出现在的显示器、哪些是虚拟显示器、本机主显示器的分辨率(只读,不改显示设置) diff --git a/docs/ios.md b/docs/ios.md index dbfd14af..e34da6e1 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -52,6 +52,10 @@ After zooming in, Airhand asks the remote for a sharper picture once your finger For computers, Menu → **Game controls** overlays buttons and sticks (same as Android): hold buttons (keys, mouse buttons, wheel, combos of up to 3 keys; tap-to-toggle; drag-to-look), WASD / arrow sticks with 8 directions, hysteresis and an edge key (Shift to sprint), floating start; dragging on empty space turns the view when the game hides the cursor. Templates: shooter, skills (MOBA / ARPG), arrow keys; per-computer on/off and layout. The editor dims the picture with a dot grid; drag to place (snaps to other buttons and the center lines with guides and a tick), pinch to resize, tap to edit, undo, add, layout settings (name, opacity, look sensitivity, haptics). +### Gamepads + +Gamepads connected to the iPhone / iPad (Xbox, PlayStation, Switch Pro, MFi) are plugged into Windows and Linux computers as Xbox 360 controllers, and games make them vibrate through the controller's haptics (see [Usage → Gamepads](usage.md#gamepads)). Menu → **Gamepads** has the switch, the reason when the computer can't take them, and the gamepads in use. The Home, Menu and Options buttons go to the computer instead of the system. + ## Share Tap **Start sharing the screen** on the Share page and choose “Start Broadcast” in the system sheet. Then: diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index e9f9fa80..816d2c6e 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -60,6 +60,10 @@ - **方案**:射击、技能(MOBA / ARPG)、方向键三套模板,可以新建、复制、重命名、删除;每台电脑分别记住开没开、用哪个方案 - **编辑布局**:画面压暗、铺一层点阵,拖动摆放(靠近别的按钮或画面中线时吸过去、画出对齐线、轻振一下),双指捏合调大小,点一下改设置(按键、文字、按法、转视角、大小;摇杆的方向、加按的键、浮动),可以复制、删除;工具栏有撤销、添加、方案设置(名称、不透明度、灵敏度、振动)、取消、完成,按住左边的把手可以把工具栏拖开 +### 手柄 + +接在 iPhone / iPad 上的手柄(Xbox、PlayStation、Switch Pro、MFi)会作为 Xbox 360 手柄插到 Windows、Linux 电脑上,游戏让它震动时手柄跟着震(见[使用指南 → 手柄](usage.zh-CN.md#手柄))。菜单 → **手柄**里有开关、电脑接不了时的原因和正在用的手柄。手柄上的主页、菜单、选项键交给电脑,不给系统。 + ## 共享本机(被看) “共享本机”页点 **开始共享屏幕**,在系统弹窗里选“开始直播”。开始后: diff --git a/docs/limitations.md b/docs/limitations.md index 154f255c..e2060009 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -16,6 +16,7 @@ - One stream per video frame also needs a v10 relay server: older servers still work, but video stays a single stream, so one lost packet holds up the frames behind it - Showing several displays at once (see [Usage → Multiple displays](usage.md#multiple-displays)) is limited to 4; each display is captured and encoded on its own, so the host's encoding load and the bandwidth roughly scale with the number of displays (the quality settings apply to each one). When the GPU can't run that many hardware encoders at once, the extra streams fall back to software encoding. A/V sync delays all of them together. The Android host has a single screen, and the Android controller shows one remote display at a time - Later frame streams can arrive first. Frames that depend on a missing reference still wait for retransmission or recovery, so long, lossy paths can stutter. +- Gamepads (see [Usage → Gamepads](usage.md#gamepads)) can only be plugged into Windows hosts with usbip-win2 installed and Linux hosts where Airhand can use `/dev/uinput` (or runs as root); macOS, Android and iOS hosts can't take them. The remote pad is an Xbox 360 controller: gyro, touchpads, extra paddles, adaptive triggers and light bars aren't passed on, and the button labels of other pads map by position. Up to four per controller (XInput itself only sees four pads per computer). Browsers only report a gamepad after one of its buttons was pressed in the page, and the Linux desktop console sees gamepads only when WebKitGTK was built with gamepad support (libmanette) ## Windows diff --git a/docs/limitations.zh-CN.md b/docs/limitations.zh-CN.md index a5e17914..c4131cc8 100644 --- a/docs/limitations.zh-CN.md +++ b/docs/limitations.zh-CN.md @@ -16,6 +16,7 @@ - 画面每帧一条流要中转服务器也是 v10:旧的服务器照样能用,只是画面还是一条流,丢一个包就挡住后面的帧 - 同时显示几个显示器时(见[使用说明 → 多屏](usage.zh-CN.md#多屏))最多 4 个;每个显示器各自采集、编码,被控端的编码开销和带宽大致按显示器的个数翻倍(画质设置对每一个分别生效);显卡同时开不了那么多硬件编码器时,多出来的那几路退回软件编码。音画同步对所有的一起推迟。Android 被控端只有一块屏幕,Android 控制端一次只看对方的一个显示器 - 独立帧流允许后面的帧先到。依赖丢失参考帧的增量帧仍需等待重传或恢复,因此长往返、高丢包链路可能卡顿。 +- 手柄(见[使用指南 → 手柄](usage.zh-CN.md#手柄))只能插到装了 usbip-win2 的 Windows 被控端、Airhand 能用 `/dev/uinput`(或以 root 运行)的 Linux 被控端上;macOS、Android、iOS 被控端不能接。对方的手柄是 Xbox 360 手柄:陀螺仪、触摸板、背键、自适应扳机、灯条都传不过去,别的手柄的按键按位置对应。每个控制端最多四个(XInput 本身每台电脑也只认四个)。浏览器要在网页里按过手柄上的键才说它接上了;Linux 桌面版的控制台要 WebKitGTK 编译时带了手柄支持(libmanette)才看得到手柄 ## Windows diff --git a/docs/usage.md b/docs/usage.md index c1e2b79a..f79b29fe 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -344,6 +344,22 @@ Keeps the people at the remote computer from seeing what you do: all of its moni - Someone at the remote computer can end it by disconnecting that computer from the network and pressing a key once the session has dropped (the screen stays locked), or by restarting it (on Windows Airhand restores the monitors when it starts; on a Mac they come back as soon as Airhand quits) - To keep others from turning it on for a computer, add `privacy_mode = false` to its `config.toml` (see [Configuration file](#configuration-file)) +### Gamepads + +Gamepads connected to the computer or phone you control from (Xbox, PlayStation, Switch Pro, the built-in pad of a handheld…) are plugged into the remote computer as wired **Xbox 360 controllers**: games see a real USB gamepad (XInput, DirectInput, Windows.Gaming.Input, SDL, Steam, evdev), and when a game makes it vibrate, your gamepad vibrates. On by default; each connection has its own switch. + +- **Windows hosts** need [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases) (a free USB/IP driver signed by Microsoft) installed once; no administrator rights are needed afterwards, and it also works for the lock screen and the system service. Airhand notices when it gets installed, no restart needed +- **Linux hosts** use the kernel's `vhci-hcd` when Airhand runs as root, otherwise `uinput`: Airhand needs access to `/dev/uinput`. Steam's controller rules (`steam-devices`) already grant it to the user at the seat; otherwise add a udev rule: + ```bash + echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' | sudo tee /etc/udev/rules.d/60-airhand-uinput.rules + sudo udevadm control --reload && sudo udevadm trigger --name-match=uinput + ``` +- **macOS, Android and iOS hosts** can't take gamepads (macOS has no way for an app to plug in a virtual gamepad) +- **Console** (desktop and web): the gamepad button appears in the toolbar once a gamepad has been used here (browsers only report gamepads after a button press). Its menu has the switch, says why when the remote computer can't take gamepads (for example "needs usbip-win2"), and lists the gamepads. Gamepads go to the connection you're viewing; switching tabs puts the remote gamepads back to rest +- **Android**: menu → **Keyboard & input** → **Gamepads**. On a TV, gamepads are sent too (play the computer's games on the TV); press **Select + Start** on the gamepad to open the menu, where the gamepad navigates as usual +- **iPhone / iPad**: menu → **Gamepads** +- Up to four gamepads per controller. Buttons map by position (A at the bottom, as on an Xbox pad), whatever the labels on yours. When a gamepad is unplugged here, the remote one is unplugged too. If the connection drops, the remote gamepads stay plugged for 30 seconds so a reconnect doesn't make the game see them disconnect; disconnecting unplugs them right away + ## Language The console and tray menu are available in **English** and **Simplified Chinese**. By default the client follows the system display language: Chinese if it is Chinese, English otherwise. Switch any time from the tray menu (Language / 语言) or the 中文 / EN switch in the console menu (the icon at the top-left). The choice is saved in `config.toml` (`language`) and used from then on; delete that line to follow the system language again. diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index eb407e3e..d158dcaf 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -344,6 +344,22 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 - 对方电脑前的人要结束它:断开那台电脑的网络,会话断开之后按一下键盘(锁着屏),或者重启它(Windows 上 Airhand 启动时会把显示器恢复原样;Mac 上 Airhand 一退出就恢复了) - 不想让别人对这台电脑开防窥模式:在它的 `config.toml` 里写上 `privacy_mode = false`(见[配置文件](#配置文件)) +### 手柄 + +接在你这边的电脑或手机上的手柄(Xbox、PlayStation、Switch Pro、掌机自带的手柄……)会作为有线的 **Xbox 360 手柄**插到对方电脑上:游戏看到的就是一个真的 USB 手柄(XInput、DirectInput、Windows.Gaming.Input、SDL、Steam、evdev),游戏让它震动时,你手里的手柄跟着震。默认打开,每个连接各有一个开关。 + +- **Windows 被控端**要先装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases)(免费的 USB/IP 驱动,有微软的签名);之后不需要管理员权限,锁屏界面、系统服务里也能用。装好之后 Airhand 自己会发现,不用重启 +- **Linux 被控端**:Airhand 以 root 运行时用内核的 `vhci-hcd`,否则用 `uinput`,需要能读写 `/dev/uinput`。装了 Steam 的手柄规则(`steam-devices`)就已经给了坐在电脑前的用户;否则加一条 udev 规则: + ```bash + echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' | sudo tee /etc/udev/rules.d/60-airhand-uinput.rules + sudo udevadm control --reload && sudo udevadm trigger --name-match=uinput + ``` +- **macOS、Android、iOS 被控端**不能接手柄(macOS 没有办法让应用插上虚拟手柄) +- **控制台**(桌面版、网页版):在这边用过手柄之后(浏览器要在手柄上按过键才说它接上了),工具栏里出现手柄按钮。菜单里有开关、对方接不了时的原因(例如“要先装 usbip-win2”)和手柄列表。手柄只给正在查看的连接;切换标签时对方的手柄放回原位 +- **Android**:菜单 → **键盘与输入** → **手柄**。电视上也发手柄(在电视上玩电脑里的游戏);在手柄上同时按 **Select + Start** 打开菜单,菜单里手柄照常用来选 +- **iPhone / iPad**:菜单 → **手柄** +- 每个控制端最多四个手柄。按键按位置对应(和 Xbox 手柄一样 A 在下面),不管你的手柄上印的是什么。这边拔掉手柄,对方的也跟着拔掉。连接断掉时,对方的手柄继续插着 30 秒,重连上来游戏不会以为手柄断开了;主动断开则马上拔掉 + ## 界面语言 控制台和托盘菜单支持**简体中文**和**英文**。默认跟随系统显示语言:系统是中文就用中文,否则用英文。可以在托盘菜单“语言 / Language”或控制台菜单(左上角的图标)里的“中文 / EN”随时切换。选的语言记在 `config.toml` 里(`language`),以后一直用它;删掉这一项就重新跟随系统语言。 diff --git a/ios/Airhand/Controller/Gamepads.swift b/ios/Airhand/Controller/Gamepads.swift new file mode 100644 index 00000000..993a8e45 --- /dev/null +++ b/ios/Airhand/Controller/Gamepads.swift @@ -0,0 +1,302 @@ +import CoreHaptics +import Foundation +import GameController +import Observation + +/// 一个手柄现在的样子:XInput 的格式(同 Rust 的 `InputEvent::Gamepad`:扳机 0-255,摇杆 -32768...32767、Y 向上为正) +struct PadState: Equatable { + var buttons = 0 + var leftTrigger = 0 + var rightTrigger = 0 + var leftX = 0 + var leftY = 0 + var rightX = 0 + var rightY = 0 + + /// 摇杆变化不到这么多不算(-32768...32767 里约 0.2%):放着不动时读数也在跳 + static let stickStep = 64 + + /// 和上次发的比,值不值得再发:按钮、扳机变了,或者摇杆动了至少 [stickStep](回到正中间也算)。和控制台的 gamepad.ts 一样 + func differs(from o: PadState?) -> Bool { + guard let o else { return true } + if buttons != o.buttons || leftTrigger != o.leftTrigger || rightTrigger != o.rightTrigger { return true } + return [(leftX, o.leftX), (leftY, o.leftY), (rightX, o.rightX), (rightY, o.rightY)] + .contains { abs($0.0 - $0.1) >= Self.stickStep || ($0.0 == 0) != ($0.1 == 0) } + } + + /// -1...1 → -32768...32767 + static func stick(_ v: Float) -> Int { + let x = min(max(v, -1), 1) + return Int((x < 0 ? x * 32768 : x * 32767).rounded()) + } + + /// 0...1 → 0...255 + static func trigger(_ v: Float) -> Int { Int((min(max(v, 0), 1) * 255).rounded()) } +} + +/// XInput 的按钮位(`airhand_proto::session::gamepad_buttons`) +enum XInput { + static let dpadUp = 0x0001 + static let dpadDown = 0x0002 + static let dpadLeft = 0x0004 + static let dpadRight = 0x0008 + static let start = 0x0010 + static let back = 0x0020 + static let leftThumb = 0x0040 + static let rightThumb = 0x0080 + static let leftShoulder = 0x0100 + static let rightShoulder = 0x0200 + static let guide = 0x0400 + static let a = 0x1000 + static let b = 0x2000 + static let x = 0x4000 + static let y = 0x8000 +} + +/// 这台设备接着的一个手柄(界面列出来) +struct LocalPad: Identifiable, Equatable { + let pad: Int + let name: String + let rumble: Bool + var id: Int { pad } +} + +/// 这台设备接着的手柄(Xbox、PlayStation、Switch Pro、MFi……,GameController 框架认得的):变成发给被控端的手柄输入, +/// 被控端插成虚拟的 Xbox 360 手柄(见 Rust 的 `airhand_proto::session` 的"手柄"),游戏让它震动时这里跟着震。 +/// 和控制台的 gamepad.ts、Android 的 Gamepads.kt 是同一套规则: +/// +/// * 手柄的编号(pad,0..<[maxPads]):先用到(按了键、动了摇杆)的用小的,拔掉之后空出来给下一个;拔掉时告诉对方; +/// * GameController 的按钮本来就是按位置排的(A 在下、B 在右……,和 Xbox 一样),Y 轴向上为正,和 XInput 一样; +/// Menu → Start,Options → Back,Home → 西瓜键(不让系统拿去打开游戏中心)。只在变了的时候发,按钮变了马上发, +/// 只是摇杆动了合并着发(见 [InputSender]); +/// * 震动:CoreHaptics,有左右两个马达的手柄(Xbox、DualSense)左边是大马达、右边是小马达,只有一个的用它; +/// 一直震到下一次设置(循环的连续振动,用强度参数调)。 +/// +/// 都在主线程上用(GameController 的回调默认在主队列)。 +@Observable +final class Gamepads { + static let maxPads = 4 + + /// 这里接着的、用过的手柄(按编号) + private(set) var pads: [LocalPad] = [] + + /// 把手柄交给对方(会话 live、对方说了能不能接、开关打开、画面在屏幕上) + @ObservationIgnored var active = false { + didSet { + guard active != oldValue else { return } + if active { resync() } else { stopRumble() } + } + } + + /// 对方接不了手柄:照样读,不发,按下按钮时说一声([onRefused]) + @ObservationIgnored var refuse = false { + didSet { if oldValue && !refuse { resync() } } + } + + @ObservationIgnored var onRefused: (() -> Void)? + + @ObservationIgnored private let send: ([JSON], Bool) -> Void + @ObservationIgnored private var slots: [GCController?] = Array(repeating: nil, count: Gamepads.maxPads) + @ObservationIgnored private var sent: [PadState?] = Array(repeating: nil, count: Gamepads.maxPads) + @ObservationIgnored private var rumblers: [Rumbler?] = Array(repeating: nil, count: Gamepads.maxPads) + @ObservationIgnored private var observers: [NSObjectProtocol] = [] + + init(send: @escaping ([JSON], Bool) -> Void) { + self.send = send + let nc = NotificationCenter.default + observers.append(nc.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { [weak self] n in + if let c = n.object as? GCController { self?.setup(c) } + }) + observers.append(nc.addObserver(forName: .GCControllerDidDisconnect, object: nil, queue: .main) { [weak self] n in + if let c = n.object as? GCController { self?.removed(c) } + }) + GCController.controllers().forEach(setup) + } + + /// 界面关掉了:不再读手柄,停下震动 + func release() { + for o in observers { NotificationCenter.default.removeObserver(o) } + observers = [] + for c in GCController.controllers() { c.extendedGamepad?.valueChangedHandler = nil } + stopRumble() + } + + /// 对方把手柄放回了原位(释放所有按键)、刚能接手柄:把完整的状态发一遍,空着的编号说"拔掉了" + func resync() { + var events: [JSON] = [] + for pad in 0.. Int? { + if let i = slots.firstIndex(where: { $0 === c }) { return i } + guard let free = slots.firstIndex(where: { $0 == nil }) else { return nil } + slots[free] = c + sent[free] = nil + publish() + return free + } + + private func removed(_ c: GCController) { + guard let pad = slots.firstIndex(where: { $0 === c }) else { return } + slots[pad] = nil + rumblers[pad]?.stop() + rumblers[pad] = nil + let wasSent = sent[pad] != nil + sent[pad] = nil + publish() + if active && !refuse && wasSent { send([Input.gamepadRemoved(pad)], true) } + } + + private func publish() { + pads = slots.enumerated().compactMap { pad, c in + guard let c else { return nil } + return LocalPad(pad: pad, name: c.vendorName ?? c.productCategory, rumble: c.haptics != nil) + } + } + + private func stopRumble() { + for r in rumblers { r?.stop() } + rumblers = Array(repeating: nil, count: Self.maxPads) + } + + /// 按位置读(见类的说明) + static func read(_ g: GCExtendedGamepad) -> PadState { + var b = 0 + func on(_ x: GCControllerButtonInput?, _ bit: Int) { if x?.isPressed == true { b |= bit } } + on(g.buttonA, XInput.a) + on(g.buttonB, XInput.b) + on(g.buttonX, XInput.x) + on(g.buttonY, XInput.y) + on(g.leftShoulder, XInput.leftShoulder) + on(g.rightShoulder, XInput.rightShoulder) + on(g.buttonMenu, XInput.start) + on(g.buttonOptions, XInput.back) + on(g.buttonHome, XInput.guide) + on(g.leftThumbstickButton, XInput.leftThumb) + on(g.rightThumbstickButton, XInput.rightThumb) + on(g.dpad.up, XInput.dpadUp) + on(g.dpad.down, XInput.dpadDown) + on(g.dpad.left, XInput.dpadLeft) + on(g.dpad.right, XInput.dpadRight) + return PadState( + buttons: b, + leftTrigger: PadState.trigger(g.leftTrigger.value), + rightTrigger: PadState.trigger(g.rightTrigger.value), + leftX: PadState.stick(g.leftThumbstick.xAxis.value), + leftY: PadState.stick(g.leftThumbstick.yAxis.value), + rightX: PadState.stick(g.rightThumbstick.xAxis.value), + rightY: PadState.stick(g.rightThumbstick.yAxis.value) + ) + } +} + +/// 一个手柄的震动:左右两个马达(大、小)各一个引擎,只有一个马达的用一个(取两者里大的)。 +/// 每个引擎放一段循环的连续振动,强度用动态参数调,0 就停 +private final class Rumbler { + private var engines: [CHHapticEngine] = [] + private var players: [CHHapticAdvancedPatternPlayer?] = [] + /// 每个引擎的锐度:大马达低沉,小马达尖 + private var sharpness: [Float] = [] + + init?(_ c: GCController) { + guard let h = c.haptics else { return nil } + let both = h.supportedLocalities.contains(.leftHandle) && h.supportedLocalities.contains(.rightHandle) + let localities: [(GCHapticsLocality, Float)] = both ? [(.leftHandle, 0.2), (.rightHandle, 0.8)] : [(.default, 0.5)] + for (l, s) in localities { + guard let e = h.createEngine(withLocality: l) else { continue } + let i = engines.count + // 引擎被系统停掉、重置了:播放器不能再用,下次重新建(回调在别的线程上) + e.resetHandler = { [weak self] in DispatchQueue.main.async { self?.players[i] = nil } } + e.stoppedHandler = { [weak self] _ in DispatchQueue.main.async { self?.players[i] = nil } } + engines.append(e) + players.append(nil) + sharpness.append(s) + } + if engines.isEmpty { return nil } + } + + func set(large: Int, small: Int) { + let levels = engines.count >= 2 ? [large, small] : [max(large, small)] + for (i, level) in levels.enumerated() where i < engines.count { play(i, Float(level) / 255) } + } + + func stop() { + for i in engines.indices { play(i, 0) } + for e in engines { e.stop() } + } + + private func play(_ i: Int, _ intensity: Float) { + let control = [CHHapticDynamicParameter(parameterID: .hapticIntensityControl, value: intensity, relativeTime: 0)] + if intensity <= 0 { + try? players[i]?.stop(atTime: CHHapticTimeImmediate) + players[i] = nil + return + } + if let p = players[i] { + try? p.sendParameters(control, atTime: CHHapticTimeImmediate) + return + } + do { + try engines[i].start() + let event = CHHapticEvent( + eventType: .hapticContinuous, + parameters: [ + CHHapticEventParameter(parameterID: .hapticIntensity, value: 1), + CHHapticEventParameter(parameterID: .hapticSharpness, value: sharpness[i]), + ], + relativeTime: 0, + duration: 30 + ) + let p = try engines[i].makeAdvancedPlayer(with: CHHapticPattern(events: [event], parameters: [])) + p.loopEnabled = true + try p.start(atTime: CHHapticTimeImmediate) + try p.sendParameters(control, atTime: CHHapticTimeImmediate) + players[i] = p + } catch { + Log.warn("can't make the gamepad vibrate: \(error)") + } + } +} diff --git a/ios/Airhand/Controller/RemoteSession.swift b/ios/Airhand/Controller/RemoteSession.swift index 6a8654fa..6e03cb6d 100644 --- a/ios/Airhand/Controller/RemoteSession.swift +++ b/ios/Airhand/Controller/RemoteSession.swift @@ -60,6 +60,19 @@ final class RemoteSession { private(set) var privacyState: PrivacyState? /// 没能打开防窥的原因(英文技术信息,对方给的) private(set) var privacyDetail: String? + /// 对方能不能接这里的手柄(Hello 之后对方会说,见 Gamepads.swift)。对方不能接(手机、旧版本)、还没说、 + /// 重连的间隙里为 nil:不读手柄 + private(set) var gamepadState: GamepadSupport? + /// 对方插不上虚拟手柄的原因(英文技术信息) + private(set) var gamepadDetail: String? + /// 把这里的手柄插到对方电脑上(开关,默认开) + private(set) var gamepadEnabled = true + /// 游戏让第 pad 个手柄震动(大、小马达 0-255;在会话的线程上):界面交给 Gamepads + @ObservationIgnored var onRumble: ((Int, Int, Int) -> Void)? + /// 让对方释放了所有按键(对方也把手柄放回了原位):界面让 Gamepads 重新发一遍手柄现在的样子 + @ObservationIgnored var onReleaseAll: (() -> Void)? + /// 这里接着的手柄(会话界面建的,菜单里列出来) + @ObservationIgnored weak var gamepads: Gamepads? /// 远端光标(UIKit 的画面直接观察,不经过 SwiftUI) @ObservationIgnored var onCursor: ((CursorState) -> Void)? @ObservationIgnored var onPhase: ((Phase) -> Void)? @@ -283,9 +296,11 @@ final class RemoteSession { if !self.grantOs.isEmpty { self.hostOs = self.grantOs } self.micState = nil self.micOn = false - // 防窥模式:对方在 Hello 之后重新说(要不要开着已经在握手里告诉它了) + // 防窥模式:对方在 Hello 之后重新说(要不要开着已经在握手里告诉它了);手柄也是 self.privacyState = nil self.privacyDetail = nil + self.gamepadState = nil + self.gamepadDetail = nil } if audioOn && !background { startAudio(tell: !sentAudio) } else if sentAudio { command { Commands.audio($0, false) } } if background { applyBackground() } @@ -462,6 +477,15 @@ final class RemoteSession { // 没能打开(Windows 换虚拟显示器要几秒,用户可能已经关了菜单):提示一下 if state == .failed, was != .failed { self.app?.show(L.t("privacy_failed", detail ?? "—")) } } + case "gamepad": + let state = GamepadSupport.fromWire(e.str("state")) + let detail = e.str("detail") + main { + self.gamepadDetail = detail + self.gamepadState = state + } + case "rumble": + onRumble?(e.int("pad") ?? 0, e.int("large") ?? 0, e.int("small") ?? 0) default: break } } @@ -518,7 +542,23 @@ final class RemoteSession { /// 输入事件(触控、键盘)。`now=false` 的会和后面的鼠标移动合并 func input(_ events: [JSON], now: Bool = true) { - if !viewOnly, phase == .live { sender.send(events, now: now) } + guard !viewOnly, phase == .live else { return } + sender.send(events, now: now) + if events.contains(where: { $0.str("type") == "releaseAll" }) { onReleaseAll?() } + } + + /// 这里的手柄的输入(Gamepads 拼好的)。`now=false` 的和后面的合并 + func gamepad(_ events: [JSON], now: Bool) { + if phase == .live, gamepadEnabled { sender.send(events, now: now) } + } + + /// 把这里的手柄插到对方电脑上(开关):关掉时对方拔掉它们 + func setGamepadEnabled(_ on: Bool) { + guard on != gamepadEnabled else { return } + if !on, phase == .live, gamepadState != nil { + sender.send((0.. JSON { ["type": "system", "action": a.rawValue] } + /// 松开所有按着的键(对方也把手柄放回原位) static func releaseAll() -> JSON { ["type": "releaseAll"] } + /// 第 `pad` 个手柄现在的样子(XInput 的格式:按钮位、扳机 0-255、摇杆 -32768...32767 且 Y 向上为正,见 Gamepads.swift) + static func gamepad(_ pad: Int, _ s: PadState) -> JSON { + ["type": "gamepad", "pad": pad, "buttons": s.buttons, "leftTrigger": s.leftTrigger, "rightTrigger": s.rightTrigger, + "leftX": s.leftX, "leftY": s.leftY, "rightX": s.rightX, "rightY": s.rightY] + } + /// 第 `pad` 个手柄拔掉了:对方拔掉对应的虚拟手柄 + static func gamepadRemoved(_ pad: Int) -> JSON { ["type": "gamepadRemoved", "pad": pad] } /// 按下再松开一组键(先按下修饰键,再按下主键,倒序松开) static func chord(_ codes: [String]) -> [JSON] { codes.map { key($0, true) } + codes.reversed().map { key($0, false) } } - /// 加到待发的一批里:紧挨着的绝对移动只留最后一个,相对移动加起来(和 Rust 的 `InputEvent::coalesce` 一样) + /// 加到待发的一批里:紧挨着的绝对移动只留最后一个,相对移动加起来;同一个手柄紧挨着的、按钮没变的状态只留最后一个 + /// (和 Rust 的 `InputEvent::coalesce` 一样) static func append(_ pending: inout [JSON], _ e: JSON) { if let last = pending.last, let t = e.str("type"), t == last.str("type") { if t == "mouseMove" { pending[pending.count - 1] = e; return } + if t == "gamepad", last.int("pad") == e.int("pad"), last.int("buttons") == e.int("buttons") { + pending[pending.count - 1] = e + return + } if t == "mouseDelta" { pending[pending.count - 1] = delta((last.int("dx") ?? 0) + (e.int("dx") ?? 0), (last.int("dy") ?? 0) + (e.int("dy") ?? 0)) return diff --git a/ios/Airhand/Session/SessionController.swift b/ios/Airhand/Session/SessionController.swift index a0f216c3..67f32f13 100644 --- a/ios/Airhand/Session/SessionController.swift +++ b/ios/Airhand/Session/SessionController.swift @@ -181,6 +181,12 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private var orientationPortrait: Bool? private var manualOrientation = false private var shownFrames = false + /// 这台设备接着的手柄:对方能接时插到对方电脑上(见 Gamepads.swift) + private var gamepads: Gamepads! + /// 画面在屏幕上(手柄只在这时交给对方) + private var onScreen = false + /// 对方接不了手柄的原因已经说过了(对方重新说了状态时再说) + private var gamepadTold = false let ui = SessionUIState() init(app: AppModel, session: RemoteSession) { @@ -192,6 +198,10 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract required init?(coder: NSCoder) { fatalError() } + deinit { + gamepads?.release() + } + override var prefersStatusBarHidden: Bool { true } override var prefersHomeIndicatorAutoHidden: Bool { true } override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { .all } @@ -283,15 +293,40 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract NotificationCenter.default.addObserver(self, selector: #selector(resignActive), name: UIApplication.willResignActiveNotification, object: nil) GCMouse.mice().forEach(setupMouse) + // 手柄:对方能接时发给它,游戏让它震动时这里跟着震;让对方释放所有按键之后重新发一遍手柄现在的样子 + gamepads = Gamepads { [weak self] events, now in self?.session.gamepad(events, now: now) } + session.gamepads = gamepads + session.onRumble = { [weak self] pad, large, small in self?.gamepads.rumble(pad, large: large, small: small) } + session.onReleaseAll = { [weak self] in DispatchQueue.main.async { self?.gamepads.resync() } } + gamepads.onRefused = { [weak self] in self?.gamepadRefused() } + observe { [weak self] in self?.sessionChanged() } observe { [weak self] in self?.gameChanged() } + observe { [weak self] in self?.gamepadsChanged() } cursorChanged(session.cursor) } + /// 手柄交不交给对方:会话 live、对方说了它能不能接、开关打开、画面在屏幕上;对方接不了的照样读、不发 + private func gamepadsChanged() { + let state = session.gamepadState + if state == nil { gamepadTold = false } + gamepads.refuse = state?.usable != true + gamepads.active = onScreen && session.phase == .live && state != nil && session.gamepadEnabled + } + + /// 在手柄上按了按钮,对方却接不了:说一声为什么(对方每说一次状态只说一次) + private func gamepadRefused() { + guard !gamepadTold, let s = session.gamepadState else { return } + gamepadTold = true + app.show(L.t("gamepad_refused", GamepadPage.hint(s, os: session.os, detail: session.gamepadDetail))) + } + override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) session.decoder.setLayer(video.displayLayer) becomeFirstResponder() + onScreen = true + gamepadsChanged() #if DEBUG if UserDefaults.standard.bool(forKey: "AirhandNoTips") { app.settings.tipsShown = true } if UserDefaults.standard.bool(forKey: "AirhandSelfTest") { DispatchQueue.main.asyncAfter(deadline: .now() + 3) { self.selfTest() } } @@ -347,6 +382,8 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract super.viewWillDisappear(animated) game.releaseAll() releaseKeys() + onScreen = false + gamepadsChanged() } override func viewDidDisappear(_ animated: Bool) { diff --git a/ios/Airhand/Session/SessionMenu.swift b/ios/Airhand/Session/SessionMenu.swift index 2e3a3be4..8bc3934c 100644 --- a/ios/Airhand/Session/SessionMenu.swift +++ b/ios/Airhand/Session/SessionMenu.swift @@ -153,6 +153,13 @@ struct SessionMenu: View { row(p.active ? "lock.shield.fill" : "lock.shield", L.t("privacy_toggle"), value: L.t(p.active ? "on" : "off")) } } + // 手柄:对方说了它能不能接才有;点开是开关、现在怎么样、这里用过的手柄 + if let g = session.gamepadState { + Divider().overlay(Theme.stroke).padding(.leading, 50) + NavigationLink { GamepadPage(session: session) } label: { + row("gamecontroller.fill", L.t("gamepads"), value: L.t(session.gamepadEnabled && g == .ready ? "on" : "off")) + } + } if computer && !session.viewOnly { Divider().overlay(Theme.stroke).padding(.leading, 50) NavigationLink { GamePage(app: app, session: session, edit: actions.editGame) } label: { @@ -423,6 +430,60 @@ struct PrivacyPage: View { } } +// ───────────────────────────── 手柄 ───────────────────────────── + +/// 把这里接着的手柄插到对方电脑上(和桌面版工具栏的手柄菜单一样):开关、现在怎么样(接不了的话为什么)、用过的手柄 +struct GamepadPage: View { + let session: RemoteSession + + var body: some View { + List { + if let s = session.gamepadState { + Section { + Toggle(isOn: Binding(get: { session.gamepadEnabled }, set: { session.setGamepadEnabled($0) })) { + VStack(alignment: .leading, spacing: 2) { + Text(L.t("gamepad_toggle")) + Text(Self.hint(s, os: session.os, detail: session.gamepadDetail)) + .font(.caption).foregroundStyle(s == .ready ? Theme.sub : Theme.bad) + } + } + } + Section(L.t("gamepads")) { + let pads = session.gamepads?.pads ?? [] + if pads.isEmpty { + Text(L.t("gamepad_none")).foregroundStyle(Theme.sub) + } + ForEach(pads) { p in + HStack { + Text("\(p.pad + 1). \(p.name)") + Spacer() + if !p.rumble { Text(L.t("gamepad_no_rumble")).font(.caption).foregroundStyle(Theme.sub) } + } + } + } + } else { + Text(L.t("session_reconnecting")).foregroundStyle(Theme.sub) + } + } + .scrollContentBackground(.hidden) + .background(Theme.bg) + .navigationTitle(L.t("gamepads")) + .navigationBarTitleDisplayMode(.inline) + .toolbar(.visible, for: .navigationBar) + } + + /// 对方能不能接手柄、为什么不能(和控制台的 gamepadHint 一样) + static func hint(_ s: GamepadSupport, os: OsKind, detail: String?) -> String { + switch s { + case .ready: return L.t("gamepad_ready") + case .noDriver: return L.t(os == .linux ? "gamepad_no_driver_linux" : "gamepad_no_driver_windows") + case .noPermission: return L.t("gamepad_no_permission") + case .failed: return L.t("gamepad_failed", detail ?? "—") + case .unsupported: return L.t(os == .mac ? "gamepad_unsupported_mac" : "gamepad_unsupported") + } + } +} + // ───────────────────────────── 游戏按键 ───────────────────────────── struct GamePage: View { diff --git a/ios/Shared/L10n.swift b/ios/Shared/L10n.swift index 34277e24..63943aff 100644 --- a/ios/Shared/L10n.swift +++ b/ios/Shared/L10n.swift @@ -121,6 +121,15 @@ enum L { "privacy_unavailable_mac": "对方 Mac 用不了:要先在那台 Mac 的“系统设置 → 隐私与安全性 → 辅助功能”里允许 Airhand(挡住它的键盘鼠标要用到)", "privacy_not_allowed": "对方电脑的设置不允许防窥模式(config.toml 里的 privacy_mode)", "privacy_note": "对方电脑前的人可以断开它的网络或者重启它来结束防窥模式", + "gamepads": "手柄", "gamepad_toggle": "把手柄插到对方电脑上", + "gamepad_ready": "这里接着的每个手柄都会作为一个 Xbox 360 手柄插到对方电脑上,游戏可以让它震动", + "gamepad_no_driver_windows": "对方电脑要先装 usbip-win2(免费、有签名的驱动)才能插虚拟手柄:在那台电脑上从 github.com/vadimgrn/usbip-win2/releases 下载安装,不用重启 Airhand", + "gamepad_no_driver_linux": "对方电脑既没有 uinput 也没有 vhci-hcd:在那台电脑上运行 sudo modprobe uinput", + "gamepad_no_permission": "对方电脑上的 Airhand 不能用 /dev/uinput:装上 Steam 的手柄规则(steam-devices),或者照 Airhand 文档加一条 udev 规则", + "gamepad_failed": "对方电脑没能插上虚拟手柄(%@),再用手柄时会重试", + "gamepad_unsupported": "对方电脑不能接手柄", "gamepad_unsupported_mac": "对方是 Mac:macOS 不允许插虚拟手柄", + "gamepad_none": "在这台设备接着的手柄上按一下按键就开始用它", "gamepad_no_rumble": "不能震动", + "gamepad_refused": "手柄没有发给对方:%@", "view_only_host": "对方是 iPhone / iPad,只能看不能操作", "files_sent": "已放进对方的剪贴板,到对方那里粘贴即可", "files_received": "对方复制了 %d 项", "files_save": "保存到“文件”", "files_saved": "已保存到“文件 › 我的 iPhone › Airhand”", "files_failed": "%@ 没有保存成功", @@ -301,6 +310,15 @@ enum L { "privacy_unavailable_mac": "Not available on the remote Mac: someone at that Mac has to allow Airhand in System Settings → Privacy & Security → Accessibility first (it's needed to block its keyboard and mouse)", "privacy_not_allowed": "The remote computer's settings don't allow privacy mode (privacy_mode in config.toml)", "privacy_note": "Someone at the remote computer can end privacy mode by disconnecting it from the network or restarting it", + "gamepads": "Gamepads", "gamepad_toggle": "Plug gamepads into the remote computer", + "gamepad_ready": "Each gamepad connected here shows up on the remote computer as an Xbox 360 controller. Games can make it vibrate", + "gamepad_no_driver_windows": "The remote computer needs usbip-win2 (a free, signed driver) for virtual gamepads: install it there from github.com/vadimgrn/usbip-win2/releases, no need to restart Airhand", + "gamepad_no_driver_linux": "The remote computer has neither uinput nor vhci-hcd: run sudo modprobe uinput there", + "gamepad_no_permission": "Airhand on the remote computer can't use /dev/uinput: install Steam's controller rules (steam-devices) or add the udev rule from the Airhand docs", + "gamepad_failed": "The remote computer couldn't plug in a virtual gamepad (%@). It tries again when you use the gamepad", + "gamepad_unsupported": "The remote computer can't take gamepads", "gamepad_unsupported_mac": "The remote is a Mac: macOS doesn't allow virtual gamepads", + "gamepad_none": "Press a button on a gamepad connected to this device to use it", "gamepad_no_rumble": "Can't vibrate", + "gamepad_refused": "The gamepad isn't sent to the remote computer: %@", "view_only_host": "The remote is an iPhone / iPad: view only", "files_sent": "Put on the remote clipboard — paste it there", "files_received": "The remote copied %d items", "files_save": "Save to Files", "files_saved": "Saved to Files › On My iPhone › Airhand", "files_failed": "Couldn't save %@", diff --git a/ios/Shared/Model.swift b/ios/Shared/Model.swift index 8b5a96ba..8794247e 100644 --- a/ios/Shared/Model.swift +++ b/ios/Shared/Model.swift @@ -169,6 +169,25 @@ enum PrivacyState: String, CaseIterable { var usable: Bool { self != .unavailable && self != .notAllowed } } +/// 被控端能不能接本机的手柄(Rust 的 `GamepadSupport`,见 Gamepads.swift) +enum GamepadSupport: String, CaseIterable { + /// 对方的平台不支持(macOS) + case unsupported + /// 缺驱动:Windows 没装 usbip-win2,Linux 没有 vhci-hcd / uinput + case noDriver + /// Linux 上对方的 Airhand 不能用 /dev/uinput + case noPermission + case ready + /// 插不上虚拟手柄(detail 是原因),对方在用到时重试 + case failed + + /// 不认识的(对方版本新增的;Rust 那边已经报成 unsupported)当作不支持 + static func fromWire(_ s: String?) -> GamepadSupport { s.flatMap(GamepadSupport.init(rawValue:)) ?? .unsupported } + + /// 手柄的输入发得过去(插不上的也发:对方在用到时重试) + var usable: Bool { self == .ready || self == .failed } +} + struct HostHello { var hostname: String var os: String diff --git a/ios/Tests/ProtocolTests.swift b/ios/Tests/ProtocolTests.swift index 2af0575f..783d1b55 100644 --- a/ios/Tests/ProtocolTests.swift +++ b/ios/Tests/ProtocolTests.swift @@ -81,6 +81,8 @@ final class ProtocolTests: XCTestCase { let mine: [JSON] = [ Input.move(0.5, 0.25), Input.delta(-3, 7), Input.button("right", true), Input.wheel(0, -120), Input.key("KeyA", false), Input.text("你好"), Input.releaseAll(), Input.touch(1, "down", 0.25, 0.75), Input.system(.back), + Input.gamepad(1, PadState(buttons: XInput.a | XInput.dpadUp, rightTrigger: 255, leftX: -32768, leftY: 32767, rightY: -1)), + Input.gamepadRemoved(1), ] let theirs = Self.fixture["input"] as! [Any] XCTAssertEqual(mine.count, theirs.count) @@ -100,6 +102,26 @@ final class ProtocolTests: XCTestCase { XCTAssertTrue(same(Commands.privacy(3, true), find("privacy"))) } + /// 会话事件 `gamepad` 的状态(Rust 的 `GamepadSupport`);不认识的当作不支持。手柄的状态换算、合并和控制台一样 + func testGamepads() { + XCTAssertEqual(GamepadSupport.allCases.map(\.rawValue), ["unsupported", "noDriver", "noPermission", "ready", "failed"]) + XCTAssertEqual(GamepadSupport.fromWire("somethingNew"), .unsupported) + XCTAssertEqual(GamepadSupport.allCases.filter(\.usable), [.ready, .failed]) + XCTAssertEqual(PadState.stick(-1), -32768) + XCTAssertEqual(PadState.stick(1), 32767) + XCTAssertEqual(PadState.stick(0.5), 16384) + XCTAssertEqual(PadState.trigger(2), 255) + XCTAssertTrue(PadState().differs(from: nil)) + XCTAssertTrue(PadState(leftX: 1).differs(from: PadState())) + XCTAssertFalse(PadState(leftX: 1000 + PadState.stickStep - 1).differs(from: PadState(leftX: 1000))) + var pending: [JSON] = [] + for e in [Input.gamepad(0, PadState(leftX: 1)), Input.gamepad(0, PadState(leftX: 2)), + Input.gamepad(0, PadState(buttons: XInput.a, leftX: 3)), Input.gamepad(1, PadState(buttons: XInput.a))] { + Input.append(&pending, e) + } + XCTAssertEqual(pending.compactMap { $0.int("leftX") }, [2, 3, 0]) + } + /// 会话事件 `privacy` 的状态(Rust 的 `PrivacyState`,camelCase);不认识的当作开不了 func testPrivacyStates() { XCTAssertEqual(PrivacyState.allCases.map(\.rawValue), ["unavailable", "notAllowed", "off", "starting", "on", "failed"]) diff --git a/ios/project.yml b/ios/project.yml index 42481214..b78f2573 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -49,6 +49,8 @@ targets: - sdk: VideoToolbox.framework - sdk: ReplayKit.framework - sdk: GameController.framework + # 手柄的震动:游戏让被控端的虚拟手柄震动时,这里接着的手柄跟着震(Gamepads.swift) + - sdk: CoreHaptics.framework - sdk: AudioToolbox.framework entitlements: path: Airhand/Airhand.entitlements From 9e064010a276ccf5b4b179110579cffae5be8d8c Mon Sep 17 00:00:00 2001 From: sqlpxc Date: Wed, 2 Dec 2026 23:18:36 +0800 Subject: [PATCH 2/3] feat(gamepads): ship usbip-win2 with the Windows installer, add an on-screen gamepad to game keys The Windows installer now carries usbip-win2, so hosts don't have to download the gamepad driver themselves, and phone game keys can be an on-screen Xbox 360 controller that is plugged into the computer like a connected gamepad. - installer: before bundling, `tauri build` runs scripts/fetch-usbip-win2.mjs (beforeBundleCommand in tauri.windows.conf.json), which downloads the pinned USBip-0.9.8.1-x64.exe and checks its SHA-256 (CI fails without it, local builds only warn and bundle without it). hooks.nsh asks once per interactive install when usbip-win2 isn't installed (x64 Windows 10 1903+, both install modes; UAC when installed just for you) and runs it very silently with /COMPONENTS=main,client /NORESTART. Silent and passive installs (updates) don't ask; /USBIP installs it without asking. An existing installation is left alone and uninstalling Airhand keeps it; its BSD license goes into usbip\. The "needs usbip-win2" hints point to the Airhand installer. - Android: gamepad buttons (pad:a ... pad:right) for keys, the D-pad and the left / right analog stick for sticks, a Gamepad (Xbox) template, a Gamepad group in the key picker, Xbox colors for A B X Y. GameControls puts the pad state together; Gamepads gives the on-screen pad a slot on first press, unplugs it when the layout has no gamepad controls left (hiding only puts it at rest), vibrates the phone on rumble (unless "vibrate on press" is off) and says why when the Gamepads switch is off or the host is too old. - iOS: the same (GameModel, GameLayer, GameEditor, Gamepads with CoreHaptics on the iPhone itself, SessionController wiring) and GameTests. - docs: usage, android, ios, building, limitations, architecture, READMEs and windows/usbip/README.md (how to update the pinned version). --- .github/workflows/release.yml | 2 + .gitignore | 3 + README.md | 2 +- README.zh-CN.md | 2 +- .../airhand/android/controller/Gamepads.kt | 111 ++++++++++++++- .../app/airhand/android/data/GameLayouts.kt | 89 +++++++++++- .../android/ui/session/GameControls.kt | 127 ++++++++++++++++-- .../airhand/android/ui/session/GameLayer.kt | 38 ++++++ .../app/airhand/android/ui/session/GameUi.kt | 70 +++++++--- .../android/ui/session/PhoneSession.kt | 3 + .../airhand/android/ui/session/RemoteView.kt | 11 ++ .../android/ui/session/SessionActivity.kt | 23 +++- .../app/src/main/res/values-zh/strings.xml | 14 +- android/app/src/main/res/values/strings.xml | 14 +- .../airhand/android/data/GameLayoutsTest.kt | 31 +++++ .../android/ui/session/GameControlsTest.kt | 97 +++++++++++++ client/scripts/fetch-usbip-win2.mjs | 80 +++++++++++ client/src-tauri/tauri.windows.conf.json | 6 +- client/src-tauri/windows/hooks.nsh | 94 +++++++++++++ client/src-tauri/windows/usbip/LICENSE.txt | 24 ++++ client/src-tauri/windows/usbip/README.md | 41 ++++++ client/src/locales/en.ts | 2 +- client/src/locales/zh.ts | 2 +- docs/android.md | 9 +- docs/android.zh-CN.md | 9 +- docs/architecture.md | 6 +- docs/architecture.zh-CN.md | 6 +- docs/building.md | 1 + docs/building.zh-CN.md | 1 + docs/ios.md | 4 +- docs/ios.zh-CN.md | 7 +- docs/limitations.md | 2 +- docs/limitations.zh-CN.md | 2 +- docs/usage.md | 8 +- docs/usage.zh-CN.md | 8 +- ios/Airhand/Controller/Gamepads.swift | 119 ++++++++++++++-- ios/Airhand/Session/GameEditor.swift | 42 ++++-- ios/Airhand/Session/GameLayer.swift | 91 ++++++++++++- ios/Airhand/Session/GameModel.swift | 98 +++++++++++++- ios/Airhand/Session/SessionController.swift | 24 ++++ ios/Airhand/Session/SessionMenu.swift | 1 + ios/Shared/L10n.swift | 20 ++- ios/Tests/GameTests.swift | 88 ++++++++++++ 43 files changed, 1326 insertions(+), 106 deletions(-) create mode 100644 client/scripts/fetch-usbip-win2.mjs create mode 100644 client/src-tauri/windows/usbip/LICENSE.txt create mode 100644 client/src-tauri/windows/usbip/README.md create mode 100644 ios/Tests/GameTests.swift diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 41b2f473..21f04759 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -156,6 +156,8 @@ jobs: - name: Set version run: node .github/scripts/set-version.mjs "$VERSION" + # 打包之前 tauri build 会下载手柄驱动 usbip-win2 的安装程序、核对 SHA-256,打进安装包(tauri.windows.conf.json 的 + # beforeBundleCommand,见 client/src-tauri/windows/usbip/README.md);CI 里下载不了就失败 - name: Build working-directory: client run: | diff --git a/.gitignore b/.gitignore index 616ed844..85230323 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,9 @@ target/ node_modules/ client/dist/ client/src-tauri/gen/ +# Windows 安装包带的 usbip-win2:打包前由 client/scripts/fetch-usbip-win2.mjs 下载(见 client/src-tauri/windows/usbip/README.md) +client/src-tauri/windows/usbip/usbip-win2-setup.exe* +client/src-tauri/windows/usbip/usbip-win2.nsh *.log web/.env # 根目录的 .env:docker-compose.yml 的变量(如固定镜像版本的 AIRHAND_VERSION) diff --git a/README.md b/README.md index 819c831e..f0a39679 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ See [How it works → Video](docs/architecture.md#video) for details. - **Android**: control computers and phones from a phone as a trackpad or touchscreen, or share your own screen to get help (a device needs the pairing code shown on the phone the first time, and you're notified whenever one connects); watch on a TV with the remote - **iPhone / iPad**: the same remote control as on Android (trackpad / touch gestures, keyboard, mouse with pointer lock on iPad, game controls), or share the screen through the system screen broadcast (view only: iOS doesn't let apps be controlled) - **Audio**: the host's system audio plays on the controller (Opus + adaptive jitter buffer), with optional A/V sync for watching videos. The other way, the controller can send its microphone to meeting apps and voice typing on Windows, macOS 14.2+ and Linux (PipeWire) hosts. Mac and Linux hosts publish **Airhand Microphone** while forwarding is on -- **Gamepads**: gamepads on the controller (desktop and web consoles, Android phones and TVs, iPhone / iPad) are plugged into Windows and Linux hosts as wired Xbox 360 controllers through [airhand-dock](https://github.com/sqlpxc/airhand-dock), so every game sees a real gamepad, and games make your gamepad vibrate. Windows hosts need [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases) installed once. [Details](docs/usage.md#gamepads) +- **Gamepads**: gamepads on the controller (desktop and web consoles, Android phones and TVs, iPhone / iPad) are plugged into Windows and Linux hosts as wired Xbox 360 controllers through [airhand-dock](https://github.com/sqlpxc/airhand-dock), so every game sees a real gamepad, and games make your gamepad vibrate. Game keys on phones can be an on-screen gamepad too. Windows hosts need the [usbip-win2](https://github.com/vadimgrn/usbip-win2) driver, which the Airhand installer includes and offers to install. [Details](docs/usage.md#gamepads) - **Handy tools**: two-way clipboard sync (text, plus files and folders, sent when you paste), typing the clipboard as keystrokes, system shortcuts (Win, Alt+Tab, Ctrl+Shift+Esc…), multiple monitors (switch between them, show and control several at once, or give each its own window to put on your own screens in full screen), keyboard lock in fullscreen, quality presets - **Secure by default**: sessions are end-to-end encrypted, so the relay server can't see the screen or keystrokes; the first connection needs the pairing code from the other computer's tray (it never goes through the server), and its identity is recognized afterwards; TLS 1.3 with certificate pinning, brute-force protection for control codes; the host always sees who is connected and can disconnect them with one click - **Leaves nothing behind**: the host is just a tray icon and doesn't start a WebView; everything worth keeping is in one `config.toml`, other runtime files are deleted on exit, and nothing is left after [uninstalling](docs/usage.md#uninstalling) (Windows has an uninstaller, where you choose whether the virtual display driver goes too; macOS has "Uninstall Airhand…" in the menu, Linux takes two commands) diff --git a/README.zh-CN.md b/README.zh-CN.md index e892b192..f73170fa 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -43,7 +43,7 @@ Airhand 是一个**高性能、低延迟**的远程桌面:画面用 GPU 硬件 - **Android**:在手机上用触控板或触屏的方式控制电脑、手机,也能共享自己的屏幕让别人协助(对方第一次连接时要输入手机上显示的配对码,有设备连上来时会提醒你);在电视上用遥控器看画面 - **iPhone / iPad**:和 Android 一样控制电脑、手机(触控板 / 触屏手势、键盘、外接鼠标,iPad 上可以锁定指针、游戏按键),也能用系统的屏幕广播共享自己的屏幕(只能被看:iOS 不允许别的应用操作本机) - **声音**:被控端的系统声音同步到控制端(Opus + 自适应抖动缓冲),看视频时可以打开音画同步。反过来,控制端的麦克风可以转发给 Windows、macOS 14.2+ 和 Linux(PipeWire)被控端,供那里的会议软件和语音输入使用。Mac 和 Linux 会在转发期间提供一个 **Airhand Microphone** 录音设备 -- **手柄**:控制端接着的手柄(桌面和网页控制台、Android 手机和电视、iPhone / iPad)经 [airhand-dock](https://github.com/sqlpxc/airhand-dock) 作为有线 Xbox 360 手柄插到 Windows、Linux 被控端上,所有游戏看到的都是真手柄,游戏的震动也传回你的手柄。Windows 被控端要先装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases)。[详情](docs/usage.zh-CN.md#手柄) +- **手柄**:控制端接着的手柄(桌面和网页控制台、Android 手机和电视、iPhone / iPad)经 [airhand-dock](https://github.com/sqlpxc/airhand-dock) 作为有线 Xbox 360 手柄插到 Windows、Linux 被控端上,所有游戏看到的都是真手柄,游戏的震动也传回你的手柄。手机上的游戏按键也可以是屏幕上的手柄。Windows 被控端要用 [usbip-win2](https://github.com/vadimgrn/usbip-win2) 驱动,Airhand 的安装包里带着,安装时会问要不要装。[详情](docs/usage.zh-CN.md#手柄) - **实用工具**:剪贴板双向同步(文字,以及文件、文件夹:粘贴时才传)、以键盘输入方式发送剪贴板、系统快捷键(Win、Alt+Tab、Ctrl+Shift+Esc……)、多显示器(可以同时显示、同时操作对方的几个显示器,也可以每个显示器单独一个窗口,放到本机的各个显示器上全屏)、全屏时锁定键盘、画质预设 - **默认安全**:会话端到端加密,中转服务器看不到画面和键盘输入;第一次连接要输入对方托盘里的配对码(不经过服务器),之后认得出对方的身份;TLS 1.3 + 证书指纹固定,控制码防暴力猜测;被控端随时能看到谁连着,一键断开 - **不留痕迹**:被控端只有一个托盘图标,不启动 WebView;要保存的东西都在一个 `config.toml` 里,其余运行时文件退出时删除;[卸载](docs/usage.zh-CN.md#卸载)后什么都不剩(Windows 用卸载程序,虚拟显示器驱动删不删由你选;macOS 在菜单里选“卸载 Airhand…”,Linux 两条命令) diff --git a/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt b/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt index 9c8ce52b..222049c0 100644 --- a/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt +++ b/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt @@ -7,9 +7,12 @@ import android.os.CombinedVibration import android.os.Handler import android.os.Looper import android.os.VibrationEffect +import android.os.Vibrator +import android.os.VibratorManager import android.view.InputDevice import android.view.KeyEvent import android.view.MotionEvent +import app.airhand.android.R import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -85,6 +88,25 @@ object XInput { KeyEvent.KEYCODE_DPAD_LEFT to DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT to DPAD_RIGHT, ) + + /** 游戏按键里手柄按钮的名字(`GameBind.PAD_BUTTONS`)→ XInput 的按钮(扳机 lt / rt 不是按钮,另外处理) */ + val NAMES: Map = mapOf( + "a" to A, + "b" to B, + "x" to X, + "y" to Y, + "lb" to LEFT_SHOULDER, + "rb" to RIGHT_SHOULDER, + "back" to BACK, + "start" to START, + "guide" to GUIDE, + "ls" to LEFT_THUMB, + "rs" to RIGHT_THUMB, + "up" to DPAD_UP, + "down" to DPAD_DOWN, + "left" to DPAD_LEFT, + "right" to DPAD_RIGHT, + ) } /** 这台设备接着的一个手柄(界面列出来) */ @@ -102,15 +124,36 @@ data class LocalPad(val pad: Int, val name: String, val rumble: Boolean) * * 交出去的事件不再给系统(方向键不会变成画面上的方向键,B 不会变成返回)。[paused] 时不拦(电视上打开菜单时用手柄选), * 返回键、主页键从来不拦; * * 震动:手柄自己的震动马达(Android 12 起每个马达单独控制,大马达是第一个),震着的时候每 [RUMBLE_REFRESH_MS] 重新放一次 - * (网页一样:一次只能放一段时间)。 + * (网页一样:一次只能放一段时间); + * * 画面上的手柄(游戏按键里的手柄按钮、摇杆,见 [screen])也是这样一个手柄:第一次按下时分一个编号,方案里不再有手柄时 + * 拔掉;游戏让它震动时手机自己震(方案里开着"按下时振动"的话)。 * * 在主线程上用(按键、轴从窗口来);[rumble] 可以从会话的线程来。 */ class Gamepads(context: Context, private val send: (events: List, now: Boolean) -> Unit) : InputManager.InputDeviceListener { + private val app = context.applicationContext private val input = context.getSystemService(Context.INPUT_SERVICE) as InputManager private val main = Handler(Looper.getMainLooper()) + /** 手机自己的振动马达:游戏让画面上的手柄震动时用 */ + private val phone: Vibrator? by lazy { + runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + app.getSystemService(VibratorManager::class.java)?.defaultVibrator + } else { + @Suppress("DEPRECATION") + app.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator + } + }.getOrNull()?.takeIf { it.hasVibrator() } + } + + /** 画面上的手柄现在的样子([screen]) */ + private var screenState = PadState() + + /** 游戏让画面上的手柄震动时手机跟着震(方案里的"按下时振动") */ + private var screenRumble = true + /** 每个编号的手柄是哪个设备([InputDevice.getId]);null = 空着 */ private val slots = arrayOfNulls(MAX_PADS) @@ -158,6 +201,9 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool /** 同时按下 Select + Start:电视上打开菜单(只用手柄的人也能出来) */ var onMenuChord: (() -> Unit)? = null + /** 按了画面上的手柄,却没有交给对方(开关关着、对方没说它能不能接):界面说一声为什么 */ + var onScreenIdle: (() -> Unit)? = null + private val refresh = object : Runnable { override fun run() { for (pad in 0 until MAX_PADS) rumbles[pad]?.let { (l, s) -> vibrate(pad, l, s) } @@ -244,6 +290,32 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool return true } + /** + * 画面上的手柄(游戏按键里的手柄按钮、摇杆)现在的样子:和接着的手柄一样占一个编号,第一次按下时分。 + * `null`:方案里不再有手柄了(关掉了游戏按键、换了方案),拔掉。收起、松开时发的是放回原位的样子,不拔掉: + * 游戏不会以为手柄断开了。[rumble]:游戏让它震动时手机跟着震 + */ + fun screen(s: PadState?, rumble: Boolean = true) { + val pad = slots.indexOf(SCREEN).takeIf { it >= 0 } + if (s == null) { + pad?.let(::free) + screenState = PadState() + return + } + if (screenRumble != rumble) { + screenRumble = rumble + if (!rumble && pad != null && rumbles[pad] != null) vibrate(pad, 0, 0) + } + screenState = s + if (!active) { + if (s.buttons != 0 || s.leftTrigger != 0 || s.rightTrigger != 0) onScreenIdle?.invoke() + return + } + // 没用过(放回原位的样子)不插 + val p = pad ?: (if (s == PadState()) null else assign(SCREEN)) ?: return + update(p, false) + } + /** 被控端让第 `pad` 个手柄震动(会话的线程上来) */ fun rumble(pad: Int, large: Int, small: Int) { if (pad !in 0 until MAX_PADS) return @@ -258,6 +330,7 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool /** 第 `pad` 个手柄现在的样子 */ private fun state(pad: Int): PadState { + if (slots[pad] == SCREEN) return screenState val a = axes[pad] ?: PadState() val t = digitalTriggers[pad] return a.copy( @@ -296,6 +369,7 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool private fun publish() { _pads.value = slots.mapIndexedNotNull { pad, id -> + if (id == SCREEN) return@mapIndexedNotNull LocalPad(pad, app.getString(R.string.gamepad_screen), phone != null) val d = id?.let { InputDevice.getDevice(it) } ?: return@mapIndexedNotNull null LocalPad(pad, d.name, hasRumble(d)) } @@ -306,7 +380,13 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool override fun onInputDeviceChanged(deviceId: Int) = publish() override fun onInputDeviceRemoved(deviceId: Int) { - val pad = slots.indexOf(deviceId).takeIf { it >= 0 } ?: return + slots.indexOf(deviceId).takeIf { it >= 0 }?.let(::free) + } + + /** 第 `pad` 个手柄拔掉了:编号空出来,告诉对方 */ + private fun free(pad: Int) { + // 手机在替画面上的手柄震:停下(接着的手柄拔掉了就不震了) + if (slots[pad] == SCREEN && rumbles[pad] != null) vibrate(pad, 0, 0) slots[pad] = null rumbles[pad] = null val wasSent = sent[pad] != null @@ -328,6 +408,10 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool private fun device(pad: Int): InputDevice? = slots[pad]?.let { InputDevice.getDevice(it) } private fun vibrate(pad: Int, large: Int, small: Int) { + if (slots[pad] == SCREEN) { + vibratePhone(if (screenRumble) max(large, small) else 0) + return + } val d = device(pad) ?: return runCatching { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { @@ -362,12 +446,35 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool } } + /** 画面上的手柄震动:手机自己的马达只有一个,按大、小马达里大的震(调不了强弱的手机只能震或者不震) */ + private fun vibratePhone(amplitude: Int) { + val v = phone ?: return + runCatching { + if (amplitude <= 0) { + v.cancel() + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + v.vibrate( + VibrationEffect.createOneShot( + RUMBLE_MS, + if (v.hasAmplitudeControl()) amplitude.coerceIn(1, 255) else VibrationEffect.DEFAULT_AMPLITUDE, + ), + ) + } else { + @Suppress("DEPRECATION") + v.vibrate(RUMBLE_MS) + } + } + } + private fun oneShot(amplitude: Int): VibrationEffect = VibrationEffect.createOneShot(RUMBLE_MS, amplitude.coerceIn(1, 255)) companion object { /** 最多同时接几个手柄(`airhand_proto::session::MAX_GAMEPADS`) */ const val MAX_PADS = 4 + /** 画面上的手柄在 [slots] 里的"设备"(真的设备的 ID 不会是负数) */ + private const val SCREEN = Int.MIN_VALUE + /** 一次震动放多久;震着的时候提前重新放 */ const val RUMBLE_MS = 5000L const val RUMBLE_REFRESH_MS = 4000L diff --git a/android/app/src/main/java/app/airhand/android/data/GameLayouts.kt b/android/app/src/main/java/app/airhand/android/data/GameLayouts.kt index 8c443b6f..b64127f7 100644 --- a/android/app/src/main/java/app/airhand/android/data/GameLayouts.kt +++ b/android/app/src/main/java/app/airhand/android/data/GameLayouts.kt @@ -15,6 +15,8 @@ import java.util.UUID /* * 游戏按键:控制电脑时叠在画面上的按钮和摇杆(见 app.airhand.android.ui.session.GameControls)。 * 只在控制端,发的是协议里已有的按键、鼠标键、滚轮和相对移动,被控端不用改。 + * 按钮、摇杆也可以是画面上的手柄(Xbox 360 手柄)的按钮、摇杆:和接着的手柄一样插到对方电脑上(见 + * app.airhand.android.controller.Gamepads),对方要能接手柄。 * * 位置是按钮中心在可用区域(视图去掉刘海、留一点边)里的比例,大小是 dp: * 换一台屏幕比例不同的手机,按钮还在相对的位置,按起来一样大。 @@ -22,29 +24,45 @@ import java.util.UUID /** * 按钮按下去发什么(一个"键"):键盘键是 W3C `KeyboardEvent.code`(`KeyW`、`ShiftLeft`), - * 鼠标键是 `mouse:left` 这样,滚轮是 `wheel:up` / `wheel:down` + * 鼠标键是 `mouse:left` 这样,滚轮是 `wheel:up` / `wheel:down`,画面上的手柄的按钮是 `pad:a` 这样 */ object GameBind { const val MOUSE = "mouse:" const val WHEEL_UP = "wheel:up" const val WHEEL_DOWN = "wheel:down" + const val PAD = "pad:" /** 和协议的 `MouseButton` 一样 */ val MOUSE_BUTTONS = listOf("left", "right", "middle", "back", "forward") + /** + * 画面上的手柄(Xbox 360 手柄)的按钮:A B X Y、肩键 LB RB、扳机 LT RT(按着就是按到底)、Back Start、西瓜键、 + * 按下摇杆 LS RS、方向键。XInput 的按钮位见 [app.airhand.android.controller.XInput.NAMES] + */ + val PAD_BUTTONS = listOf("a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "guide", "ls", "rs", "up", "down", "left", "right") + /** 摇杆的四个方向:上、左、下、右 */ val WASD = listOf("KeyW", "KeyA", "KeyS", "KeyD") val ARROWS = listOf("ArrowUp", "ArrowLeft", "ArrowDown", "ArrowRight") + /** 手柄的方向键(摇杆按方向键,8 个方向) */ + val DPAD = listOf(pad("up"), pad("left"), pad("down"), pad("right")) + /** 一个按钮最多同时按几个键(组合键) */ const val MAX_BINDS = 3 fun mouse(button: String) = MOUSE + button + fun pad(button: String) = PAD + button + /** 鼠标键的名字(`left`…);不是鼠标键时为 null */ fun mouseButton(token: String): String? = if (token.startsWith(MOUSE)) token.removePrefix(MOUSE).takeIf { it in MOUSE_BUTTONS } else null + /** 手柄按钮的名字(`a`、`lt`…);不是手柄的按钮时为 null */ + fun padButton(token: String): String? = + if (token.startsWith(PAD)) token.removePrefix(PAD).takeIf { it in PAD_BUTTONS } else null + /** 滚轮转一格(120 = 向上,和协议一样);不是滚轮时为 0 */ fun wheel(token: String): Int = when (token) { WHEEL_UP -> 120 @@ -52,9 +70,9 @@ object GameBind { else -> 0 } - /** 认得的键:鼠标键、滚轮,或者像 W3C code 那样只有字母数字的键名(不认识的键被控端自己会跳过) */ + /** 认得的键:鼠标键、滚轮、手柄的按钮,或者像 W3C code 那样只有字母数字的键名(不认识的键被控端自己会跳过) */ fun valid(token: String): Boolean = - mouseButton(token) != null || wheel(token) != 0 || + mouseButton(token) != null || wheel(token) != 0 || padButton(token) != null || (token.length in 1..32 && token.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' }) } @@ -86,6 +104,19 @@ sealed interface GameControl { fun sized(size: Float): GameControl fun withId(id: Int): GameControl fun toJson(): JSONObject + + /** 用到了画面上的手柄(手柄的按钮、方向键、摇杆) */ + val usesPad: Boolean +} + +/** 摇杆是画面上的手柄的哪一个摇杆:推多远发多远(模拟量),不按键 */ +enum class PadStick(val id: String) { + LEFT("left"), + RIGHT("right"); + + companion object { + fun of(id: String?) = entries.firstOrNull { it.id == id } + } } /** @@ -106,6 +137,7 @@ data class GameKey( override fun at(x: Float, y: Float) = copy(x = x.coerceIn(0f, 1f), y = y.coerceIn(0f, 1f)) override fun sized(size: Float) = copy(size = size.coerceIn(MIN, MAX)) override fun withId(id: Int) = copy(id = id) + override val usesPad: Boolean get() = binds.any { GameBind.padButton(it) != null } override fun toJson(): JSONObject = JSONObject() .put("type", "key") @@ -129,8 +161,9 @@ data class GameKey( } /** - * 摇杆:推向哪边就按着哪个方向的键,斜着推按两个(8 个方向)。[keys] 是上、左、下、右。 - * [sprint]:推出边缘再往外时加按的键(例如 Shift 奔跑),null 表示不加。 + * 摇杆:推向哪边就按着哪个方向的键,斜着推按两个(8 个方向)。[keys] 是上、左、下、右(也可以是手柄的方向键 [GameBind.DPAD])。 + * [analog] 不为 null 时是画面上的手柄的左 / 右摇杆:推多远发多远,不按 [keys](还是存着:旧版本读到时当作 WASD 摇杆)。 + * [sprint]:推出边缘再往外时加按的键(例如 Shift 奔跑、按下摇杆),null 表示不加。 * [floating]:中心落在手指按下的地方(不用正好按在中间) */ data class GameStick( @@ -141,10 +174,22 @@ data class GameStick( val keys: List = GameBind.WASD, val sprint: String? = null, val floating: Boolean = true, + val analog: PadStick? = null, ) : GameControl { override fun at(x: Float, y: Float) = copy(x = x.coerceIn(0f, 1f), y = y.coerceIn(0f, 1f)) override fun sized(size: Float) = copy(size = size.coerceIn(MIN, MAX)) override fun withId(id: Int) = copy(id = id) + override val usesPad: Boolean + get() = analog != null || keys.any { GameBind.padButton(it) != null } || sprint?.let(GameBind::padButton) != null + + /** 推出边缘时可以加按的键:手柄的摇杆是按下摇杆(LS / RS),别的是 Shift、Ctrl、Alt */ + val sprintKeys: List get() = if (analog != null) PAD_SPRINT_KEYS else SPRINT_KEYS + + /** 换成按 [keys] 的摇杆,或者手柄的摇杆([analog]);加按的键换了一种摇杆就不合适了,去掉 */ + fun kind(keys: List, analog: PadStick?): GameStick { + val s = copy(keys = keys, analog = analog) + return if (sprint == null || sprint in s.sprintKeys) s else s.copy(sprint = null) + } override fun toJson(): JSONObject = JSONObject() .put("type", "stick") @@ -155,6 +200,7 @@ data class GameStick( .put("keys", JSONArray(keys)) .put("sprint", sprint ?: JSONObject.NULL) .put("floating", floating) + .put("analog", analog?.id ?: JSONObject.NULL) companion object { const val MIN = 100f @@ -163,6 +209,9 @@ data class GameStick( /** 摇杆推出边缘时可以加按的键 */ val SPRINT_KEYS = listOf("ShiftLeft", "ControlLeft", "AltLeft") + + /** 手柄的摇杆推出边缘时可以加按的:按下左 / 右摇杆(很多游戏是奔跑) */ + val PAD_SPRINT_KEYS = listOf(GameBind.pad("ls"), GameBind.pad("rs")) } } @@ -180,6 +229,9 @@ data class GameLayout( ) { fun control(id: Int): GameControl? = controls.firstOrNull { it.id == id } fun nextId(): Int = (controls.maxOfOrNull { it.id } ?: 0) + 1 + + /** 有画面上的手柄的按钮、摇杆(没有了的话拔掉画面上的手柄) */ + val usesPad: Boolean get() = controls.any { it.usesPad } fun with(c: GameControl) = copy(controls = controls.map { if (it.id == c.id) c else it }) fun without(id: Int) = copy(controls = controls.filter { it.id != id }) fun plus(c: GameControl) = copy(controls = controls + c) @@ -244,6 +296,7 @@ data class GameLayout( keys = if (keys.size == 4 && keys.all(GameBind::valid)) keys else GameBind.WASD, sprint = o.optStringOrNull("sprint")?.takeIf(GameBind::valid), floating = o.optBoolean("floating", true), + analog = PadStick.of(o.optStringOrNull("analog")), ) } else -> null @@ -266,6 +319,7 @@ enum class GameTemplate(@StringRes val title: Int, @StringRes val desc: Int) { SHOOTER(R.string.game_tpl_shooter, R.string.game_tpl_shooter_desc), SKILLS(R.string.game_tpl_skills, R.string.game_tpl_skills_desc), ARROWS(R.string.game_tpl_arrows, R.string.game_tpl_arrows_desc), + GAMEPAD(R.string.game_tpl_gamepad, R.string.game_tpl_gamepad_desc), BLANK(R.string.game_tpl_blank, R.string.game_tpl_blank_desc); fun controls(): List { @@ -277,6 +331,12 @@ enum class GameTemplate(@StringRes val title: Int, @StringRes val desc: Int) { fun stick(x: Float, y: Float, keys: List, sprint: String?) { out += GameStick(out.size + 1, x, y, GameStick.DEFAULT, keys, sprint) } + + fun pad(x: Float, y: Float, size: Float, button: String) = key(x, y, size, GameBind.pad(button)) + + fun analog(x: Float, y: Float, size: Float, which: PadStick) { + out += GameStick(out.size + 1, x, y, size, analog = which) + } when (this) { SHOOTER -> { stick(0.15f, 0.68f, GameBind.WASD, "ShiftLeft") @@ -315,6 +375,25 @@ enum class GameTemplate(@StringRes val title: Int, @StringRes val desc: Int) { key(0.44f, 0.10f, 48f, "Escape") key(0.56f, 0.10f, 48f, "Enter") } + GAMEPAD -> { + // 和 Xbox 手柄一样:左手左摇杆、方向键,右手 A B X Y、右摇杆,肩键扳机在上面两角,Back / 西瓜键 / Start 在中间 + analog(0.12f, 0.58f, 140f, PadStick.LEFT) + out += GameStick(out.size + 1, 0.30f, 0.80f, 110f, GameBind.DPAD, floating = false) + analog(0.64f, 0.80f, 110f, PadStick.RIGHT) + pad(0.875f, 0.76f, 54f, "a") + pad(0.949f, 0.60f, 54f, "b") + pad(0.801f, 0.60f, 54f, "x") + pad(0.875f, 0.44f, 54f, "y") + pad(0.06f, 0.11f, 50f, "lt") + pad(0.15f, 0.11f, 50f, "lb") + pad(0.82f, 0.11f, 50f, "rb") + pad(0.91f, 0.11f, 50f, "rt") + pad(0.42f, 0.11f, 40f, "back") + pad(0.50f, 0.11f, 40f, "guide") + pad(0.58f, 0.11f, 40f, "start") + pad(0.27f, 0.45f, 42f, "ls") + pad(0.52f, 0.66f, 42f, "rs") + } BLANK -> {} } return out 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..a04fad72 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 @@ -2,12 +2,15 @@ package app.airhand.android.ui.session import androidx.annotation.StringRes import app.airhand.android.R +import app.airhand.android.controller.PadState +import app.airhand.android.controller.XInput import app.airhand.android.data.GameBind import app.airhand.android.data.GameControl import app.airhand.android.data.GameKey import app.airhand.android.data.GameLayout import app.airhand.android.data.GameStick import app.airhand.android.data.KeyMode +import app.airhand.android.data.PadStick import kotlin.math.hypot /** @@ -78,6 +81,8 @@ class GameGeometry(val density: Float) { * * 按钮:按住就按着键(组合键按顺序按下、倒序松开),或者点一下切换;滚轮按着会一格一格地转下去; * 可以转视角的按钮(开火)按着拖动时发相对移动,一边开火一边瞄准; * * 摇杆:8 个方向,方向边界和死区都有回差,手指在边界上抖不会让键来回按;推出边缘再往外加按一个键(奔跑); + * * 画面上的手柄([GameBind.PAD] 的按钮、手柄的摇杆):按钮和键一样按着、松开,扳机按着是按到底;手柄的摇杆推多远发多远 + * (中间一点死区,推到边缘是推到底)。手柄有变化就把它整个现在的样子交出去([Out.pad]),由 Gamepads 插到对方电脑上; * * 同一个键被几处按着(摇杆的 W 和一个 W 按钮)时数着:都松开才松开,不会提前松掉; * * 一个手指从按下到抬起都归同一个按钮:开火时手指滑出按钮也不会松开。 * @@ -96,6 +101,9 @@ class GameControls( /** 转视角:手指移动了多少(视图像素),由接收方乘上灵敏度、换算成被控端的移动量 */ fun look(dx: Float, dy: Float) + + /** 画面上的手柄现在的样子(变了才给) */ + fun pad(state: PadState) fun haptic() /** 要重画(按下、松开、摇杆动了);按着的鼠标键也可能变了([holdsMouse]) */ @@ -118,12 +126,17 @@ class GameControls( var repeat: Any? = null } - /** 摇杆上的手指:(`cx`, `cy`) 是这一次的中心(浮动摇杆是按下的地方),(`x`, `y`) 是手指 */ + /** + * 摇杆上的手指:(`cx`, `cy`) 是这一次的中心(浮动摇杆是按下的地方),(`x`, `y`) 是手指。 + * 手柄的摇杆:(`ax`, `ay`) 是推到哪里(-1..1,Y 向上为正) + */ private class StickTouch(val stick: GameStick, val cx: Float, val cy: Float) { var x = cx var y = cy val dirs = BooleanArray(4) var sprint = false + var ax = 0f + var ay = 0f } /** 手指(MotionEvent 的 pointer id)→ 它按着的按钮 */ @@ -135,6 +148,9 @@ class GameControls( /** 按着的键 → 几处按着 */ private val held = HashMap() + /** 最近交出去的画面上的手柄的样子 */ + private var padSent = PadState() + /** 这个手指归游戏按键 */ fun owns(pointer: Int) = pointer in touches @@ -229,14 +245,17 @@ class GameControls( out.changed() } - /** 全部松开:手指按着的、切换着的,再加上万一漏掉的 */ + /** 全部松开:手指按着的、切换着的,再加上万一漏掉的;画面上的手柄放回原位 */ fun releaseAll() { touches.values.toList().forEach(::endTouch) touches.clear() latched.values.toList().forEach(::releaseBinds) latched.clear() - for (token in held.keys.toList()) emit(token, false) - held.clear() + for (token in held.keys.toList()) { + held.remove(token) + emit(token, false) + } + pushPad() out.changed() } @@ -252,6 +271,11 @@ class GameControls( for (i in 3 downTo 0) if (t.dirs[i]) release(t.stick.keys[i]) t.sprint = false t.dirs.fill(false) + if (t.stick.analog != null && (t.ax != 0f || t.ay != 0f)) { + t.ax = 0f + t.ay = 0f + pushPad() + } } } } @@ -268,7 +292,7 @@ class GameControls( return if (c is GameStick) r * 0.3f else maxOf(r * 0.15f, 6 * geo.density) } - /** 摇杆:按手指相对中心的方向决定按着哪几个方向键 */ + /** 摇杆:按手指相对中心的方向决定按着哪几个方向键;手柄的摇杆按手指离中心多远、往哪边推 */ private fun steer(t: StickTouch, x: Float, y: Float) { t.x = x t.y = y @@ -278,13 +302,20 @@ class GameControls( val d = hypot(vx, vy) val active = t.dirs.any { it } val want = BooleanArray(4) - if (d > r * (if (active) DEAD_OUT else DEAD_IN)) { + val analog = t.stick.analog != null + if (analog) { + // 死区以外按比例到边缘(推到边缘是推到底);Y 向上为正 + val m = if (d <= r * ANALOG_DEAD || r <= 0f) 0f else ((d / r).coerceAtMost(1f) - ANALOG_DEAD) / (1f - ANALOG_DEAD) + t.ax = if (m > 0f) vx / d * m else 0f + t.ay = if (m > 0f) -vy / d * m else 0f + } else if (d > r * (if (active) DEAD_OUT else DEAD_IN)) { // 上、左、下、右方向上的分量(单位向量) val comp = floatArrayOf(-vy / d, -vx / d, vy / d, vx / d) for (i in 0..3) want[i] = comp[i] > if (t.dirs[i]) AXIS_OUT else AXIS_IN } val sprintKey = t.stick.sprint - val sprint = sprintKey != null && want.any { it } && d > r * (if (t.sprint) SPRINT_OUT else SPRINT_IN) + val pushed = if (analog) t.ax != 0f || t.ay != 0f else want.any { it } + val sprint = sprintKey != null && pushed && d > r * (if (t.sprint) SPRINT_OUT else SPRINT_IN) // 先松开再按下:手指一下子从上甩到下时先松 W 再按 S,不会两个一起按着 if (t.sprint && !sprint) sprintKey?.let(::release) for (i in 0..3) if (t.dirs[i] && !want[i]) release(t.stick.keys[i]) @@ -295,6 +326,43 @@ class GameControls( } want.copyInto(t.dirs) t.sprint = sprint + if (analog) pushPad() + } + + /** 画面上的手柄现在的样子:按着的手柄按钮、扳机,手柄的摇杆推到哪里(同一边有两个摇杆按着时加起来)。变了才交出去 */ + private fun pushPad() { + var buttons = 0 + var lt = 0 + var rt = 0 + for (token in held.keys) { + when (val b = GameBind.padButton(token) ?: continue) { + "lt" -> lt = 255 + "rt" -> rt = 255 + else -> buttons = buttons or (XInput.NAMES[b] ?: 0) + } + } + var lx = 0f + var ly = 0f + var rx = 0f + var ry = 0f + for (t in touches.values) { + if (t !is StickTouch) continue + when (t.stick.analog) { + PadStick.LEFT -> { + lx += t.ax + ly += t.ay + } + PadStick.RIGHT -> { + rx += t.ax + ry += t.ay + } + null -> {} + } + } + val s = PadState(buttons, lt, rt, PadState.stick(lx), PadState.stick(ly), PadState.stick(rx), PadState.stick(ry)) + if (s == padSent) return + padSent = s + out.pad(s) } private fun pressBinds(binds: List) { @@ -325,6 +393,10 @@ class GameControls( } private fun emit(token: String, down: Boolean) { + if (GameBind.padButton(token) != null) { + pushPad() + return + } val b = GameBind.mouseButton(token) if (b != null) out.button(b, down) else out.key(token, down) } @@ -342,6 +414,9 @@ class GameControls( const val SPRINT_IN = 1.15f const val SPRINT_OUT = 1.0f + /** 手柄的摇杆中间的死区(半径的比例):拇指放着不动、轻轻一碰不算推 */ + const val ANALOG_DEAD = 0.06f + /** 按着滚轮按钮:多久之后开始一格一格地转,之后每格隔多久 */ const val WHEEL_DELAY_MS = 350L const val WHEEL_REPEAT_MS = 110L @@ -367,6 +442,14 @@ object GameKeys { R.string.game_group_numpad, (0..9).map { "Numpad$it" } + listOf("NumpadAdd", "NumpadSubtract", "NumpadMultiply", "NumpadDivide", "NumpadDecimal", "NumpadEnter"), ), + Group(R.string.game_group_pad, GameBind.PAD_BUTTONS.map(GameBind::pad)), + ) + + /** 手柄的按钮上写的(和 Xbox 手柄一样);方向键前面加个 D,和键盘的方向键分开 */ + private val PAD_NAMES = mapOf( + "a" to "A", "b" to "B", "x" to "X", "y" to "Y", "lb" to "LB", "rb" to "RB", "lt" to "LT", "rt" to "RT", + "back" to "Back", "start" to "Start", "guide" to "Xbox", "ls" to "LS", "rs" to "RS", + "up" to "D↑", "down" to "D↓", "left" to "D←", "right" to "D→", ) private val NAMES = mapOf( @@ -398,6 +481,7 @@ object GameKeys { GameBind.WHEEL_UP -> return text(R.string.game_wheel_up) GameBind.WHEEL_DOWN -> return text(R.string.game_wheel_down) } + GameBind.padButton(token)?.let { return PAD_NAMES[it] ?: it } NAMES[token]?.let { return it } return when { token.startsWith("Key") && token.length == 4 -> token.substring(3) @@ -413,13 +497,23 @@ object GameKeys { /** 按钮上显示的字:自己写的,或者按键名 */ fun caption(k: GameKey, text: (Int) -> String): String = k.label.ifBlank { label(k.binds, text) } - /** 摇杆四个方向的名字(上、左、下、右):W A S D,方向键用箭头 */ - fun stickLabels(s: GameStick, text: (Int) -> String): List = s.keys.map { label(it, text) } + /** 摇杆四个方向的名字(上、左、下、右):W A S D,方向键用箭头,手柄的方向键用三角;手柄的摇杆没有 */ + fun stickLabels(s: GameStick, text: (Int) -> String): List = when { + s.analog != null -> emptyList() + s.keys == GameBind.DPAD -> listOf("▲", "◀", "▼", "▶") + else -> s.keys.map { label(it, text) } + } + + /** 手柄的摇杆头上写的:L / R */ + fun analogLabel(s: GameStick): String = if (s.analog == PadStick.RIGHT) "R" else "L" - /** 摇杆是哪一种:WASD / 方向键 / 别的 */ - fun stickName(s: GameStick, text: (Int) -> String): String = when (s.keys) { - GameBind.WASD -> "WASD" - GameBind.ARROWS -> "↑←↓→" + /** 摇杆是哪一种:WASD / 方向键 / 手柄的方向键、左右摇杆 / 别的 */ + fun stickName(s: GameStick, text: (Int) -> String): String = when { + s.analog == PadStick.LEFT -> text(R.string.game_pad_left_stick) + s.analog == PadStick.RIGHT -> text(R.string.game_pad_right_stick) + s.keys == GameBind.DPAD -> text(R.string.game_pad_dpad) + s.keys == GameBind.WASD -> "WASD" + s.keys == GameBind.ARROWS -> "↑←↓→" else -> stickLabels(s, text).joinToString("") } @@ -428,7 +522,12 @@ object GameKeys { l.controls.joinToString(" · ") { when (it) { is GameKey -> caption(it, text) - is GameStick -> text(R.string.game_stick) + " " + stickName(it, text) + // 手柄的摇杆、方向键:名字里已经说了是什么 + is GameStick -> if (it.analog != null || it.keys == GameBind.DPAD) { + stickName(it, text) + } else { + text(R.string.game_stick) + " " + stickName(it, text) + } } } diff --git a/android/app/src/main/java/app/airhand/android/ui/session/GameLayer.kt b/android/app/src/main/java/app/airhand/android/ui/session/GameLayer.kt index 022f2508..0e31ecff 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/GameLayer.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/GameLayer.kt @@ -8,6 +8,7 @@ import android.graphics.DashPathEffect import android.graphics.Paint import android.graphics.Typeface import android.view.View +import app.airhand.android.data.GameBind import app.airhand.android.data.GameControl import app.airhand.android.data.GameKey import app.airhand.android.data.GameLayout @@ -21,6 +22,7 @@ import kotlin.math.max * * 平时:半透明的圆按钮,按下时变成主题色、稍微缩一点;切换着的按钮外面一圈主题色; * 能转视角的按钮下面有个小准星,点一下切换的按钮上面有个小圆点; * 摇杆是一个大圆加四个方向的键名,按着时圆心跟着手指落下的地方,按着的方向亮起来,推出边缘时外圈亮起来; + * 手柄的摇杆没有键名,里面一圈虚线,摇杆头上写着 L / R;手柄的 A B X Y 用 Xbox 手柄上的颜色; * * 编辑时:画面压暗、铺一层点阵,按钮都有虚线框,选中的是主题色的框,拖动时画出对齐的辅助线 */ @SuppressLint("ViewConstructor") @@ -160,8 +162,11 @@ class GameLayer(context: Context, private val view: RemoteView) : View(context) val w = text.measureText(label) val maxW = r0 * 1.5f if (w > maxW) text.textSize *= maxW / w + // 手柄的 A B X Y:和 Xbox 手柄上一样的颜色(按下时底是主题色,字还是白的) + text.color = if (pressed || k.label.isNotBlank()) Color.WHITE else padColor(k.binds) ?: Color.WHITE text.alpha = (255 * max(a, 0.45f)).toInt() canvas.drawText(label, cx, cy - (text.descent() + text.ascent()) / 2, text) + text.color = Color.WHITE // 能转视角:下面一个小准星 if (k.look) { val y = cy + r0 * 0.62f @@ -214,6 +219,10 @@ class GameLayer(context: Context, private val view: RemoteView) : View(context) line.color = Color.WHITE line.alpha = (255 * a * 0.6f).toInt() canvas.drawCircle(bx, by, r, line) + if (s.analog != null) { + drawAnalog(canvas, s, a, st, bx, by, r) + return + } // 四个方向的键名,按着的亮起来 val labels = GameKeys.stickLabels(s, str) val offs = arrayOf(0f to -1f, -1f to 0f, 0f to 1f, 1f to 0f) @@ -238,8 +247,37 @@ class GameLayer(context: Context, private val view: RemoteView) : View(context) canvas.drawCircle(kx, ky, r * 0.36f, fill) } + /** 手柄的摇杆:里面一圈虚线(推多远发多远,没有方向键),摇杆头上写着 L / R */ + private fun drawAnalog(canvas: Canvas, s: GameStick, a: Float, st: GameControls.StickState?, bx: Float, by: Float, r: Float) { + line.pathEffect = dash + line.strokeWidth = 1.2f * d + line.alpha = (255 * a * 0.45f).toInt() + canvas.drawCircle(bx, by, r * 0.62f, line) + line.pathEffect = null + val kx = st?.kx ?: bx + val ky = st?.ky ?: by + val kr = r * 0.36f + fill.color = Color.WHITE + fill.alpha = (255 * max(a, 0.4f) * (if (st != null) 0.85f else 0.55f)).toInt() + canvas.drawCircle(kx, ky, kr, fill) + text.color = Color.BLACK + text.alpha = (255 * max(a, 0.5f) * 0.8f).toInt() + text.textSize = kr * 0.9f + canvas.drawText(GameKeys.analogLabel(s), kx, ky - (text.descent() + text.ascent()) / 2, text) + text.color = Color.WHITE + } + companion object { /** 主题色([app.airhand.android.ui.theme.Brand.accent]) */ private val ACCENT = Color.rgb(0x5B, 0x7C, 0xFF) + + /** Xbox 手柄上 A B X Y 的颜色(按钮只按其中一个时) */ + private fun padColor(binds: List): Int? = when (binds.singleOrNull()?.let(GameBind::padButton)) { + "a" -> Color.rgb(0x7E, 0xD3, 0x21) + "b" -> Color.rgb(0xFF, 0x5A, 0x4E) + "x" -> Color.rgb(0x4A, 0xA8, 0xFF) + "y" -> Color.rgb(0xFF, 0xD0, 0x2E) + else -> null + } } } 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..58efbbf2 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 @@ -95,6 +95,7 @@ import app.airhand.android.data.GameLayout 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.ui.ConfirmDialog import app.airhand.android.ui.EditTextDialog import kotlin.math.ln @@ -367,9 +368,10 @@ fun GameEditOverlay(ed: LayoutEditor, onCancel: () -> Unit, onDone: () -> Unit) null -> {} Pick.Add -> KeyPicker( initial = emptyList(), - onStick = { keys -> + onStick = { keys, analog -> pick = null - ed.add { id -> GameStick(id, 0.5f, 0.5f, keys = keys) } + // 方向键不浮动:和手柄上的一样按在哪个方向就是哪个 + ed.add { id -> GameStick(id, 0.5f, 0.5f, keys = keys, analog = analog, floating = keys != GameBind.DPAD) } }, onPick = { binds -> pick = null @@ -564,6 +566,7 @@ private fun ColumnScope.ControlPanel(ed: LayoutEditor, c: GameControl, onPick: ( } TextButton(onClick = onPick) { Text(stringResource(R.string.game_change)) } } + if (c.usesPad) PadNote() ValueRow(stringResource(R.string.game_label), c.label.ifBlank { stringResource(R.string.game_label_auto, GameKeys.label(c.binds, text)) }) { labeling = true } @@ -588,18 +591,17 @@ private fun ColumnScope.ControlPanel(ed: LayoutEditor, c: GameControl, onPick: ( } is GameStick -> { FieldLabel(stringResource(R.string.game_stick_keys)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - FilterChip( - selected = c.keys == GameBind.WASD, - onClick = { ed.update(c.id) { (it as GameStick).copy(keys = GameBind.WASD) } }, - label = { Text("W A S D") }, - ) - FilterChip( - selected = c.keys == GameBind.ARROWS, - onClick = { ed.update(c.id) { (it as GameStick).copy(keys = GameBind.ARROWS) } }, - label = { Text("↑ ← ↓ →") }, - ) + // 键盘的 WASD / 方向键,画面上的手柄的方向键 / 左摇杆 / 右摇杆 + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + StickKinds.forEach { (keys, analog, title) -> + FilterChip( + selected = if (analog != null) c.analog == analog else c.analog == null && c.keys == keys, + onClick = { ed.update(c.id) { (it as GameStick).kind(keys, analog) } }, + label = { Text(title ?: stringResource(stickKindTitle(analog))) }, + ) + } } + if (c.usesPad) PadNote() FieldLabel(stringResource(R.string.game_sprint)) FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { FilterChip( @@ -607,7 +609,7 @@ private fun ColumnScope.ControlPanel(ed: LayoutEditor, c: GameControl, onPick: ( onClick = { ed.update(c.id) { (it as GameStick).copy(sprint = null) } }, label = { Text(stringResource(R.string.game_sprint_none)) }, ) - GameStick.SPRINT_KEYS.forEach { k -> + c.sprintKeys.forEach { k -> FilterChip( selected = c.sprint == k, onClick = { ed.update(c.id) { (it as GameStick).copy(sprint = k) } }, @@ -652,6 +654,32 @@ private fun ColumnScope.ControlPanel(ed: LayoutEditor, c: GameControl, onPick: ( } } +/** 摇杆的几种:按哪几个键(手柄的摇杆不按键)、手柄的哪个摇杆、显示的名字(null 用 [stickKindTitle]) */ +private val StickKinds: List, PadStick?, String?>> = listOf( + Triple(GameBind.WASD, null, "W A S D"), + Triple(GameBind.ARROWS, null, "↑ ← ↓ →"), + Triple(GameBind.DPAD, null, null), + Triple(GameBind.WASD, PadStick.LEFT, null), + Triple(GameBind.WASD, PadStick.RIGHT, null), +) + +private fun stickKindTitle(analog: PadStick?): Int = when (analog) { + PadStick.LEFT -> R.string.game_pad_left_stick + PadStick.RIGHT -> R.string.game_pad_right_stick + null -> R.string.game_pad_dpad +} + +/** 手柄的按钮、摇杆:说一声它们发给对方电脑上的虚拟手柄,对方要能接手柄 */ +@Composable +private fun PadNote() { + Text( + stringResource(R.string.game_pad_note), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp, end = 8.dp), + ) +} + /** 转视角灵敏度的滑块按对数走:0.25× … 1× … 4×,1× 在正中间 */ private fun lookToSlider(v: Float) = ln(v / GameLayout.MIN_LOOK) / ln(GameLayout.MAX_LOOK / GameLayout.MIN_LOOK) @@ -697,13 +725,13 @@ private fun ColumnScope.LayoutPanel(ed: LayoutEditor) { /** * 选键:平时点一个键就选好了;打开"组合键"之后可以按顺序点最多 3 个(一起按下,例如 Ctrl+1),再点"确定"。 - * [onStick] 不为 null 时(添加)最上面还有摇杆 + * [onStick] 不为 null 时(添加)最上面还有摇杆(按哪几个键、手柄的哪个摇杆);最下面是画面上的手柄的按钮 */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable private fun KeyPicker( initial: List, - onStick: ((List) -> Unit)?, + onStick: ((keys: List, analog: PadStick?) -> Unit)?, onPick: (List) -> Unit, onDismiss: () -> Unit, ) { @@ -754,9 +782,12 @@ private fun KeyPicker( } if (onStick != null && !combo) { GroupTitle(stringResource(R.string.game_stick)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - KeyCap(stringResource(R.string.game_stick) + " · WASD") { onStick(GameBind.WASD) } - KeyCap(stringResource(R.string.game_stick) + " · ↑←↓→") { onStick(GameBind.ARROWS) } + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + KeyCap(stringResource(R.string.game_stick) + " · WASD") { onStick(GameBind.WASD, null) } + KeyCap(stringResource(R.string.game_stick) + " · ↑←↓→") { onStick(GameBind.ARROWS, null) } + KeyCap(stringResource(R.string.game_pad_dpad)) { onStick(GameBind.DPAD, null) } + KeyCap(stringResource(R.string.game_pad_left_stick)) { onStick(GameBind.WASD, PadStick.LEFT) } + KeyCap(stringResource(R.string.game_pad_right_stick)) { onStick(GameBind.WASD, PadStick.RIGHT) } } } GameKeys.groups.forEach { g -> @@ -843,6 +874,7 @@ fun GameTips(onDone: () -> Unit) { R.string.game_tip_stick to R.string.game_tip_stick_desc, R.string.game_tip_look to R.string.game_tip_look_desc, R.string.game_tip_aim to R.string.game_tip_aim_desc, + R.string.game_tip_pad to R.string.game_tip_pad_desc, ).forEach { (g, a) -> Row(Modifier.padding(horizontal = 24.dp, vertical = 6.dp)) { Text(stringResource(g), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.SemiBold, modifier = Modifier.width(130.dp)) 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 c6bec38b..77fecce3 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 @@ -263,6 +263,9 @@ fun PhoneSession( val live = phase == RemoteSession.Phase.Live && video != null val showGame = gameOn && live && !covered && !imeVisible && editor == null LaunchedEffect(showGame, gameLayout) { view.setGame(if (showGame) gameLayout else null) } + // 画面上的手柄:只是收起时放回原位、不拔掉(游戏不会以为手柄断开了);关掉游戏按键、换成没有手柄的方案时拔掉 + val padLayout = gameOn && gameLayout?.usesPad == true + LaunchedEffect(padLayout) { if (!padLayout) view.screenPadGone() } // 被控端的提示(采集失败、不能操作……)和本机的问题 val messages = notices.entries.filter { it.key !in dismissed }.map { it.key to Messages.notice(ctx, it.value, os) } + diff --git a/android/app/src/main/java/app/airhand/android/ui/session/RemoteView.kt b/android/app/src/main/java/app/airhand/android/ui/session/RemoteView.kt index bcbaf476..0854afba 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/RemoteView.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/RemoteView.kt @@ -33,6 +33,7 @@ import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import app.airhand.android.controller.CursorState import app.airhand.android.controller.Input +import app.airhand.android.controller.PadState import app.airhand.android.data.GameLayout import app.airhand.android.data.GameStick import app.airhand.android.data.ScaleMode @@ -66,6 +67,12 @@ class RemoteView(context: Context, private val host: Host) : FrameLayout(context fun onZoom(zoomed: Boolean, shownW: Float, shownH: Float) fun onInput(events: List, now: Boolean) fun onToggleKeyboard() + + /** + * 游戏按键里画面上的手柄现在的样子(交给 Gamepads,和接着的手柄一样插到对方电脑上);null:方案里没有手柄了,拔掉。 + * [rumble]:游戏让它震动时手机跟着震(方案里的"按下时振动") + */ + fun onScreenPad(state: PadState?, rumble: Boolean) val keyboard: KeyboardController } @@ -144,6 +151,7 @@ class RemoteView(context: Context, private val host: Host) : FrameLayout(context override fun button(button: String, down: Boolean) = host.onInput(listOf(Input.button(button, down)), true) override fun wheel(dy: Int) = host.onInput(listOf(Input.wheel(0, dy)), true) override fun look(dx: Float, dy: Float) = lookBy(dx, dy) + override fun pad(state: PadState) = host.onScreenPad(state, game.layout?.haptics != false) override fun haptic() { performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) } @@ -703,6 +711,9 @@ class RemoteView(context: Context, private val host: Host) : FrameLayout(context updateGestureExclusion() } + /** 画面上的手柄不用了(关掉了游戏按键、换了没有手柄的方案):对方拔掉它。只是收起(打开键盘、编辑)时不拔 */ + fun screenPadGone() = host.onScreenPad(null, false) + /** * 摇杆、贴着屏幕边的按钮不让系统的返回手势抢走(Android 10+ 的手势导航:从左右边缘滑入是返回, * 拇指推摇杆时很容易碰到)。系统每条边最多让出 200dp,从下往上算,摇杆一般在下面 diff --git a/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt b/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt index a99be678..ecaaa68f 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt @@ -58,6 +58,7 @@ import androidx.lifecycle.lifecycleScope import app.airhand.android.AirhandApp import app.airhand.android.R import app.airhand.android.controller.Gamepads +import app.airhand.android.controller.PadState import app.airhand.android.controller.RemoteSession import app.airhand.android.core.Code import app.airhand.android.core.DisplayInfo @@ -166,7 +167,8 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { /** * 手柄:会话连着、对方说了它能不能接、开关打开、界面在前台时拦下手柄的输入:对方能接就发给它, - * 接不了就在按下按钮时说一声为什么(每次对方的说法变了只说一次)。游戏让它震动时这里跟着震 + * 接不了就在按下按钮时说一声为什么(每次对方的说法变了只说一次)。游戏让它震动时这里跟着震。 + * 游戏按键里画面上的手柄也交给它([onScreenPad]):开关关着、对方没说它能不能接(旧版本)时按下也说一声 */ private fun startGamepads(s: RemoteSession): Gamepads { val pads = Gamepads(this) { events, now -> s.gamepad(events, now) } @@ -182,6 +184,19 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { Toast.makeText(this, getString(R.string.gamepad_refused, hint), Toast.LENGTH_LONG).show() } } + var screenTold = false + pads.onScreenIdle = { + val text = when { + s.phase.value != RemoteSession.Phase.Live -> null + !s.gamepadEnabled.value -> R.string.gamepad_screen_off + s.gamepadState.value == null -> R.string.gamepad_screen_unknown + else -> null + } + if (!screenTold && text != null) { + screenTold = true + Toast.makeText(this, text, Toast.LENGTH_LONG).show() + } + } lifecycleScope.launch { combine(s.phase, s.gamepadState, s.gamepadEnabled, started) { phase, st, on, fg -> Triple(phase == RemoteSession.Phase.Live && st != null && on && fg, st, on) @@ -189,6 +204,8 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { pads.refuse = st?.usable != true pads.active = active if (st == null) told = false + // 开关、对方的说法变了:画面上的手柄再发不出去时重新说 + screenTold = false } } lifecycleScope.launch { pads.pads.collect { s.localPads.value = it } } @@ -306,6 +323,10 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { override fun onToggleKeyboard() { keyboardOpen.value = !keyboardOpen.value } + + override fun onScreenPad(state: PadState?, rumble: Boolean) { + gamepads?.screen(state, rumble) + } } /** diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml index 06c88863..44775376 100644 --- a/android/app/src/main/res/values-zh/strings.xml +++ b/android/app/src/main/res/values-zh/strings.xml @@ -348,7 +348,7 @@ 手柄 把手柄插到对方电脑上 这里接着的每个手柄都会作为一个 Xbox 360 手柄插到对方电脑上,游戏可以让它震动 - 对方电脑要先装 usbip-win2(免费、有签名的驱动)才能插虚拟手柄:在那台电脑上从 github.com/vadimgrn/usbip-win2/releases 下载安装,不用重启 Airhand + 对方电脑要先装手柄驱动 usbip-win2:在那台电脑上重新运行 Airhand 的安装程序,选择安装它(也可以从 github.com/vadimgrn/usbip-win2/releases 下载),不用重启 Airhand 对方电脑既没有 uinput 也没有 vhci-hcd:在那台电脑上运行 sudo modprobe uinput 对方电脑上的 Airhand 不能用 /dev/uinput:装上 Steam 的手柄规则(steam-devices),或者照 Airhand 文档加一条 udev 规则 对方电脑没能插上虚拟手柄(%1$s),再用手柄时会重试 @@ -359,6 +359,9 @@ %1$d. %2$s(不能震动) 手柄没有发给对方:%1$s 在手柄上同时按 Select 和 Start 打开这个菜单 + 屏幕上的手柄(游戏按键) + 屏幕上的手柄没有发给对方:菜单 → 键盘与输入里的“手柄”关着 + 屏幕上的手柄没有发给对方:对方电脑上的 Airhand 版本太旧,不能接手柄,在那台电脑上更新一下 在画面上显示 @@ -381,6 +384,8 @@ Q W E R、D F、物品 1–4、B、空格;点画面就是点击 方向键(横版 / 模拟器) 方向键摇杆、Z X C、空格、回车、Esc + 手柄(Xbox) + 画面上的 Xbox 360 手柄:左右摇杆、方向键、A B X Y、LB RB LT RT、Back、Start;对方电脑要能接手柄 空白 自己添加按钮 添加 @@ -409,6 +414,10 @@ 不加 从按下的地方开始 拇指不用正好落在摇杆中间 + 手柄方向键 + 手柄左摇杆 + 手柄右摇杆 + 手柄的按钮、摇杆发给对方电脑上的虚拟 Xbox 360 手柄(和这里接着的手柄一样),对方要能接手柄(Windows 要装 usbip-win2) 不透明度 转视角灵敏度 空白处拖动、能转视角的按钮都按这个 @@ -426,6 +435,7 @@ 方向和编辑 符号 小键盘 + 手柄(Xbox) 左键 右键 中键 @@ -442,6 +452,8 @@ 游戏隐藏了光标时转视角,否则照常操作 按住开火键拖动 一边开火一边瞄准 + 手柄按钮 + A B X Y、摇杆、方向键:画面上的 Xbox 手柄,插在对方电脑上 菜单 → 游戏按键 → 编辑布局:拖动摆放、换按键、调大小,也可以自己添加。 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 0d6ef7e4..60749f92 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -355,7 +355,7 @@ Gamepads Plug gamepads into the remote computer Each gamepad connected here shows up on the remote computer as an Xbox 360 controller. Games can make it vibrate - The remote computer needs usbip-win2 (a free, signed driver) for virtual gamepads: install it there from github.com/vadimgrn/usbip-win2/releases, no need to restart Airhand + The remote computer needs the gamepad driver usbip-win2: run the Airhand installer there again and choose to install it (or get it from github.com/vadimgrn/usbip-win2/releases). No need to restart Airhand The remote computer has neither uinput nor vhci-hcd: run sudo modprobe uinput there Airhand on the remote computer can\'t use /dev/uinput: install Steam\'s controller rules (steam-devices) or add the udev rule from the Airhand docs The remote computer couldn\'t plug in a virtual gamepad (%1$s). It tries again when you use the gamepad @@ -366,6 +366,9 @@ %1$d. %2$s (can\'t vibrate) The gamepad isn\'t sent to the remote computer: %1$s Select + Start on the gamepad opens this menu + On-screen gamepad (game keys) + The on-screen gamepad isn\'t sent: Gamepads is turned off in the menu (Keyboard & input) + The on-screen gamepad isn\'t sent: Airhand on the remote computer is too old for gamepads, update it there Show on the screen @@ -388,6 +391,8 @@ Q W E R, D F, items 1–4, B, Space; tap the picture to click Arrow keys (platformer / emulator) Arrow-key joystick, Z X C, Space, Enter, Esc + Gamepad (Xbox) + An on-screen Xbox 360 controller: both sticks, D-pad, A B X Y, LB RB LT RT, Back, Start. The remote computer needs to take gamepads Blank Add your own buttons Add @@ -416,6 +421,10 @@ Nothing Center where you touch Your thumb doesn\'t need to land in the middle + D-pad + Left stick + Right stick + Gamepad controls go to a virtual Xbox 360 controller on the remote computer (like a gamepad connected here), so it needs to take gamepads (Windows: usbip-win2) Opacity View turning speed For dragging on empty space and on buttons that turn the view @@ -433,6 +442,7 @@ Arrows and editing Symbols Numpad + Gamepad (Xbox) L-click R-click M-click @@ -449,6 +459,8 @@ Turns the view when the game hides the cursor; otherwise works as usual Hold fire and drag Fire and aim at the same time + Gamepad buttons + A B X Y, sticks, D-pad: an on-screen Xbox controller plugged into the remote computer Menu → Game keys → Edit layout: move buttons, change keys and sizes, add your own. diff --git a/android/app/src/test/java/app/airhand/android/data/GameLayoutsTest.kt b/android/app/src/test/java/app/airhand/android/data/GameLayoutsTest.kt index b81630a4..8a20b73e 100644 --- a/android/app/src/test/java/app/airhand/android/data/GameLayoutsTest.kt +++ b/android/app/src/test/java/app/airhand/android/data/GameLayoutsTest.kt @@ -99,6 +99,37 @@ class GameLayoutsTest { assertEquals(120, GameBind.wheel(GameBind.WHEEL_UP)) assertEquals(-120, GameBind.wheel(GameBind.WHEEL_DOWN)) assertEquals(0, GameBind.wheel("KeyW")) + assertTrue(GameBind.valid("pad:a")) + assertTrue(GameBind.valid("pad:lt")) + assertFalse(GameBind.valid("pad:z")) + assertEquals("lt", GameBind.padButton("pad:lt")) + assertNull(GameBind.padButton("KeyA")) + assertTrue(GameBind.DPAD.all(GameBind::valid)) + } + + /** 画面上的手柄:存取、认得出来、换一种摇杆时去掉不合适的加按键 */ + @Test + fun padControls() { + val l = GameTemplate.GAMEPAD.build("g", "pad") + assertEquals(l, GameLayout.parse(JSONObject(l.toJson().toString()))) + assertTrue(l.usesPad) + assertFalse(sample.usesPad) + assertEquals(2, l.controls.count { it is GameStick && it.analog != null }) + + val s = GameStick(1, 0.5f, 0.5f, sprint = "ShiftLeft") + assertFalse(s.usesPad) + val left = s.kind(GameBind.WASD, PadStick.LEFT) + assertEquals(PadStick.LEFT, left.analog) + assertNull("Shift 不是手柄摇杆的加按键", left.sprint) + assertTrue(left.usesPad) + val withLs = left.copy(sprint = GameBind.pad("ls")) + assertEquals(GameBind.pad("ls"), withLs.kind(GameBind.WASD, PadStick.RIGHT).sprint) + assertNull(withLs.kind(GameBind.ARROWS, null).sprint) + assertTrue(s.kind(GameBind.DPAD, null).usesPad) + + // 不认识的摇杆(新版本的)当作按键的摇杆 + val o = JSONObject().put("type", "stick").put("id", 1).put("analog", "middle") + assertNull((GameLayout.parseControl(o) as GameStick).analog) } /** diff --git a/android/app/src/test/java/app/airhand/android/ui/session/GameControlsTest.kt b/android/app/src/test/java/app/airhand/android/ui/session/GameControlsTest.kt index d0421119..656d1567 100644 --- a/android/app/src/test/java/app/airhand/android/ui/session/GameControlsTest.kt +++ b/android/app/src/test/java/app/airhand/android/ui/session/GameControlsTest.kt @@ -1,10 +1,13 @@ package app.airhand.android.ui.session +import app.airhand.android.controller.PadState +import app.airhand.android.controller.XInput import app.airhand.android.data.GameBind import app.airhand.android.data.GameKey import app.airhand.android.data.GameLayout import app.airhand.android.data.GameStick import app.airhand.android.data.KeyMode +import app.airhand.android.data.PadStick import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -37,6 +40,10 @@ class GameControlsTest { log += "look %.0f %.0f".format(dx, dy) } + override fun pad(state: PadState) { + log += with(state) { "pad b=$buttons lt=$leftTrigger rt=$rightTrigger l=$leftX,$leftY r=$rightX,$rightY" } + } + override fun haptic() { haptics++ } @@ -320,6 +327,96 @@ class GameControlsTest { assertEquals(0, haptics) } + // ───────────── 画面上的手柄 ───────────── + + // 左摇杆 (126, 265.2) 半径 75(不浮动,推出边缘按 LS);A (705.6, 280.8);LT (252, 117);方向键 (420, 312) 半径 55;W (420, 195) + private val leftStick = GameStick(1, 0.15f, 0.68f, 150f, sprint = GameBind.pad("ls"), floating = false, analog = PadStick.LEFT) + private val padA = GameKey(2, 0.84f, 0.72f, 54f, listOf(GameBind.pad("a"))) + private val padLt = GameKey(3, 0.3f, 0.3f, 50f, listOf(GameBind.pad("lt"))) + private val dpad = GameStick(4, 0.5f, 0.8f, 110f, GameBind.DPAD, floating = false) + private val padLayout = GameLayout("p", "pad", listOf(leftStick, padA, padLt, dpad, w)) + + private fun padLog(buttons: Int = 0, lt: Int = 0, lx: Int = 0, ly: Int = 0) = "pad b=$buttons lt=$lt rt=0 l=$lx,$ly r=0,0" + + @Test + fun padButtonsAndTriggersMakeUpTheWholePad() { + g.layout = padLayout + log.clear() + assertTrue(g.down(0, 705.6f, 280.8f)) + assertEquals(listOf(padLog(XInput.A)), log) + // 扳机按着是按到底;每次都是整个手柄的样子 + g.down(1, 252f, 117f) + assertEquals(padLog(XInput.A, lt = 255), log.last()) + g.up(0) + assertEquals(padLog(lt = 255), log.last()) + g.up(1) + assertEquals(listOf(padLog(XInput.A), padLog(XInput.A, lt = 255), padLog(lt = 255), padLog()), log) + // 键盘的键照常发 + g.down(2, 420f, 195f) + assertEquals("KeyW↓", log.last()) + } + + @Test + fun padStickSendsHowFarItIsPushed() { + g.layout = padLayout + log.clear() + assertTrue(g.down(0, sx, sy)) + assertTrue("中心不发: $log", log.isEmpty()) + g.move(0, sx + 3f, sy) // 0.04 r:死区里 + assertTrue(log.isEmpty()) + // 推到边缘是推到底,Y 向上为正 + g.move(0, sx, sy - 75f) + assertEquals(listOf(padLog(ly = 32767)), log) + // 一半:死区以外按比例 + g.move(0, sx + 37.5f, sy) + val half = PadState.stick((0.5f - GameControls.ANALOG_DEAD) / (1f - GameControls.ANALOG_DEAD)) + assertEquals(padLog(lx = half), log.last()) + // 推出边缘再往外:还是推到底,再加按 LS + g.move(0, sx, sy + 200f) + assertEquals(padLog(XInput.LEFT_THUMB, ly = -32768), log.last()) + g.up(0) + assertEquals(padLog(), log.last()) + assertNull(g.stickState(leftStick.id)) + } + + @Test + fun dpadStickPressesPadDirections() { + g.layout = padLayout + log.clear() + g.down(0, 420f, 312f) + g.move(0, 420f, 272f) + assertEquals(listOf(padLog(XInput.DPAD_UP)), log) + g.move(0, 448f, 284f) // 右上 45° + assertEquals(padLog(XInput.DPAD_UP or XInput.DPAD_RIGHT), log.last()) + g.up(0) + assertEquals(padLog(), log.last()) + } + + @Test + fun releaseAllPutsThePadAtRest() { + g.layout = padLayout + g.down(0, sx, sy) + g.move(0, sx, sy - 75f) + g.down(1, 705.6f, 280.8f) + log.clear() + g.releaseAll() + assertEquals(padLog(), log.last()) + assertFalse(g.owns(0)) + // 已经在原位:不再发 + log.clear() + g.layout = null + assertTrue(log.isEmpty()) + } + + @Test + fun keyboardLayoutsNeverTouchThePad() { + g.down(0, sx, sy) + moveStick(90f, 45.0) + g.down(1, 705.6f, 280.8f) + g.releaseAll() + assertTrue(log.none { it.startsWith("pad") }) + } + @Test fun overlappingButtonsPickTheNearestCenter() { val a = GameKey(1, 0.5f, 0.5f, 60f, listOf("KeyA")) diff --git a/client/scripts/fetch-usbip-win2.mjs b/client/scripts/fetch-usbip-win2.mjs new file mode 100644 index 00000000..0bb59eeb --- /dev/null +++ b/client/scripts/fetch-usbip-win2.mjs @@ -0,0 +1,80 @@ +// 把 usbip-win2(手柄驱动)的安装程序下载到 src-tauri/windows/usbip/,Windows 安装包带上它、安装时问用户要不要装 +// (见 src-tauri/windows/hooks.nsh 和 src-tauri/windows/usbip/README.md)。 +// +// tauri.windows.conf.json 的 beforeBundleCommand 在打包之前运行它(`npm run tauri build`);也可以直接运行: +// node scripts/fetch-usbip-win2.mjs +// 已经下好、SHA-256 对得上就什么都不做。版本和哈希固定在下面,更新时一起改(README.md 里有步骤)。 +// 下载不了时:CI 里(GitHub Actions 设置了环境变量 CI)报错退出,发布的安装包一定带着它;本机构建只警告一声, +// 打出来的安装包不带 usbip-win2,安装时也就不问。 +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const VERSION = "0.9.8.1"; +const URL = `https://github.com/vadimgrn/usbip-win2/releases/download/v.${VERSION}/USBip-${VERSION}-x64.exe`; +const SHA256 = "38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a"; + +const dir = join(dirname(fileURLToPath(import.meta.url)), "..", "src-tauri", "windows", "usbip"); +/** 安装程序(hooks.nsh 在它存在时才带上 usbip-win2) */ +const exe = join(dir, "usbip-win2-setup.exe"); +/** 告诉 hooks.nsh 带的是哪个版本 */ +const nsh = join(dir, "usbip-win2.nsh"); + +const sha256 = (buf) => createHash("sha256").update(buf).digest("hex"); + +function writeNsh() { + // 只用 ASCII:NSIS 按系统代码页读没有 BOM 的文件 + const text = [ + "; Generated by client/scripts/fetch-usbip-win2.mjs: don't edit or commit.", + `!define AIRHAND_USBIP_VERSION "${VERSION}"`, + "", + ].join("\r\n"); + if (!existsSync(nsh) || readFileSync(nsh, "utf8") !== text) writeFileSync(nsh, text); +} + +async function download() { + let last; + for (let attempt = 1; attempt <= 3; attempt++) { + try { + const res = await fetch(URL, { redirect: "follow", signal: AbortSignal.timeout(300_000) }); + if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`); + return Buffer.from(await res.arrayBuffer()); + } catch (e) { + last = e; + console.warn(`usbip-win2: download attempt ${attempt} failed: ${e.message ?? e}`); + } + } + throw last; +} + +async function main() { + if (existsSync(exe) && sha256(readFileSync(exe)) === SHA256) { + writeNsh(); + console.log(`usbip-win2 ${VERSION}: already downloaded`); + return; + } + // 没有、或者是别的版本:先删掉,下载不了的话安装包就不带(不会带着一个和 usbip-win2.nsh 对不上的版本) + rmSync(exe, { force: true }); + rmSync(nsh, { force: true }); + console.log(`usbip-win2 ${VERSION}: downloading ${URL}`); + const data = await download(); + const got = sha256(data); + if (got !== SHA256) throw new Error(`SHA-256 mismatch: expected ${SHA256}, got ${got}`); + mkdirSync(dir, { recursive: true }); + writeFileSync(`${exe}.tmp`, data); + renameSync(`${exe}.tmp`, exe); + writeNsh(); + console.log(`usbip-win2 ${VERSION}: saved to ${exe} (${(data.length / 1048576).toFixed(1)} MB)`); +} + +main().catch((e) => { + if (process.env.CI) { + console.error(`usbip-win2: ${e.message ?? e}`); + process.exit(1); + } + console.warn( + `warning: usbip-win2 couldn't be downloaded (${e.message ?? e}).\n` + + "The Windows installer is built without it and won't offer to install the gamepad driver.", + ); +}); diff --git a/client/src-tauri/tauri.windows.conf.json b/client/src-tauri/tauri.windows.conf.json index f57e3615..db9a5a91 100644 --- a/client/src-tauri/tauri.windows.conf.json +++ b/client/src-tauri/tauri.windows.conf.json @@ -1,11 +1,15 @@ { "$schema": "https://schema.tauri.app/config/2", + "build": { + "beforeBundleCommand": "node scripts/fetch-usbip-win2.mjs" + }, "bundle": { "resources": { "windows/vdd/MttVDD.inf": "vdd/MttVDD.inf", "windows/vdd/mttvdd.cat": "vdd/mttvdd.cat", "windows/vdd/MttVDD.dll": "vdd/MttVDD.dll", - "windows/vdd/LICENSE.txt": "vdd/LICENSE.txt" + "windows/vdd/LICENSE.txt": "vdd/LICENSE.txt", + "windows/usbip/LICENSE.txt": "usbip/LICENSE.txt" } } } diff --git a/client/src-tauri/windows/hooks.nsh b/client/src-tauri/windows/hooks.nsh index c543a362..1b0bfd8d 100644 --- a/client/src-tauri/windows/hooks.nsh +++ b/client/src-tauri/windows/hooks.nsh @@ -46,6 +46,15 @@ ; 防窥撤下的显示器放回去。模板自己的确认页上加不了勾选框(它的 un.ConfirmShow 画了"删除应用程序数据"), ; 这个文件又在模板声明页面之前引入,所以这一页排在确认页前面。 ; +; 手柄驱动 usbip-win2(它自己的安装程序,打包前由 scripts/fetch-usbip-win2.mjs 下载到 windows/usbip/,见那里的 README.md): +; 控制端的手柄插到这台电脑上要用它(src/host/gamepad.rs)。两种安装方式都能用(装好之后不要管理员权限): +; * 这台电脑没装、是 x64 的 Windows 10 1903 以上:交互安装时问一次(不记住答案:当时没装的话,重新运行安装程序还会问, +; 这就是以后再装的办法)。静默、被动安装(自动更新)不问不装,命令行里有 /USBIP 就不问直接装; +; * 装的时候解压到临时目录,很安静地运行它(只装驱动和命令行工具,不重启)。它要管理员权限:安装程序没有提升权限时 +; (普通账户仅为我安装)它自己弹出 UAC 确认。在启动服务、托盘之前装,被控端一开始就看得到; +; * 已经装了(不管是谁装的、哪个版本)不动它;卸载 Airhand 时也不动:它是单独的程序,在“设置 → 应用”里卸载; +; * 打包时没有它的安装程序(本机构建时下载不了):安装包不带它,也不问。 +; ; 这个文件在模板的大部分定义之前引入:模板的 ${UNINSTKEY} 这些还没定义、语言还没加载,$MultiUser.InstallMode 也还没声明。 ; 所以这里的函数用不了它们(插在安装、卸载步骤里的 NSIS_HOOK_* 宏展开得晚,可以用),LangString 直接用语言 ID ; (2052 简体中文、1033 英语,和 tauri.conf.json 的 languages 对应)。 @@ -62,6 +71,17 @@ !define AIRHAND_VDDKEY "Software\Airhand\VirtualDisplay" !include nsDialogs.nsh +!include WinVer.nsh + +; usbip-win2 的安装程序(见文件开头):下载好了才带上。usbip-win2.nsh 里是它的版本 AIRHAND_USBIP_VERSION +!if /FileExists "${__FILEDIR__}\usbip\usbip-win2-setup.exe" + !if /FileExists "${__FILEDIR__}\usbip\usbip-win2.nsh" + !include "${__FILEDIR__}\usbip\usbip-win2.nsh" + !define AIRHAND_USBIP_SETUP "${__FILEDIR__}\usbip\usbip-win2-setup.exe" + !endif +!endif +; usbip-win2 的卸载信息(它的 Inno Setup 安装程序的 AppId):有就是装了 +!define AIRHAND_USBIP_UNINSTKEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\{199505b0-b93d-4521-a8c7-897818e0205a}_is1" ; 1:有管理员权限(安装 / 卸载程序已经提升了权限) Var AirhandAdmin @@ -113,6 +133,14 @@ LangString AirhandVddPageText 1033 "The virtual display driver (Virtual Display LangString AirhandVddRemove 2052 "同时删除虚拟显示器驱动" LangString AirhandVddRemove 1033 "Also remove the virtual display driver" +; 手柄驱动 usbip-win2(见文件开头) +LangString AirhandAskUsbip 2052 "要安装手柄驱动 usbip-win2 吗?$\r$\n$\r$\n装上之后,控制端接着的手柄(电脑、手机、平板上的)和手机屏幕上的虚拟手柄可以作为 Xbox 360 手柄插到这台电脑上玩游戏,游戏也能让手柄震动。$\r$\n$\r$\nusbip-win2 是免费的开源 USB/IP 驱动(BSD 许可,有微软的签名),随安装包带着,作为单独的程序装上,以后可以在$\"设置 → 应用$\"里卸载。安装时这台电脑的 USB 设备(键盘、鼠标等)会断开一两秒再恢复;usbip-win2 建议装好后重新启动一次电脑。$\r$\n$\r$\n现在不装的话,以后重新运行 Airhand 的安装程序会再问。" +LangString AirhandAskUsbip 1033 "Install the gamepad driver usbip-win2?$\r$\n$\r$\nWith it, gamepads on the controller's side (on a computer, phone or tablet) and the on-screen gamepad of the phone app are plugged into this computer as Xbox 360 controllers for games, and games can make them vibrate.$\r$\n$\r$\nusbip-win2 is a free, open-source USB/IP driver (BSD license, signed by Microsoft). It's shipped with this installer and installed as a separate program, which you can remove under Settings → Apps. While it installs, this computer's USB devices (keyboard, mouse…) disconnect for a second or two; usbip-win2 recommends restarting the computer afterwards.$\r$\n$\r$\nIf you skip it now, running the Airhand installer again asks again." +LangString AirhandUsbipNeedsAdmin 2052 "安装它需要管理员权限:Windows 会请你确认(普通账户要输入管理员密码)。" +LangString AirhandUsbipNeedsAdmin 1033 "Installing it needs administrator rights: Windows will ask you to confirm (other accounts need an administrator password)." +LangString AirhandUsbipFailed 2052 "没能安装 usbip-win2($0),这台电脑暂时不能接控制端的手柄。$\r$\n$\r$\n以后可以重新运行 Airhand 的安装程序再装,或者从 github.com/vadimgrn/usbip-win2/releases 下载安装。" +LangString AirhandUsbipFailed 1033 "Couldn't install usbip-win2 ($0), so this computer can't take the controller's gamepads for now.$\r$\n$\r$\nYou can run the Airhand installer again later, or install it from github.com/vadimgrn/usbip-win2/releases." + ; 选择安装目录的页面:说明两种方式各能装在哪里(不符合时"下一步"不能点,见 .onVerifyInstDir) LangString AirhandDirTop 2052 "为所有用户安装时只能装在 Program Files 里:Airhand 作为系统服务运行,别的位置普通用户可能改得了它的程序。仅为我安装时不能装在 Program Files 或 Windows 文件夹里:设置要保存在程序旁边。" LangString AirhandDirTop 1033 "For all users, Airhand must be in Program Files: it runs as a system service, and elsewhere ordinary users might be able to change it. Just for you, it can't be in Program Files or the Windows folder: its settings are saved next to it." @@ -337,6 +365,29 @@ Function AirhandShareVersion Pop $0 FunctionEnd +!ifdef AIRHAND_USBIP_VERSION +; 要不要提 usbip-win2(见文件开头),结果在 $0(1:这台电脑装得了、还没装)。它的安装程序只认 x64 的 Windows 10 1903 +; (build 18362)以上;装没装看它的卸载信息(64 位安装程序写在 64 位的注册表里,32 位的也看一眼) +Function AirhandUsbipMissing + Push $1 + StrCpy $0 0 + ${If} ${IsNativeAMD64} + ${AndIf} ${AtLeastBuild} 18362 + SetRegView 64 + ReadRegStr $1 HKLM "${AIRHAND_USBIP_UNINSTKEY}" "UninstallString" + SetRegView 32 + ${If} $1 == "" + ReadRegStr $1 HKLM "${AIRHAND_USBIP_UNINSTKEY}" "UninstallString" + ${EndIf} + SetRegView default + ${If} $1 == "" + StrCpy $0 1 + ${EndIf} + ${EndIf} + Pop $1 +FunctionEnd +!endif + ; 静默安装在复制文件之前失败:模板已经用 SetOutPath 建好了安装目录,空着的话删掉,然后退出 Function AirhandQuitBeforeInstall SetOutPath $TEMP @@ -401,6 +452,49 @@ FunctionEnd ${EndIf} ${EndIf} ${EndIf} + ; 手柄驱动 usbip-win2(见文件开头):在启动服务、托盘之前装好 + !ifdef AIRHAND_USBIP_VERSION + Call AirhandUsbipMissing + ${If} $0 == 1 + StrCpy $1 0 + ClearErrors + ${GetOptions} $CMDLINE "/USBIP" $2 + ${IfNot} ${Errors} + StrCpy $1 1 + ${ElseIfNot} ${Silent} + ${AndIf} $PassiveMode <> 1 + StrCpy $2 "$(AirhandAskUsbip)" + ${If} $AirhandAdmin != 1 + StrCpy $2 "$2$\r$\n$\r$\n$(AirhandUsbipNeedsAdmin)" + ${EndIf} + MessageBox MB_YESNO|MB_ICONQUESTION "$2" IDNO airhand_usbip_asked + StrCpy $1 1 + airhand_usbip_asked: + ${EndIf} + ${If} $1 == 1 + DetailPrint "Installing usbip-win2 ${AIRHAND_USBIP_VERSION} (the gamepad driver)…" + InitPluginsDir + File "/oname=$PLUGINSDIR\usbip-win2-setup.exe" "${AIRHAND_USBIP_SETUP}" + ; 只装驱动和命令行工具(main、client),不装图形界面、SDK、调试符号;不重启。要重启时它也返回 0 + ClearErrors + ExecWait '"$PLUGINSDIR\usbip-win2-setup.exe" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- /COMPONENTS=main,client' $0 + ${If} ${Errors} + StrCpy $0 "can't run it" + ${EndIf} + Delete "$PLUGINSDIR\usbip-win2-setup.exe" + ${If} $0 == 0 + DetailPrint "usbip-win2 is installed" + ${ElseIf} $0 == 2 + ${OrIf} $0 == 5 + ; 2:用户在 UAC 确认里选了否(它提升权限被取消时是这个);5:安装中被取消。不用再说 + DetailPrint "usbip-win2 wasn't installed (cancelled)" + ${Else} + DetailPrint "usbip-win2 couldn't be installed ($0)" + MessageBox MB_ICONEXCLAMATION "$(AirhandUsbipFailed)" /SD IDOK + ${EndIf} + ${EndIf} + ${EndIf} + !endif ${If} $MultiUser.InstallMode == "CurrentUser" DetailPrint "Setting up Airhand for this user…" nsExec::ExecToLog '"$INSTDIR\${MAINBINARYNAME}.exe" --install-user' diff --git a/client/src-tauri/windows/usbip/LICENSE.txt b/client/src-tauri/windows/usbip/LICENSE.txt new file mode 100644 index 00000000..e920d6b1 --- /dev/null +++ b/client/src-tauri/windows/usbip/LICENSE.txt @@ -0,0 +1,24 @@ +BSD 2-Clause License + +Copyright (c) 2021-2026, Vadym Hrynchyshyn + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/client/src-tauri/windows/usbip/README.md b/client/src-tauri/windows/usbip/README.md new file mode 100644 index 00000000..d75cfb79 --- /dev/null +++ b/client/src-tauri/windows/usbip/README.md @@ -0,0 +1,41 @@ +# 手柄驱动(usbip-win2) + +控制端的手柄插到 Windows 被控端上要用到 usbip-win2 的驱动(见 `src/host/gamepad.rs` 和 +[airhand-dock](https://github.com/sqlpxc/airhand-dock))。Windows 安装包带着它的安装程序,安装时问用户要不要装 +(见 `windows/hooks.nsh`),用户不用自己去下载。 + +| 文件 | 说明 | +|---|---| +| `usbip-win2-setup.exe` | usbip-win2 的安装程序,原样取自发布包。**不提交**:打包前由 `client/scripts/fetch-usbip-win2.mjs` 下载、核对 SHA-256(`tauri.windows.conf.json` 的 `beforeBundleCommand`,`npm run tauri build` 时自动运行) | +| `usbip-win2.nsh` | 同一个脚本生成,告诉 `hooks.nsh` 带的是哪个版本。**不提交** | +| `LICENSE.txt` | usbip-win2 的许可证(BSD 2-Clause),装在安装目录的 `usbip\` 里 | + +- 项目:usbip-win2,,BSD 2-Clause 许可 +- 版本:0.9.8.1 发布里的 `USBip-0.9.8.1-x64.exe`(Inno Setup 安装程序,约 25 MB,里面带着 VC++ 运行库) +- SHA-256:`38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a` +- 签名:安装程序是 OSSign 签的(Cloudyne Systems (Scheibling Consulting AB)),里面的驱动有微软的签名(WHLK / attestation), + 安装时 Windows 不会问是否信任发布者。只带 x64 的:Airhand 的 Windows 版只有 x64 + +## 安装包怎么用它 + +- 这台电脑没装 usbip-win2(看它的卸载信息,`HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{199505b0-b93d-4521-a8c7-897818e0205a}_is1`)、 + 是 x64 的 Windows 10 1903(build 18362)以上:交互安装时问一次要不要装(两种安装方式都问;仅为我安装时装它要管理员权限, + Windows 会弹出确认)。静默(`/S`)、被动(`/P`,自动更新用的)安装不问、不装,命令行里加了 `/USBIP` 就不问直接装 +- 装的时候把它解压到临时目录,运行 + `usbip-win2-setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP- /COMPONENTS=main,client`: + 只装驱动和命令行工具(不装图形界面、SDK、调试符号),不重启。它装的时候所有 USB 设备会断开一下再恢复; + 它自己说装完要重启,Airhand 不替用户重启 +- 已经装了(不管是谁装的、哪个版本)就不动它。卸载 Airhand 时也不动:它是单独的程序,在"设置 → 应用"里卸载 +- 打包时没有 `usbip-win2-setup.exe`(例如本机构建时下载不了):安装包不带它,安装时也不问 + +## 更新 + +1. 在 [Releases](https://github.com/vadimgrn/usbip-win2/releases) 里找到新版本的 `USBip-<版本>-x64.exe`, + 记下 GitHub 显示的 SHA-256(或者下载下来 `Get-FileHash`),确认签名: + ```powershell + Get-AuthenticodeSignature .\USBip-<版本>-x64.exe | Format-List Status, SignerCertificate + ``` +2. 改 `client/scripts/fetch-usbip-win2.mjs` 里的 `VERSION` 和 `SHA256`,运行一次 `node scripts/fetch-usbip-win2.mjs`(在 `client/` 里) +3. 看一下新版本的 `userspace/innosetup/setup.iss`:组件名(`main`、`client`)、命令行参数、AppId(卸载信息的键名)变了的话 + 跟着改 `hooks.nsh`;许可证变了的话替换 `LICENSE.txt` +4. airhand-dock 要认得新版本的驱动接口(它的 README 里有支持的版本;认不得时会退回调用 `usbip.exe`) diff --git a/client/src/locales/en.ts b/client/src/locales/en.ts index dd924a57..34b0aaba 100644 --- a/client/src/locales/en.ts +++ b/client/src/locales/en.ts @@ -320,7 +320,7 @@ const en: Record = { "privacy.startingMac": "Turning on", "gamepad.send": "Plug gamepads into the remote computer", "gamepad.ready": "Each gamepad connected here shows up on the remote computer as an Xbox 360 controller while you're viewing this connection. Games can make it vibrate", - "gamepad.noDriverWindows": "The remote computer needs usbip-win2 (a free, signed driver) for virtual gamepads: install it there from github.com/vadimgrn/usbip-win2/releases, no need to restart Airhand", + "gamepad.noDriverWindows": "The remote computer needs the gamepad driver usbip-win2: run the Airhand installer there again and choose to install it (or get it from github.com/vadimgrn/usbip-win2/releases). No need to restart Airhand", "gamepad.noDriverLinux": "The remote computer has neither uinput nor vhci-hcd: run sudo modprobe uinput there", "gamepad.noPermission": "Airhand on the remote computer can't use /dev/uinput: install Steam's controller rules (steam-devices) or add the udev rule from the Airhand docs", "gamepad.failed": "The remote computer couldn't plug in a virtual gamepad ({detail}). It tries again when you use the gamepad", diff --git a/client/src/locales/zh.ts b/client/src/locales/zh.ts index a2eb8c5b..7670c2c0 100644 --- a/client/src/locales/zh.ts +++ b/client/src/locales/zh.ts @@ -335,7 +335,7 @@ export default { // 手柄:这里接着的手柄插到对方电脑上,成为虚拟的 Xbox 360 手柄(见 lib/gamepad.ts) "gamepad.send": "把手柄插到对方电脑上", "gamepad.ready": "这里接着的每个手柄都会作为一个 Xbox 360 手柄插到对方电脑上(正在查看这个连接时),游戏可以让它震动", - "gamepad.noDriverWindows": "对方电脑要先装 usbip-win2(免费、有签名的驱动)才能插虚拟手柄:在那台电脑上从 github.com/vadimgrn/usbip-win2/releases 下载安装,不用重启 Airhand", + "gamepad.noDriverWindows": "对方电脑要先装手柄驱动 usbip-win2:在那台电脑上重新运行 Airhand 的安装程序,选择安装它(也可以从 github.com/vadimgrn/usbip-win2/releases 下载),不用重启 Airhand", "gamepad.noDriverLinux": "对方电脑既没有 uinput 也没有 vhci-hcd:在那台电脑上运行 sudo modprobe uinput", "gamepad.noPermission": "对方电脑上的 Airhand 不能用 /dev/uinput:装上 Steam 的手柄规则(steam-devices),或者照 Airhand 文档加一条 udev 规则", "gamepad.failed": "对方电脑没能插上虚拟手柄({detail}),再用手柄时会重试", diff --git a/docs/android.md b/docs/android.md index 425a34db..beb96625 100644 --- a/docs/android.md +++ b/docs/android.md @@ -62,20 +62,21 @@ After you pinch to zoom the local view, a moment after your fingers stop the app ### Game keys -When controlling a computer, **Game keys** under On-screen keys in the menu lays buttons and a joystick over the picture, so games that need a keyboard (WASD to walk, Space to jump, hold Shift to run…) can be played from the phone. It lives only in the controller: it sends the key, mouse button, wheel and relative-motion events the protocol already has, so hosts don't need an update; Windows injects them as scan codes, which games accept. +When controlling a computer, **Game keys** under On-screen keys in the menu lays buttons and a joystick over the picture, so games that need a keyboard (WASD to walk, Space to jump, hold Shift to run…) can be played from the phone. It lives only in the controller: it sends the key, mouse button, wheel and relative-motion events the protocol already has, so hosts don't need an update; Windows injects them as scan codes, which games accept. Buttons and sticks can also be those of an on-screen gamepad (an Xbox 360 controller), for games played with a gamepad (see On-screen gamepad below). - **Buttons**: hold a button to hold its key, let go to release it. A button can press a keyboard key, a mouse button, the wheel (keeps turning while held) or a combination of up to 3 keys (pressed in order, released in reverse, e.g. Ctrl+1). A button can be set to **tap to toggle** (tap to press, tap again to release: auto-run, staying crouched), and shows an accent ring while it is down. Sliding your finger off a button doesn't release it (thumbs drift while firing) - **Joystick**: WASD or the arrow keys, 8 directions (two keys on diagonals). Both the direction boundaries and the dead zone in the middle have hysteresis, so a thumb resting on a boundary doesn't make keys flicker. It can also press a key when pushed past its edge (Shift to sprint, etc.). By default it centers where your thumb lands, so you don't have to hit the middle - **Turning the view**: fingers that don't land on a button work as usual (trackpad / touch). When the game hides the cursor, dragging on empty space turns the view: it sends motion only, without holding the left button or accelerating, times the layout's sensitivity. A quick tap is still a left click, but a resting thumb is not a long press (no accidental scope), and a slow release is not a click (no accidental shot). A button can be set to **drag to turn the view**: in the shooter template, holding fire and dragging aims while firing +- **On-screen gamepad**: a button can also press a gamepad button (Gamepad (Xbox) in the key list: A B X Y, LB RB, LT RT (pulled all the way while held), Back, Start, the Xbox button, LS RS (clicking the sticks), the D-pad), and a stick can be the gamepad's D-pad (8 directions) or its left / right stick, which sends how far it's pushed (a small dead zone in the middle, all the way at the edge; past the edge it can also press LS / RS). Together they are one more gamepad of the phone, plugged into the computer as an Xbox 360 controller like a connected one (see [Gamepads](#gamepads) below): it gets its number the first time you press one, and is unplugged when game keys are turned off or the layout has no gamepad controls left; just hiding them (opening the keyboard, editing) puts it at rest without unplugging it. When the game makes it vibrate, the phone vibrates (not if Vibrate on press is off). The computer must be able to take gamepads (Windows: usbip-win2); when it can't, or the Gamepads switch in the menu is off, pressing a button says why - A key held in several places (the joystick's W and a W button) is released only when all of them let go. Opening the menu, pulling down the notification shade, going to the background, losing the connection, opening the keyboard and switching layouts release every held key (toggles too), so your character doesn't keep walking - The joystick and buttons are excluded from the system back gesture (with gesture navigation, swiping in from the side means Back), and buttons stay clear of the display cutout -- **Layouts**: three templates to start with — shooter (WASD joystick that sprints past the edge; fire, scope, jump, crouch, reload, E, Q, weapons 1–3, Tab, Esc), skills (MOBA / ARPG: Q W E R, D F, items 1–4, B, Space; tap the picture to click) and arrow keys (platformer / emulator: arrow-key joystick, Z X C, Space, Enter, Esc). You can create new ones (from a template or blank), duplicate, rename and delete them. Each computer remembers whether game keys are on and which layout it uses -- **Edit layout** (Game keys → Edit layout): the picture dims under a dot grid. Drag buttons to move them (they snap to other buttons and the middle of the screen, with an alignment line and a light tick), pinch with two fingers to resize the selected one, and tap a button to open its settings on the other side of the screen (key, text on the button, hold / tap to toggle, drag to turn the view, size; for the joystick: directions, key pressed past the edge, center where you touch, size), or duplicate / delete it. The toolbar has undo (every step can be undone), add (a key, or a joystick), layout settings (name, opacity, view turning speed, vibrate on press), cancel and done; drag it by the handle on its left when it covers a button. You edit a copy: nothing is saved until Done, and cancelling with changes asks first +- **Layouts**: three templates to start with — shooter (WASD joystick that sprints past the edge; fire, scope, jump, crouch, reload, E, Q, weapons 1–3, Tab, Esc), skills (MOBA / ARPG: Q W E R, D F, items 1–4, B, Space; tap the picture to click) and arrow keys (platformer / emulator: arrow-key joystick, Z X C, Space, Enter, Esc); creating a layout also offers gamepad (Xbox: left stick, D-pad, right stick, A B X Y, LB RB LT RT, Back, Xbox, Start, LS, RS). You can create new ones (from a template or blank), duplicate, rename and delete them. Each computer remembers whether game keys are on and which layout it uses +- **Edit layout** (Game keys → Edit layout): the picture dims under a dot grid. Drag buttons to move them (they snap to other buttons and the middle of the screen, with an alignment line and a light tick), pinch with two fingers to resize the selected one, and tap a button to open its settings on the other side of the screen (key, text on the button, hold / tap to toggle, drag to turn the view, size; for the joystick: directions (WASD, arrow keys, the gamepad's D-pad, left or right stick), key pressed past the edge, center where you touch, size), or duplicate / delete it. The toolbar has undo (every step can be undone), add (a key, a joystick, the D-pad or a gamepad stick), layout settings (name, opacity, view turning speed, vibrate on press), cancel and done; drag it by the handle on its left when it covers a button. You edit a copy: nothing is saved until Done, and cancelling with changes asks first - A short explanation is shown the first time ### Gamepads -Gamepads connected to the phone (Bluetooth, USB, the built-in controls of a handheld) are plugged into Windows and Linux computers as Xbox 360 controllers, and games make them vibrate (see [Usage → Gamepads](usage.md#gamepads)). Menu → **Keyboard & input** → **Gamepads** has the switch and says why when the computer can't take them (for example usbip-win2 isn't installed there). While they're sent, the gamepad's D-pad and buttons only go to the computer; Back and Home still work as usual. +Gamepads connected to the phone (Bluetooth, USB, the built-in controls of a handheld) are plugged into Windows and Linux computers as Xbox 360 controllers, and games make them vibrate (see [Usage → Gamepads](usage.md#gamepads)). Menu → **Keyboard & input** → **Gamepads** has the switch and says why when the computer can't take them (for example usbip-win2 isn't installed there). While they're sent, the gamepad's D-pad and buttons only go to the computer; Back and Home still work as usual. The [on-screen gamepad](#game-keys) of game keys counts as one of them and is listed there too. ## Phone: Share screen (be controlled) diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index 176b0c3c..7c81b7d1 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -62,20 +62,21 @@ ### 游戏按键 -控制电脑时,菜单 → 屏幕按键里的**游戏按键**可以在画面上叠一层按钮和摇杆,用手机玩要按键盘的游戏(WASD 走路、空格跳、按住 Shift 跑……)。只在控制端:发的是协议里已有的按键、鼠标键、滚轮和相对移动,被控端不用升级,Windows 上按扫描码注入,游戏认得。 +控制电脑时,菜单 → 屏幕按键里的**游戏按键**可以在画面上叠一层按钮和摇杆,用手机玩要按键盘的游戏(WASD 走路、空格跳、按住 Shift 跑……)。只在控制端:发的是协议里已有的按键、鼠标键、滚轮和相对移动,被控端不用升级,Windows 上按扫描码注入,游戏认得。按钮、摇杆也可以是画面上的手柄(Xbox 360 手柄)的,玩要用手柄的游戏(见下面的“屏幕上的手柄”)。 - **按钮**:按住就是按着那个键,松手就松开;可以是键盘上的键、鼠标键、滚轮(按着会一格一格地转下去),也可以是组合键(最多 3 个,按顺序按下、倒序松开,例如 Ctrl+1)。每个按钮可以选“点一下切换”(点一下按下、再点一下松开,自动奔跑、一直蹲着这类),切换着的按钮外面有一圈主题色。手指从按钮上滑出去也不会松开(开火时拇指会挪) - **摇杆**:WASD 或方向键,8 个方向(斜着推同时按两个),方向边界和中间的死区都有回差,拇指在边界上抖也不会让键来回按;可以设“推出边缘时加按”一个键(Shift 奔跑等);默认从拇指落下的地方开始,不用正好按在中间 - **转视角**:手指没落在按钮上时照常操作(触控板 / 触屏)。游戏隐藏了光标时,空白处拖动就是转视角:只发移动量、不按左键、不加速,乘上方案里的灵敏度;快速点一下仍是左键,拇指停着不动不算长按(不会误开镜),慢慢松开也不算点击(不会误开枪)。按钮可以设“拖动可以转视角”:射击模板的开火键按住拖动就是一边开火一边瞄准 +- **屏幕上的手柄**:按钮也可以按手柄的键(选键里的“手柄(Xbox)”:A B X Y、LB RB、LT RT(按着就是按到底)、Back、Start、西瓜键、LS RS(按下摇杆)、方向键),摇杆也可以是手柄的方向键(8 个方向)或者左 / 右摇杆:推多远发多远(中间一点死区,推到边缘是推到底,推出边缘时可以加按 LS / RS)。它们合起来是这台手机的一个手柄,和接着的手柄一样作为 Xbox 360 手柄插到电脑上(见下面的[手柄](#手柄)):第一次按下时插上、占一个编号;关掉游戏按键、换成没有手柄按钮的方案时拔掉,只是收起(打开键盘、编辑)时放回原位、不拔;游戏让它震动时手机跟着震(方案里关了“按下时振动”就不震)。电脑要能接手柄(Windows 要装 usbip-win2),接不了、或者菜单里的手柄开关关着时,按下按钮会说一声为什么 - 同一个键被几处按着(摇杆的 W 和一个 W 按钮)时都松开才松开。打开菜单、拉下通知栏、切到后台、断线、打开键盘、换方案时,按着的键(包括切换着的)全部松开,角色不会一直走下去 - 摇杆和按钮所在的地方不让系统的返回手势抢走(手势导航时从屏幕边滑入是返回);按钮避开刘海 -- **方案**:第一次用时有三套模板——射击(WASD 摇杆,推出边缘奔跑;开火、开镜、跳、蹲、换弹、E、Q、武器 1–3、Tab、Esc)、技能(MOBA / ARPG:Q W E R、D F、物品 1–4、B、空格,点画面就是点击)、方向键(横版 / 模拟器:方向键摇杆、Z X C、空格、回车、Esc),可以新建(从模板或者空白开始)、复制、重命名、删除。每台电脑分别记住开没开、用哪个方案 -- **编辑布局**(游戏按键页 → 编辑布局):画面压暗、铺一层点阵,拖动按钮摆放(靠近别的按钮或者画面中线时吸过去,画出对齐线,轻振一下),双指捏合调选中的按钮的大小,点一下按钮在另一边弹出它的设置(按键、按钮上的文字、按住 / 点一下切换、拖动可以转视角、大小;摇杆是方向键、推出边缘加按、从按下的地方开始、大小),还可以复制、删除。工具栏:撤销(每一步都能撤销)、添加(选键,或者摇杆)、方案设置(名称、不透明度、转视角灵敏度、按下时振动)、取消、完成;工具栏挡住按钮时按着左边的把手拖开。改的是一份副本,点“完成”才保存,有改动时取消会先确认 +- **方案**:第一次用时有三套模板——射击(WASD 摇杆,推出边缘奔跑;开火、开镜、跳、蹲、换弹、E、Q、武器 1–3、Tab、Esc)、技能(MOBA / ARPG:Q W E R、D F、物品 1–4、B、空格,点画面就是点击)、方向键(横版 / 模拟器:方向键摇杆、Z X C、空格、回车、Esc);新建时还有手柄(Xbox:左摇杆、方向键、右摇杆、A B X Y、LB RB LT RT、Back、西瓜键、Start、LS、RS),可以新建(从模板或者空白开始)、复制、重命名、删除。每台电脑分别记住开没开、用哪个方案 +- **编辑布局**(游戏按键页 → 编辑布局):画面压暗、铺一层点阵,拖动按钮摆放(靠近别的按钮或者画面中线时吸过去,画出对齐线,轻振一下),双指捏合调选中的按钮的大小,点一下按钮在另一边弹出它的设置(按键、按钮上的文字、按住 / 点一下切换、拖动可以转视角、大小;摇杆是方向(WASD、方向键、手柄方向键、手柄左 / 右摇杆)、推出边缘加按、从按下的地方开始、大小),还可以复制、删除。工具栏:撤销(每一步都能撤销)、添加(选键,或者摇杆、手柄方向键、手柄摇杆)、方案设置(名称、不透明度、转视角灵敏度、按下时振动)、取消、完成;工具栏挡住按钮时按着左边的把手拖开。改的是一份副本,点“完成”才保存,有改动时取消会先确认 - 第一次打开时有一页说明 ### 手柄 -接在手机上的手柄(蓝牙、USB、掌机自带的按键)会作为 Xbox 360 手柄插到 Windows、Linux 电脑上,游戏也能让它震动(见[使用指南 → 手柄](usage.zh-CN.md#手柄))。菜单 → **键盘与输入** → **手柄**里有开关,电脑接不了时说明原因(例如那台电脑没装 usbip-win2)。发给电脑的时候,手柄的方向键和按键只给电脑;返回键、主页键照常是手机的。 +接在手机上的手柄(蓝牙、USB、掌机自带的按键)会作为 Xbox 360 手柄插到 Windows、Linux 电脑上,游戏也能让它震动(见[使用指南 → 手柄](usage.zh-CN.md#手柄))。菜单 → **键盘与输入** → **手柄**里有开关,电脑接不了时说明原因(例如那台电脑没装 usbip-win2)。发给电脑的时候,手柄的方向键和按键只给电脑;返回键、主页键照常是手机的。游戏按键里[屏幕上的手柄](#游戏按键)也算一个手柄,列在这里。 ## 手机:共享本机(被控) diff --git a/docs/architecture.md b/docs/architecture.md index 0558a317..48313a2a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -256,11 +256,11 @@ Gamepads on the controller are plugged into the host as wired Xbox 360 controlle | Stage | How | |---|---| | State | After `Hello` a desktop host says whether it can take gamepads (`HostMsg::Gamepad`: unsupported / no driver / no permission / ready / failed, with a technical detail) and again when that changes. Hosts that don't say (phones) take no gamepad input; the controllers don't send any | -| Capture | Console: the Gamepad API, polled every 4 ms by one hub for the whole page and handed to the session you're viewing (`client/src/lib/gamepad.ts`); Android: key and joystick events of gamepad input devices (`controller/Gamepads.kt`, TVs included); iOS: GameController (`Controller/Gamepads.swift`). All map to XInput's layout (buttons by position, triggers 0–255, sticks with Y up) | +| Capture | Console: the Gamepad API, polled every 4 ms by one hub for the whole page and handed to the session you're viewing (`client/src/lib/gamepad.ts`); Android: key and joystick events of gamepad input devices (`controller/Gamepads.kt`, TVs included); iOS: GameController (`Controller/Gamepads.swift`). All map to XInput's layout (buttons by position, triggers 0–255, sticks with Y up). The on-screen gamepad of game keys on phones (gamepad buttons and sticks, `GameControls.kt` / `GameLayer.swift`) is one more pad in the same `Gamepads`: its state is put together from the held gamepad buttons and pushed sticks, it takes a number when first pressed and is unplugged when the layout has none left | | Transport | Input events on the control lane like keys and the mouse (`InputEvent::Gamepad` carries the whole state of one pad, `GamepadRemoved` unplugs it). Only changes are sent (stick noise below 1/1024 of the range isn't); consecutive states of one pad with the same buttons are coalesced at every queue, never across a button change. Stale input becomes "release all", which puts every remote pad back to rest; the controller then resends the current state | -| Virtual pad | [airhand-dock](https://github.com/sqlpxc/airhand-dock) (`client/src-tauri/src/host/gamepad.rs`): one dock per process, opened on first use; plugging and unplugging on one worker thread (plugging takes tens of milliseconds). Windows: usbip-win2 attaches the device served on a loopback USB/IP server, Windows binds its own `xusb22`. Linux: `vhci-hcd` as root, otherwise `uinput`, where airhand-dock plays the USB host and the `xpad` driver itself. macOS can't | +| Virtual pad | [airhand-dock](https://github.com/sqlpxc/airhand-dock) (`client/src-tauri/src/host/gamepad.rs`): one dock per process, opened on first use; plugging and unplugging on one worker thread (plugging takes tens of milliseconds). Windows: usbip-win2 attaches the device served on a loopback USB/IP server, Windows binds its own `xusb22`; the installer carries usbip-win2's own installer and offers it (`client/src-tauri/windows/usbip/`). Linux: `vhci-hcd` as root, otherwise `uinput`, where airhand-dock plays the USB host and the `xpad` driver itself. macOS can't | | Ownership | Pads belong to the controller (its identity from the end-to-end handshake), not to a session: a reconnect keeps them. When its last session ends normally they're unplugged at once; when it drops, after 30 s without a reconnect | -| Rumble | airhand-dock reports the motors the game set; the host sends `HostMsg::Rumble` to the controller's latest session (latest value per pad, ahead of queued messages). The console uses `vibrationActuator` (refreshed every 4 s while on), Android the input device's vibrators, iOS CoreHaptics on the pad's handles | +| Rumble | airhand-dock reports the motors the game set; the host sends `HostMsg::Rumble` to the controller's latest session (latest value per pad, ahead of queued messages). The console uses `vibrationActuator` (refreshed every 4 s while on), Android the input device's vibrators, iOS CoreHaptics on the pad's handles; for the on-screen gamepad, the phone's own motor | ## A/V sync (optional, off by default) Audio goes through a jitter buffer while video is shown as soon as it arrives, so by default audio lags video slightly: about **70 ms** in our measurements (same machine, local relay, 4K output at 1080p; 49–78 ms per run). That's barely noticeable while working, but may be when watching video. diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index ab9f9cfc..d9200b2c 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -256,11 +256,11 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 | 环节 | 怎么做 | |---|---| | 状态 | 桌面被控端在 `Hello` 之后说它能不能接手柄(`HostMsg::Gamepad`:不支持 / 缺驱动 / 没有权限 / 能接 / 出错了,带技术信息),之后有变化再说。不说的被控端(手机)不接手柄,控制端也就不发 | -| 采集 | 控制台:Gamepad API,整个网页一个轮询(每 4 ms),交给正在查看的会话(`client/src/lib/gamepad.ts`);Android:手柄设备的按键和摇杆事件(`controller/Gamepads.kt`,电视也是);iOS:GameController(`Controller/Gamepads.swift`)。都换成 XInput 的格式(按钮按位置、扳机 0–255、摇杆 Y 向上为正) | +| 采集 | 控制台:Gamepad API,整个网页一个轮询(每 4 ms),交给正在查看的会话(`client/src/lib/gamepad.ts`);Android:手柄设备的按键和摇杆事件(`controller/Gamepads.kt`,电视也是);iOS:GameController(`Controller/Gamepads.swift`)。都换成 XInput 的格式(按钮按位置、扳机 0–255、摇杆 Y 向上为正)。手机上游戏按键里画面上的手柄(手柄的按钮、摇杆,`GameControls.kt` / `GameLayer.swift`)是同一个 `Gamepads` 里的又一个手柄:按着的手柄按钮、推着的摇杆拼成它的状态,第一次按下时分编号,方案里没有了就拔掉 | | 传输 | 和键盘鼠标一样是控制通道上的输入(`InputEvent::Gamepad` 是一个手柄完整的状态,`GamepadRemoved` 拔掉它)。只在变了的时候发(摇杆不到量程 1/1024 的抖动不算);每个队列里同一个手柄、按钮一样的相邻状态只留最后一个,不会越过按钮的变化。过时的输入换成“释放所有按键”,对方把手柄都放回原位,控制端随后重发现在的状态 | -| 虚拟手柄 | [airhand-dock](https://github.com/sqlpxc/airhand-dock)(`client/src-tauri/src/host/gamepad.rs`):整个进程一个,第一次用时打开;插拔都在一个线程上(插一个要几十毫秒)。Windows:usbip-win2 把本机回环 USB/IP 服务器上的设备插上,系统用自带的 `xusb22` 驱动;Linux:root 时用 `vhci-hcd`,否则用 `uinput`,airhand-dock 自己当 USB 主机、做 `xpad` 驱动做的事。macOS 不行 | +| 虚拟手柄 | [airhand-dock](https://github.com/sqlpxc/airhand-dock)(`client/src-tauri/src/host/gamepad.rs`):整个进程一个,第一次用时打开;插拔都在一个线程上(插一个要几十毫秒)。Windows:usbip-win2 把本机回环 USB/IP 服务器上的设备插上,系统用自带的 `xusb22` 驱动,安装包带着 usbip-win2 自己的安装程序、安装时问要不要装(`client/src-tauri/windows/usbip/`);Linux:root 时用 `vhci-hcd`,否则用 `uinput`,airhand-dock 自己当 USB 主机、做 `xpad` 驱动做的事。macOS 不行 | | 归属 | 手柄属于控制端(端到端握手里的身份),不属于会话:断线重连接着用。它的最后一个会话正常结束时马上拔掉,断掉的等 30 秒没连回来再拔 | -| 震动 | airhand-dock 报告游戏设置的马达,被控端发 `HostMsg::Rumble` 给这个控制端最新的会话(每个手柄只留最新值,排在前面)。控制台用 `vibrationActuator`(震着时每 4 秒重放),Android 用手柄设备的振动器,iOS 用手柄两侧的 CoreHaptics | +| 震动 | airhand-dock 报告游戏设置的马达,被控端发 `HostMsg::Rumble` 给这个控制端最新的会话(每个手柄只留最新值,排在前面)。控制台用 `vibrationActuator`(震着时每 4 秒重放),Android 用手柄设备的振动器,iOS 用手柄两侧的 CoreHaptics;画面上的手柄用手机自己的马达 | ## 音画同步(可选,默认关闭) 声音要经过抖动缓冲,画面则是一到就显示,所以默认声音会比画面晚一点:实测约 **70 ms**(同机、本地中转、4K 屏输出 1080p;单次 49~78 ms)。操作电脑时几乎察觉不到,看视频时可能会。 diff --git a/docs/building.md b/docs/building.md index d513ba4a..89958456 100644 --- a/docs/building.md +++ b/docs/building.md @@ -74,6 +74,7 @@ The output is under `client/src-tauri/target/release/`: - The installer installs for all users and registers the system service, or installs just for the current user (see [Windows installation](usage.md#windows-installation)); its extra steps are in `client/src-tauri/windows/hooks.nsh` - The virtual display driver (MttVDD, see [Virtual display](usage.md#virtual-display)) is in `client/src-tauri/windows/vdd/` and is packaged into `vdd\` in the install directory (`resources` in `tauri.windows.conf.json`). The files are taken unchanged from its release and carry its signature, so don't edit them; the `README.md` there explains how to update them +- The gamepad driver usbip-win2 (see [Gamepads](usage.md#gamepads)) goes into the installer as its own installer (about 25 MB), which isn't in the repository: before bundling, `tauri build` runs `client/scripts/fetch-usbip-win2.mjs` (`beforeBundleCommand` in `tauri.windows.conf.json`), which downloads the pinned release into `client/src-tauri/windows/usbip/` and checks its SHA-256 (only once; later builds reuse it). If the download fails, CI fails, while a local build only warns and produces an installer without usbip-win2 (which then doesn't offer it). The `README.md` there explains how to update it - `npm run tauri build -- --no-bundle` only builds `airhand.exe`, but a release build refuses to run until installed - The C runtime is statically linked, so the VC++ redistributable isn't needed - Media Foundation is delay-loaded, so Windows N editions (without the Media Feature Pack) still run and use software encoding diff --git a/docs/building.zh-CN.md b/docs/building.zh-CN.md index 71348ed1..0cc2864a 100644 --- a/docs/building.zh-CN.md +++ b/docs/building.zh-CN.md @@ -74,6 +74,7 @@ npm run tauri build - 安装程序可以为所有用户安装并注册系统服务,也可以仅为当前用户安装(见 [Windows 安装版](usage.zh-CN.md#windows-安装版)),附加步骤在 `client/src-tauri/windows/hooks.nsh` - 虚拟显示器驱动(MttVDD,见[虚拟显示器](usage.zh-CN.md#虚拟显示器))在 `client/src-tauri/windows/vdd/` 里,打包时放进安装目录的 `vdd\`(`tauri.windows.conf.json` 的 `resources`)。这几个文件原样取自它的发布包、带着签名,不要改;更新方法见那里的 `README.md` +- 手柄驱动 usbip-win2(见[手柄](usage.zh-CN.md#手柄))是把它自己的安装程序(约 25 MB)打进安装包,不放在仓库里:打包之前 `tauri build` 会运行 `client/scripts/fetch-usbip-win2.mjs`(`tauri.windows.conf.json` 的 `beforeBundleCommand`),把固定版本下载到 `client/src-tauri/windows/usbip/`、核对 SHA-256(只下一次,之后的构建接着用)。下载不了时 CI 报错;本机构建只警告,打出来的安装包不带 usbip-win2(安装时也就不问)。更新方法见那里的 `README.md` - `npm run tauri build -- --no-bundle` 只生成 `airhand.exe`,但发布版没有安装时不能运行 - C 运行时是静态链接的,不需要装 VC++ 运行库 - Media Foundation 是延迟加载的,Windows N 版(没装媒体功能包)也能运行,会改用软件编码 diff --git a/docs/ios.md b/docs/ios.md index e34da6e1..88c79ce5 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -50,11 +50,11 @@ After zooming in, Airhand asks the remote for a sharper picture once your finger ### Game controls -For computers, Menu → **Game controls** overlays buttons and sticks (same as Android): hold buttons (keys, mouse buttons, wheel, combos of up to 3 keys; tap-to-toggle; drag-to-look), WASD / arrow sticks with 8 directions, hysteresis and an edge key (Shift to sprint), floating start; dragging on empty space turns the view when the game hides the cursor. Templates: shooter, skills (MOBA / ARPG), arrow keys; per-computer on/off and layout. The editor dims the picture with a dot grid; drag to place (snaps to other buttons and the center lines with guides and a tick), pinch to resize, tap to edit, undo, add, layout settings (name, opacity, look sensitivity, haptics). +For computers, Menu → **Game controls** overlays buttons and sticks (same as Android): hold buttons (keys, mouse buttons, wheel, combos of up to 3 keys; tap-to-toggle; drag-to-look), WASD / arrow sticks with 8 directions, hysteresis and an edge key (Shift to sprint), floating start; dragging on empty space turns the view when the game hides the cursor. Buttons and sticks can also be those of an on-screen gamepad (an Xbox 360 controller): A B X Y, LB RB, LT RT, Back, Start, the Xbox button, LS RS, the D-pad, and the D-pad or the left / right stick as a stick (sending how far it's pushed). They make up one more gamepad of the device, plugged into the computer like a connected one (see [Gamepads](#gamepads) below), and the iPhone vibrates when the game makes it rumble; the computer must be able to take gamepads. Templates: shooter, skills (MOBA / ARPG), arrow keys, gamepad (Xbox); per-computer on/off and layout. The editor dims the picture with a dot grid; drag to place (snaps to other buttons and the center lines with guides and a tick), pinch to resize, tap to edit, undo, add, layout settings (name, opacity, look sensitivity, haptics). ### Gamepads -Gamepads connected to the iPhone / iPad (Xbox, PlayStation, Switch Pro, MFi) are plugged into Windows and Linux computers as Xbox 360 controllers, and games make them vibrate through the controller's haptics (see [Usage → Gamepads](usage.md#gamepads)). Menu → **Gamepads** has the switch, the reason when the computer can't take them, and the gamepads in use. The Home, Menu and Options buttons go to the computer instead of the system. +Gamepads connected to the iPhone / iPad (Xbox, PlayStation, Switch Pro, MFi) are plugged into Windows and Linux computers as Xbox 360 controllers, and games make them vibrate through the controller's haptics (see [Usage → Gamepads](usage.md#gamepads)). Menu → **Gamepads** has the switch, the reason when the computer can't take them, and the gamepads in use. The Home, Menu and Options buttons go to the computer instead of the system. The [on-screen gamepad](#game-controls) of game controls counts as one of them and is listed there too. ## Share diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index 816d2c6e..5765d924 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -56,13 +56,14 @@ - **按钮**:按住就是按着那个键;可以是键盘上的键、鼠标键、滚轮,也可以是组合键(最多 3 个,按顺序按下、倒序松开);可以设“点一下切换”、“拖动可以转视角”(射击模板的开火键按住拖动 = 一边开火一边瞄准)。手指滑出按钮也不会松开 - **摇杆**:WASD 或方向键,8 个方向,方向边界和死区都有回差;可以设“推出边缘时加按”一个键(Shift 奔跑);默认从拇指落下的地方开始 - **转视角**:游戏隐藏了光标时,空白处拖动就是转视角(只发移动量、不加速,乘上方案里的灵敏度) +- **屏幕上的手柄**:按钮也可以按手柄(Xbox 360 手柄)的 A B X Y、LB RB、LT RT、Back、Start、西瓜键、LS RS、方向键,摇杆也可以是手柄的方向键或者左 / 右摇杆(推多远发多远)。它们算这台设备的一个手柄,和接着的手柄一样插到电脑上(见下面的[手柄](#手柄));游戏让它震动时 iPhone 跟着震。电脑要能接手柄 - 同一个键被几处按着时都松开才松开;打开菜单、切到后台、断线、打开键盘时按着的键全部松开 -- **方案**:射击、技能(MOBA / ARPG)、方向键三套模板,可以新建、复制、重命名、删除;每台电脑分别记住开没开、用哪个方案 -- **编辑布局**:画面压暗、铺一层点阵,拖动摆放(靠近别的按钮或画面中线时吸过去、画出对齐线、轻振一下),双指捏合调大小,点一下改设置(按键、文字、按法、转视角、大小;摇杆的方向、加按的键、浮动),可以复制、删除;工具栏有撤销、添加、方案设置(名称、不透明度、灵敏度、振动)、取消、完成,按住左边的把手可以把工具栏拖开 +- **方案**:射击、技能(MOBA / ARPG)、方向键、手柄(Xbox)几套模板,可以新建、复制、重命名、删除;每台电脑分别记住开没开、用哪个方案 +- **编辑布局**:画面压暗、铺一层点阵,拖动摆放(靠近别的按钮或画面中线时吸过去、画出对齐线、轻振一下),双指捏合调大小,点一下改设置(按键、文字、按法、转视角、大小;摇杆的方向(WASD、方向键、手柄方向键、手柄左 / 右摇杆)、加按的键、浮动),可以复制、删除;工具栏有撤销、添加、方案设置(名称、不透明度、灵敏度、振动)、取消、完成,按住左边的把手可以把工具栏拖开 ### 手柄 -接在 iPhone / iPad 上的手柄(Xbox、PlayStation、Switch Pro、MFi)会作为 Xbox 360 手柄插到 Windows、Linux 电脑上,游戏让它震动时手柄跟着震(见[使用指南 → 手柄](usage.zh-CN.md#手柄))。菜单 → **手柄**里有开关、电脑接不了时的原因和正在用的手柄。手柄上的主页、菜单、选项键交给电脑,不给系统。 +接在 iPhone / iPad 上的手柄(Xbox、PlayStation、Switch Pro、MFi)会作为 Xbox 360 手柄插到 Windows、Linux 电脑上,游戏让它震动时手柄跟着震(见[使用指南 → 手柄](usage.zh-CN.md#手柄))。菜单 → **手柄**里有开关、电脑接不了时的原因和正在用的手柄。手柄上的主页、菜单、选项键交给电脑,不给系统。游戏按键里[屏幕上的手柄](#游戏按键)也算一个手柄,列在这里。 ## 共享本机(被看) diff --git a/docs/limitations.md b/docs/limitations.md index e2060009..a803d3ce 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -16,7 +16,7 @@ - One stream per video frame also needs a v10 relay server: older servers still work, but video stays a single stream, so one lost packet holds up the frames behind it - Showing several displays at once (see [Usage → Multiple displays](usage.md#multiple-displays)) is limited to 4; each display is captured and encoded on its own, so the host's encoding load and the bandwidth roughly scale with the number of displays (the quality settings apply to each one). When the GPU can't run that many hardware encoders at once, the extra streams fall back to software encoding. A/V sync delays all of them together. The Android host has a single screen, and the Android controller shows one remote display at a time - Later frame streams can arrive first. Frames that depend on a missing reference still wait for retransmission or recovery, so long, lossy paths can stutter. -- Gamepads (see [Usage → Gamepads](usage.md#gamepads)) can only be plugged into Windows hosts with usbip-win2 installed and Linux hosts where Airhand can use `/dev/uinput` (or runs as root); macOS, Android and iOS hosts can't take them. The remote pad is an Xbox 360 controller: gyro, touchpads, extra paddles, adaptive triggers and light bars aren't passed on, and the button labels of other pads map by position. Up to four per controller (XInput itself only sees four pads per computer). Browsers only report a gamepad after one of its buttons was pressed in the page, and the Linux desktop console sees gamepads only when WebKitGTK was built with gamepad support (libmanette) +- Gamepads (see [Usage → Gamepads](usage.md#gamepads)) can only be plugged into Windows hosts with usbip-win2 installed (the installer offers it on x64 Windows 10 1903 or later) and Linux hosts where Airhand can use `/dev/uinput` (or runs as root); macOS, Android and iOS hosts can't take them. The remote pad is an Xbox 360 controller: gyro, touchpads, extra paddles, adaptive triggers and light bars aren't passed on, and the button labels of other pads map by position. Up to four per controller (XInput itself only sees four pads per computer). Browsers only report a gamepad after one of its buttons was pressed in the page, and the Linux desktop console sees gamepads only when WebKitGTK was built with gamepad support (libmanette) ## Windows diff --git a/docs/limitations.zh-CN.md b/docs/limitations.zh-CN.md index c4131cc8..082cfd54 100644 --- a/docs/limitations.zh-CN.md +++ b/docs/limitations.zh-CN.md @@ -16,7 +16,7 @@ - 画面每帧一条流要中转服务器也是 v10:旧的服务器照样能用,只是画面还是一条流,丢一个包就挡住后面的帧 - 同时显示几个显示器时(见[使用说明 → 多屏](usage.zh-CN.md#多屏))最多 4 个;每个显示器各自采集、编码,被控端的编码开销和带宽大致按显示器的个数翻倍(画质设置对每一个分别生效);显卡同时开不了那么多硬件编码器时,多出来的那几路退回软件编码。音画同步对所有的一起推迟。Android 被控端只有一块屏幕,Android 控制端一次只看对方的一个显示器 - 独立帧流允许后面的帧先到。依赖丢失参考帧的增量帧仍需等待重传或恢复,因此长往返、高丢包链路可能卡顿。 -- 手柄(见[使用指南 → 手柄](usage.zh-CN.md#手柄))只能插到装了 usbip-win2 的 Windows 被控端、Airhand 能用 `/dev/uinput`(或以 root 运行)的 Linux 被控端上;macOS、Android、iOS 被控端不能接。对方的手柄是 Xbox 360 手柄:陀螺仪、触摸板、背键、自适应扳机、灯条都传不过去,别的手柄的按键按位置对应。每个控制端最多四个(XInput 本身每台电脑也只认四个)。浏览器要在网页里按过手柄上的键才说它接上了;Linux 桌面版的控制台要 WebKitGTK 编译时带了手柄支持(libmanette)才看得到手柄 +- 手柄(见[使用指南 → 手柄](usage.zh-CN.md#手柄))只能插到装了 usbip-win2 的 Windows 被控端(安装包里带着,x64 的 Windows 10 1903 以上安装时会问)、Airhand 能用 `/dev/uinput`(或以 root 运行)的 Linux 被控端上;macOS、Android、iOS 被控端不能接。对方的手柄是 Xbox 360 手柄:陀螺仪、触摸板、背键、自适应扳机、灯条都传不过去,别的手柄的按键按位置对应。每个控制端最多四个(XInput 本身每台电脑也只认四个)。浏览器要在网页里按过手柄上的键才说它接上了;Linux 桌面版的控制台要 WebKitGTK 编译时带了手柄支持(libmanette)才看得到手柄 ## Windows diff --git a/docs/usage.md b/docs/usage.md index f79b29fe..6bc837d0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -53,6 +53,7 @@ On Windows Airhand is installed with its installer, either for all users or just - **First install**: administrator accounts choose in the installer (for all users by default). For other accounts the installer asks first: Yes runs it again as administrator (you'll need an administrator password) to install for all users; No installs just for you - **Upgrading, reinstalling**: the installer keeps the way Airhand was installed and doesn't ask again. The copy installed for all users needs administrator rights; other accounts get an explanation and then a prompt for an administrator password. If the tray was open before the upgrade, it opens again afterwards (when you upgrade someone's computer remotely, the connection comes back) - **Switching between the two**: uninstall first, then install again +- **Gamepad driver**: the installer includes [usbip-win2](https://github.com/vadimgrn/usbip-win2) and asks whether to install it when the computer doesn't have it yet (both ways of installing), see [Gamepads](#gamepads) ### For all users @@ -147,6 +148,8 @@ Settings → Apps → Airhand → Uninstall. The uninstaller stops and removes t If the [virtual display](#virtual-display) driver was installed, a page before the confirmation offers "Also remove the virtual display driver", unticked by default: unticked keeps the disabled driver (with the record that recognizes it, `HKLM\SOFTWARE\Airhand\VirtualDisplay`, and its settings in `%ProgramData%\Airhand\VirtualDisplay`) for a later reinstall; ticked removes it too. +The [gamepad driver usbip-win2](#gamepads), if it was installed with Airhand, is a separate program and stays when Airhand is uninstalled; uninstall USBip under Settings → Apps if you no longer need it (all USB devices disconnect for a moment, and it recommends restarting afterwards). + (Choosing "uninstall the old version first" during an upgrade isn't an uninstall: `config.toml` is kept, see [Windows installation](#windows-installation).) ### macOS @@ -348,7 +351,9 @@ Keeps the people at the remote computer from seeing what you do: all of its moni Gamepads connected to the computer or phone you control from (Xbox, PlayStation, Switch Pro, the built-in pad of a handheld…) are plugged into the remote computer as wired **Xbox 360 controllers**: games see a real USB gamepad (XInput, DirectInput, Windows.Gaming.Input, SDL, Steam, evdev), and when a game makes it vibrate, your gamepad vibrates. On by default; each connection has its own switch. -- **Windows hosts** need [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases) (a free USB/IP driver signed by Microsoft) installed once; no administrator rights are needed afterwards, and it also works for the lock screen and the system service. Airhand notices when it gets installed, no restart needed +- **Windows hosts** need [usbip-win2](https://github.com/vadimgrn/usbip-win2) (a free, open-source USB/IP driver, BSD license, signed by Microsoft) installed once, and **the Airhand installer comes with it**: when it isn't installed yet and the computer runs x64 Windows 10 1903 or later, installing Airhand asks whether to install it (also when installing just for you; Windows then asks for administrator rights). While it installs, the computer's USB devices disconnect for a second or two; usbip-win2 recommends restarting once afterwards + - If you said No, running the Airhand installer again asks again; you can also install it from its [Releases](https://github.com/vadimgrn/usbip-win2/releases). Silent (`/S`) and passive (`/P`, used by updates) installs don't ask and don't install it; add `/USBIP` to the command line to install it without asking + - It's a separate program (USBip under Settings → Apps): an existing installation is left alone, and uninstalling Airhand keeps it. No administrator rights are needed afterwards, and it also works for the lock screen and the system service. Airhand notices when it gets installed, no restart needed - **Linux hosts** use the kernel's `vhci-hcd` when Airhand runs as root, otherwise `uinput`: Airhand needs access to `/dev/uinput`. Steam's controller rules (`steam-devices`) already grant it to the user at the seat; otherwise add a udev rule: ```bash echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' | sudo tee /etc/udev/rules.d/60-airhand-uinput.rules @@ -358,6 +363,7 @@ Gamepads connected to the computer or phone you control from (Xbox, PlayStation, - **Console** (desktop and web): the gamepad button appears in the toolbar once a gamepad has been used here (browsers only report gamepads after a button press). Its menu has the switch, says why when the remote computer can't take gamepads (for example "needs usbip-win2"), and lists the gamepads. Gamepads go to the connection you're viewing; switching tabs puts the remote gamepads back to rest - **Android**: menu → **Keyboard & input** → **Gamepads**. On a TV, gamepads are sent too (play the computer's games on the TV); press **Select + Start** on the gamepad to open the menu, where the gamepad navigates as usual - **iPhone / iPad**: menu → **Gamepads** +- **On-screen gamepad** (Android, iPhone / iPad): game keys can have gamepad buttons and sticks (the Gamepad (Xbox) template is a whole Xbox 360 controller). They count as one more gamepad of the phone: plugged in with its own number the first time you press one, unplugged when you turn game keys off or switch to a layout without them. When a game makes it vibrate, the phone vibrates (not if Vibrate on press is off in the layout). The switch above covers it too. See [Android → Game keys](android.md#game-keys) - Up to four gamepads per controller. Buttons map by position (A at the bottom, as on an Xbox pad), whatever the labels on yours. When a gamepad is unplugged here, the remote one is unplugged too. If the connection drops, the remote gamepads stay plugged for 30 seconds so a reconnect doesn't make the game see them disconnect; disconnecting unplugs them right away ## Language diff --git a/docs/usage.zh-CN.md b/docs/usage.zh-CN.md index d158dcaf..b847f75e 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -53,6 +53,7 @@ Windows 上用安装程序安装,可以为所有用户安装,也可以仅为 - **第一次安装**:管理员账户在安装程序里选择安装方式(默认为所有用户安装)。普通账户运行时安装程序先问一句:选“是”就以管理员身份重新运行(要输入管理员密码),为所有用户安装;选“否”仅为你安装 - **升级、重新安装**:按原来的方式安装,不再询问。为所有用户安装的那份需要管理员权限,普通账户运行时会先说明,再要求输入管理员密码。升级前托盘开着的话,装好后自动重新打开(远程帮别人升级时,连接随之恢复) - **换安装方式**:先卸载,再重新安装 +- **手柄驱动**:安装包里带着 [usbip-win2](https://github.com/vadimgrn/usbip-win2),这台电脑还没装的话安装时问要不要装(两种安装方式都问),见[手柄](#手柄) ### 为所有用户安装 @@ -147,6 +148,8 @@ Airhand 要保存的东西都在一个 `config.toml` 里(里面有注释)。 装过[虚拟显示器](#虚拟显示器)驱动的话,卸载程序在确认卸载之前有一页“同时删除虚拟显示器驱动”,默认不勾:不勾就留着停用了的驱动(还有注册表里认得它的记录 `HKLM\SOFTWARE\Airhand\VirtualDisplay` 和它的设置 `%ProgramData%\Airhand\VirtualDisplay`),重新安装 Airhand 时接着用;勾上就一起删掉。 +安装时装上的[手柄驱动 usbip-win2](#手柄)是单独的程序,卸载 Airhand 时留着;不用了的话在“设置 → 应用”里卸载 USBip(卸载时所有 USB 设备会断开一下,它建议之后重新启动)。 + (升级时选择“先卸载旧版本”不算卸载:会保留 `config.toml`,见 [Windows 安装版](#windows-安装版)。) ### macOS @@ -348,7 +351,9 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 接在你这边的电脑或手机上的手柄(Xbox、PlayStation、Switch Pro、掌机自带的手柄……)会作为有线的 **Xbox 360 手柄**插到对方电脑上:游戏看到的就是一个真的 USB 手柄(XInput、DirectInput、Windows.Gaming.Input、SDL、Steam、evdev),游戏让它震动时,你手里的手柄跟着震。默认打开,每个连接各有一个开关。 -- **Windows 被控端**要先装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2/releases)(免费的 USB/IP 驱动,有微软的签名);之后不需要管理员权限,锁屏界面、系统服务里也能用。装好之后 Airhand 自己会发现,不用重启 +- **Windows 被控端**要装一次 [usbip-win2](https://github.com/vadimgrn/usbip-win2)(免费的开源 USB/IP 驱动,BSD 许可,有微软的签名),**Airhand 的安装包里带着它**:这台电脑还没装、是 x64 的 Windows 10 1903 以上时,安装 Airhand 时会问要不要装(仅为我安装时也问,Windows 会要求管理员权限)。装的时候这台电脑的 USB 设备会断开一两秒再恢复;usbip-win2 建议装好后重新启动一次电脑 + - 当时没装的话,重新运行 Airhand 的安装程序会再问;也可以从它的 [Releases](https://github.com/vadimgrn/usbip-win2/releases) 下载安装。静默(`/S`)、被动(`/P`,自动更新用的)安装不问也不装,命令行里加上 `/USBIP` 就不问直接装 + - 它是单独的程序(“设置 → 应用”里的 USBip),已经装了的不动它,卸载 Airhand 时也留着。装好之后不需要管理员权限,锁屏界面、系统服务里也能用;Airhand 自己会发现装好了,不用重启 - **Linux 被控端**:Airhand 以 root 运行时用内核的 `vhci-hcd`,否则用 `uinput`,需要能读写 `/dev/uinput`。装了 Steam 的手柄规则(`steam-devices`)就已经给了坐在电脑前的用户;否则加一条 udev 规则: ```bash echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' | sudo tee /etc/udev/rules.d/60-airhand-uinput.rules @@ -358,6 +363,7 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 - **控制台**(桌面版、网页版):在这边用过手柄之后(浏览器要在手柄上按过键才说它接上了),工具栏里出现手柄按钮。菜单里有开关、对方接不了时的原因(例如“要先装 usbip-win2”)和手柄列表。手柄只给正在查看的连接;切换标签时对方的手柄放回原位 - **Android**:菜单 → **键盘与输入** → **手柄**。电视上也发手柄(在电视上玩电脑里的游戏);在手柄上同时按 **Select + Start** 打开菜单,菜单里手柄照常用来选 - **iPhone / iPad**:菜单 → **手柄** +- **屏幕上的手柄**(Android、iPhone / iPad):游戏按键里可以放手柄的按钮和摇杆(“手柄(Xbox)”模板就是一整个 Xbox 360 手柄),它们算这台手机的一个手柄,第一次按下时插上、占一个编号,关掉游戏按键或者换成没有手柄的方案时拔掉;游戏让它震动时手机跟着震(方案里关了“按下时振动”就不震)。上面的开关对它也管用。见 [Android → 游戏按键](android.zh-CN.md#游戏按键) - 每个控制端最多四个手柄。按键按位置对应(和 Xbox 手柄一样 A 在下面),不管你的手柄上印的是什么。这边拔掉手柄,对方的也跟着拔掉。连接断掉时,对方的手柄继续插着 30 秒,重连上来游戏不会以为手柄断开了;主动断开则马上拔掉 ## 界面语言 diff --git a/ios/Airhand/Controller/Gamepads.swift b/ios/Airhand/Controller/Gamepads.swift index 993a8e45..ee283a50 100644 --- a/ios/Airhand/Controller/Gamepads.swift +++ b/ios/Airhand/Controller/Gamepads.swift @@ -51,6 +51,12 @@ enum XInput { static let b = 0x2000 static let x = 0x4000 static let y = 0x8000 + + /// 游戏按键里手柄按钮的名字(`GameItem.padButtons`)→ XInput 的按钮(扳机 lt / rt 不是按钮,另外处理) + static let names: [String: Int] = [ + "a": a, "b": b, "x": x, "y": y, "lb": leftShoulder, "rb": rightShoulder, "back": back, "start": start, + "guide": guide, "ls": leftThumb, "rs": rightThumb, "up": dpadUp, "down": dpadDown, "left": dpadLeft, "right": dpadRight, + ] } /// 这台设备接着的一个手柄(界面列出来) @@ -70,7 +76,9 @@ struct LocalPad: Identifiable, Equatable { /// Menu → Start,Options → Back,Home → 西瓜键(不让系统拿去打开游戏中心)。只在变了的时候发,按钮变了马上发, /// 只是摇杆动了合并着发(见 [InputSender]); /// * 震动:CoreHaptics,有左右两个马达的手柄(Xbox、DualSense)左边是大马达、右边是小马达,只有一个的用它; -/// 一直震到下一次设置(循环的连续振动,用强度参数调)。 +/// 一直震到下一次设置(循环的连续振动,用强度参数调); +/// * 画面上的手柄(游戏按键里的手柄按钮、摇杆,见 [screen])也是这样一个手柄:第一次按下时分一个编号,方案里不再有手柄时 +/// 拔掉;游戏让它震动时 iPhone 自己震(方案里开着“按下时振动”的话)。 /// /// 都在主线程上用(GameController 的回调默认在主队列)。 @Observable @@ -95,11 +103,28 @@ final class Gamepads { @ObservationIgnored var onRefused: (() -> Void)? + /// 按了画面上的手柄,却没有交给对方(开关关着、对方没说它能不能接):界面说一声为什么 + @ObservationIgnored var onScreenIdle: (() -> Void)? + @ObservationIgnored private let send: ([JSON], Bool) -> Void @ObservationIgnored private var slots: [GCController?] = Array(repeating: nil, count: Gamepads.maxPads) @ObservationIgnored private var sent: [PadState?] = Array(repeating: nil, count: Gamepads.maxPads) @ObservationIgnored private var rumblers: [Rumbler?] = Array(repeating: nil, count: Gamepads.maxPads) @ObservationIgnored private var observers: [NSObjectProtocol] = [] + /// 画面上的手柄的编号(第一次按下时分)、现在的样子、游戏让它震动时 iPhone 跟不跟着震 + @ObservationIgnored private var screenSlot: Int? + @ObservationIgnored private var screenState = PadState() + @ObservationIgnored private var screenRumble = true + /// iPhone 自己的振动(替画面上的手柄震;iPad 没有),第一次用到时建 + @ObservationIgnored private var phoneRumbler: Rumbler? + @ObservationIgnored private var phoneChecked = false + private var phone: Rumbler? { + if !phoneChecked { + phoneChecked = true + phoneRumbler = Rumbler(phone: ()) + } + return phoneRumbler + } init(send: @escaping ([JSON], Bool) -> Void) { self.send = send @@ -125,7 +150,10 @@ final class Gamepads { func resync() { var events: [JSON] = [] for pad in 0.. Int? { + (0.. Int? { if let i = slots.firstIndex(where: { $0 === c }) { return i } - guard let free = slots.firstIndex(where: { $0 == nil }) else { return nil } + guard let free = freeSlot() else { return nil } slots[free] = c sent[free] = nil publish() @@ -192,6 +277,7 @@ final class Gamepads { private func publish() { pads = slots.enumerated().compactMap { pad, c in + if pad == screenSlot { return LocalPad(pad: pad, name: L.t("gamepad_screen"), rumble: phone != nil) } guard let c else { return nil } return LocalPad(pad: pad, name: c.vendorName ?? c.productCategory, rumble: c.haptics != nil) } @@ -200,6 +286,7 @@ final class Gamepads { private func stopRumble() { for r in rumblers { r?.stop() } rumblers = Array(repeating: nil, count: Self.maxPads) + phoneRumbler?.stop() } /// 按位置读(见类的说明) @@ -247,17 +334,27 @@ private final class Rumbler { let localities: [(GCHapticsLocality, Float)] = both ? [(.leftHandle, 0.2), (.rightHandle, 0.8)] : [(.default, 0.5)] for (l, s) in localities { guard let e = h.createEngine(withLocality: l) else { continue } - let i = engines.count - // 引擎被系统停掉、重置了:播放器不能再用,下次重新建(回调在别的线程上) - e.resetHandler = { [weak self] in DispatchQueue.main.async { self?.players[i] = nil } } - e.stoppedHandler = { [weak self] _ in DispatchQueue.main.async { self?.players[i] = nil } } - engines.append(e) - players.append(nil) - sharpness.append(s) + add(e, sharpness: s) } if engines.isEmpty { return nil } } + /// 这台 iPhone 自己的马达(画面上的手柄震动时用);没有(iPad)是 nil + init?(phone: Void) { + guard CHHapticEngine.capabilitiesForHardware().supportsHaptics, let e = try? CHHapticEngine() else { return nil } + add(e, sharpness: 0.4) + } + + private func add(_ e: CHHapticEngine, sharpness s: Float) { + let i = engines.count + // 引擎被系统停掉、重置了:播放器不能再用,下次重新建(回调在别的线程上) + e.resetHandler = { [weak self] in DispatchQueue.main.async { self?.players[i] = nil } } + e.stoppedHandler = { [weak self] _ in DispatchQueue.main.async { self?.players[i] = nil } } + engines.append(e) + players.append(nil) + sharpness.append(s) + } + func set(large: Int, small: Int) { let levels = engines.count >= 2 ? [large, small] : [max(large, small)] for (i, level) in levels.enumerated() where i < engines.count { play(i, Float(level) / 255) } diff --git a/ios/Airhand/Session/GameEditor.swift b/ios/Airhand/Session/GameEditor.swift index 98d8cdb9..c4b6b29c 100644 --- a/ios/Airhand/Session/GameEditor.swift +++ b/ios/Airhand/Session/GameEditor.swift @@ -86,11 +86,16 @@ struct GameEditor: View { } .confirmationDialog(L.t("game_add"), isPresented: $adding, titleVisibility: .visible) { Button(L.t("game_key")) { picking = true } - Button(L.t("game_stick")) { - snapshot() - let s = GameTemplates.stick(0.2, 0.68, GameItem.wasd, sprint: "ShiftLeft") - layout.items.append(s) - selected = s.id + Button(L.t("game_stick")) { addStick(GameTemplates.stick(0.2, 0.68, GameItem.wasd, sprint: "ShiftLeft")) } + // 画面上的手柄:方向键(不浮动,和手柄上的一样按在哪个方向就是哪个)、左右摇杆 + Button(L.t("game_pad_dpad")) { + addStick(GameItem(kind: .stick, x: 0.3, y: 0.75, size: 110, keys: GameItem.dpad, floating: false)) + } + Button(L.t("game_pad_left_stick")) { + addStick(GameItem(kind: .stick, x: 0.2, y: 0.68, size: 140, keys: GameItem.wasd, analog: "left")) + } + Button(L.t("game_pad_right_stick")) { + addStick(GameItem(kind: .stick, x: 0.65, y: 0.75, size: 120, keys: GameItem.wasd, analog: "right")) } } .confirmationDialog(L.t("game_discard_title"), isPresented: $confirmDiscard, titleVisibility: .visible) { @@ -237,6 +242,12 @@ struct GameEditor: View { .accessibilityLabel(label) } + private func addStick(_ s: GameItem) { + snapshot() + layout.items.append(s) + selected = s.id + } + private func duplicate(_ id: UUID) { guard let i = index(id) else { return } snapshot() @@ -266,7 +277,11 @@ struct ItemSettings: View { let willChange: () -> Void @State private var picking = false - private let sprintKeys = ["", "ShiftLeft", "ControlLeft", "AltLeft", "Space"] + /// 摇杆的几种:键盘的 WASD / 方向键,画面上的手柄的方向键 / 左摇杆 / 右摇杆(GameItem.stickKind) + private let stickKinds: [(String, String)] = [ + ("wasd", "W A S D"), ("arrows", "↑ ← ↓ →"), + ("dpad", L.t("game_pad_dpad")), ("left", L.t("game_pad_left_stick")), ("right", L.t("game_pad_right_stick")), + ] var body: some View { NavigationStack { @@ -291,19 +306,20 @@ struct ItemSettings: View { Text(L.t("game_look_desc")).font(.caption).foregroundStyle(Theme.sub) } } + } footer: { + if item.usesPad { Text(L.t("game_pad_note")) } } } else { Section { - Picker(L.t("game_stick_keys"), selection: change(\.keys)) { - Text("W A S D").tag(GameItem.wasd) - Text("↑ ← ↓ →").tag(GameItem.arrows) + Picker(L.t("game_stick_keys"), selection: change(\.stickKind)) { + ForEach(stickKinds, id: \.0) { kind, title in Text(title).tag(kind) } } Picker(L.t("game_sprint"), selection: Binding(get: { item.sprint ?? "" }, set: { v in willChange() item.sprint = v.isEmpty ? nil : v })) { - ForEach(sprintKeys, id: \.self) { k in - Text(k.isEmpty ? L.t("game_sprint_none") : KeyMap.label(k, os: os)).tag(k) + ForEach([""] + item.sprintKeys, id: \.self) { k in + Text(k.isEmpty ? L.t("game_sprint_none") : GameItem.keyLabel(k, os: os)).tag(k) } } Toggle(isOn: change(\.floating)) { @@ -312,6 +328,8 @@ struct ItemSettings: View { Text(L.t("game_floating_desc")).font(.caption).foregroundStyle(Theme.sub) } } + } footer: { + if item.usesPad { Text(L.t("game_pad_note")) } } } Section(L.t("game_size")) { @@ -395,6 +413,8 @@ struct KeyPicker: View { ("game_group_function", (1...12).map { "F\($0)" }), ("game_group_nav", ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown", "Insert", "Delete"]), ("game_group_symbols", ["Backquote", "Minus", "Equal", "BracketLeft", "BracketRight", "Backslash", "Semicolon", "Quote", "Comma", "Period", "Slash"]), + // 画面上的手柄(Xbox 360 手柄)的按钮 + ("game_group_pad", GameItem.padButtons.map { "pad:" + $0 }), ] var body: some View { diff --git a/ios/Airhand/Session/GameLayer.swift b/ios/Airhand/Session/GameLayer.swift index 2f1567c8..caf3f741 100644 --- a/ios/Airhand/Session/GameLayer.swift +++ b/ios/Airhand/Session/GameLayer.swift @@ -1,18 +1,26 @@ import UIKit -/// 游戏按键发出去的东西:同一个键被几处按着(摇杆的 W 和一个 W 按钮)时都松开才松开 +/// 游戏按键发出去的东西:同一个键被几处按着(摇杆的 W 和一个 W 按钮)时都松开才松开。 +/// 画面上的手柄(`pad:` 的按钮、手柄的摇杆)有变化就把它整个现在的样子交出去([pad]),由 Gamepads 插到对方电脑上 final class GameOutput { var send: ([JSON]) -> Void = { _ in } /// 拖动转视角:移动了多少点(交给画面换算成相对移动) var look: (CGFloat, CGFloat) -> Void = { _, _ in } + /// 画面上的手柄现在的样子(变了才给) + var pad: (PadState) -> Void = { _ in } var haptics = true private var counts: [String: Int] = [:] private var wheels: [String: Timer] = [:] + /// 按着的手柄的摇杆:哪一边(left / right)、推到哪里(-1...1,Y 向上为正) + private var sticks: [ObjectIdentifier: (side: String, x: Float, y: Float)] = [:] + private var padSent = PadState() func press(_ k: String) { counts[k, default: 0] += 1 guard counts[k] == 1 else { return } - if k.hasPrefix("mouse:") { + if k.hasPrefix("pad:") { + pushPad() + } else if k.hasPrefix("mouse:") { send([Input.button(String(k.dropFirst(6)), true)]) } else if k.hasPrefix("wheel:") { let dy = k == "wheel:up" ? 120 : -120 @@ -28,7 +36,9 @@ final class GameOutput { guard let n = counts[k] else { return } if n > 1 { counts[k] = n - 1; return } counts[k] = nil - if k.hasPrefix("mouse:") { + if k.hasPrefix("pad:") { + pushPad() + } else if k.hasPrefix("mouse:") { send([Input.button(String(k.dropFirst(6)), false)]) } else if k.hasPrefix("wheel:") { wheels.removeValue(forKey: k)?.invalidate() @@ -37,11 +47,45 @@ final class GameOutput { } } + /// 手柄的摇杆 `owner` 推到了 (`x`, `y`);都是 0 就是放开了 + func stick(_ owner: AnyObject, side: String, x: Float, y: Float) { + let id = ObjectIdentifier(owner) + if x == 0 && y == 0 { sticks[id] = nil } else { sticks[id] = (side: side, x: x, y: y) } + pushPad() + } + + /// 全部松开,画面上的手柄放回原位 func releaseAll() { for k in Array(counts.keys) { counts[k] = 1 release(k) } + sticks.removeAll() + pushPad() + } + + /// 画面上的手柄现在的样子:按着的手柄按钮、扳机(按到底),手柄的摇杆推到哪里(同一边两个摇杆时加起来) + private func pushPad() { + var b = 0, lt = 0, rt = 0 + for k in counts.keys { + guard let name = GameItem.padButton(k) else { continue } + switch name { + case "lt": lt = 255 + case "rt": rt = 255 + default: b |= XInput.names[name] ?? 0 + } + } + var l: (Float, Float) = (0, 0), r: (Float, Float) = (0, 0) + for s in sticks.values { + if s.side == "right" { r.0 += s.x; r.1 += s.y } else { l.0 += s.x; l.1 += s.y } + } + let state = PadState( + buttons: b, leftTrigger: lt, rightTrigger: rt, + leftX: PadState.stick(l.0), leftY: PadState.stick(l.1), rightX: PadState.stick(r.0), rightY: PadState.stick(r.1) + ) + guard state != padSent else { return } + padSent = state + pad(state) } func tick() { @@ -134,7 +178,8 @@ final class GameButton: GameControl { layer.borderColor = UIColor(white: 1, alpha: 0.35).cgColor layer.borderWidth = 1.5 label.text = item.title(os: os) - label.textColor = .white + // 手柄的 A B X Y:和 Xbox 手柄上一样的颜色 + label.textColor = item.label.isEmpty ? GameButton.padColor(item.keys) ?? .white : .white label.font = .systemFont(ofSize: max(11, min(18, item.size * 0.26)), weight: .bold) label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.5 @@ -196,6 +241,18 @@ final class GameButton: GameControl { setPressed(false) } + /// Xbox 手柄上 A B X Y 的颜色(按钮只按其中一个时) + static func padColor(_ keys: [String]) -> UIColor? { + guard keys.count == 1 else { return nil } + switch GameItem.padButton(keys[0]) { + case "a": return UIColor(red: 0.49, green: 0.83, blue: 0.13, alpha: 1) + case "b": return UIColor(red: 1, green: 0.35, blue: 0.31, alpha: 1) + case "x": return UIColor(red: 0.29, green: 0.66, blue: 1, alpha: 1) + case "y": return UIColor(red: 1, green: 0.82, blue: 0.18, alpha: 1) + default: return nil + } + } + private func setPressed(_ p: Bool) { UIView.animate(withDuration: 0.08) { self.transform = p ? CGAffineTransform(scaleX: 0.92, y: 0.92) : .identity @@ -204,10 +261,15 @@ final class GameButton: GameControl { } } -/// 摇杆:8 个方向(斜着推同时按两个),方向边界和中间的死区都有回差;推出边缘时可以加按一个键 +/// 摇杆:8 个方向(斜着推同时按两个),方向边界和中间的死区都有回差;推出边缘时可以加按一个键。 +/// 手柄的摇杆(`item.analog`)推多远发多远:中间一点死区,推到边缘是推到底,摇杆头上写着 L / R final class GameStick: GameControl { + /// 手柄的摇杆中间的死区(半径的比例):拇指放着不动、轻轻一碰不算推 + static let analogDead: CGFloat = 0.06 + private let base = UIView() private let knob = UIView() + private let knobLabel = UILabel() private var origin: CGPoint = .zero private var dir: Int? // 0..7,0 = 右,逆时针 private var sprinting = false @@ -223,6 +285,13 @@ final class GameStick: GameControl { knob.isUserInteractionEnabled = false addSubview(base) addSubview(knob) + if let side = item.analog { + knobLabel.text = side == "right" ? "R" : "L" + knobLabel.textColor = UIColor(white: 0, alpha: 0.7) + knobLabel.font = .systemFont(ofSize: max(11, item.size * 0.14), weight: .bold) + knobLabel.textAlignment = .center + knob.addSubview(knobLabel) + } } required init?(coder: NSCoder) { fatalError() } @@ -241,6 +310,7 @@ final class GameStick: GameControl { let k = radius * 0.8 knob.frame = CGRect(x: p.x - k / 2, y: p.y - k / 2, width: k, height: k) knob.layer.cornerRadius = k / 2 + knobLabel.frame = knob.bounds } override func touchesBegan(_ touches: Set, with event: UIEvent?) { @@ -260,6 +330,7 @@ final class GameStick: GameControl { override func reset() { set(dir: nil) setSprint(false) + if let side = item.analog { output.stick(self, side: side, x: 0, y: 0) } active = false origin = CGPoint(x: bounds.midX, y: bounds.midY) place(knobAt: origin) @@ -270,6 +341,16 @@ final class GameStick: GameControl { let dist = hypot(dx, dy) let clamped = dist > radius ? CGPoint(x: origin.x + dx / dist * radius, y: origin.y + dy / dist * radius) : p place(knobAt: clamped) + if let side = item.analog { + // 手柄的摇杆:死区以外按比例到边缘;Y 向上为正 + let d0 = GameStick.analogDead + let m = dist <= radius * d0 || radius <= 0 ? 0 : (min(dist / radius, 1) - d0) / (1 - d0) + output.stick(self, side: side, x: Float(m > 0 ? dx / dist * m : 0), y: Float(m > 0 ? -dy / dist * m : 0)) + if item.sprint != nil { + if m > 0 && dist > radius * 0.95 { setSprint(true) } else if dist < radius * 0.8 { setSprint(false) } + } + return + } // 死区有回差:按着方向时 0.18 以下才松开,没按时 0.28 以上才按下 let dead = radius * (dir == nil ? 0.28 : 0.18) if dist < dead { diff --git a/ios/Airhand/Session/GameModel.swift b/ios/Airhand/Session/GameModel.swift index ff70db4b..ce20be01 100644 --- a/ios/Airhand/Session/GameModel.swift +++ b/ios/Airhand/Session/GameModel.swift @@ -3,6 +3,8 @@ import Observation /// 游戏按键:叠在画面上的按钮和摇杆(控制电脑时用),和 Android 版的功能一样。 /// 按钮发的是协议里已有的按键、鼠标键、滚轮和相对移动,被控端不用做什么。 +/// 按钮、摇杆也可以是画面上的手柄(Xbox 360 手柄)的按钮(`pad:a` 这样)、方向键、左右摇杆:和接着的手柄一样 +/// 插到对方电脑上(见 Gamepads.swift),对方要能接手柄。 struct GameItem: Codable, Identifiable, Equatable { enum Kind: String, Codable { case button, stick } @@ -13,8 +15,8 @@ struct GameItem: Codable, Identifiable, Equatable { var y: Double /// 直径(点) var size: Double - /// 按钮:按下的键(最多 3 个,组合键按顺序按下、倒序松开):W3C 的 code,或者 `mouse:left`、`wheel:up` 这样的; - /// 摇杆:上、左、下、右 + /// 按钮:按下的键(最多 3 个,组合键按顺序按下、倒序松开):W3C 的 code,或者 `mouse:left`、`wheel:up`、`pad:a` 这样的; + /// 摇杆:上、左、下、右(也可以是手柄的方向键 [dpad]) var keys: [String] var label: String = "" /// 点一下切换(按下 / 松开),否则按住 @@ -25,18 +27,76 @@ struct GameItem: Codable, Identifiable, Equatable { var sprint: String? = nil /// 摇杆从拇指落下的地方开始 var floating = true + /// 摇杆是画面上的手柄的左 / 右摇杆(`left` / `right`):推多远发多远,不按 [keys]。 + /// 可选的:旧版本存的没有这一项,旧版本读到时当作 WASD 摇杆 + var analog: String? = nil static let wasd = ["KeyW", "KeyA", "KeyS", "KeyD"] static let arrows = ["ArrowUp", "ArrowLeft", "ArrowDown", "ArrowRight"] + /// 手柄的方向键(摇杆按方向键,8 个方向) + static let dpad = ["pad:up", "pad:left", "pad:down", "pad:right"] + + /// 画面上的手柄的按钮(XInput 的按钮位见 `XInput.names`;扳机 lt / rt 按着是按到底) + static let padButtons = ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "guide", "ls", "rs", "up", "down", "left", "right"] + + /// 手柄按钮上写的(和 Xbox 手柄一样);方向键前面加个 D,和键盘的方向键分开 + private static let padNames = [ + "a": "A", "b": "B", "x": "X", "y": "Y", "lb": "LB", "rb": "RB", "lt": "LT", "rt": "RT", + "back": "Back", "start": "Start", "guide": "Xbox", "ls": "LS", "rs": "RS", + "up": "D↑", "down": "D↓", "left": "D←", "right": "D→", + ] + + /// 手柄按钮的名字(`a`、`lt`……);不是手柄的按钮时为 nil + static func padButton(_ k: String) -> String? { + guard k.hasPrefix("pad:") else { return nil } + let b = String(k.dropFirst(4)) + return padButtons.contains(b) ? b : nil + } + + /// 用到了画面上的手柄(手柄的按钮、方向键、摇杆) + var usesPad: Bool { + analog != nil || keys.contains { GameItem.padButton($0) != nil } || sprint.flatMap(GameItem.padButton) != nil + } + + /// 摇杆推出边缘时可以加按的键:手柄的摇杆是按下摇杆(LS / RS),别的是 Shift、Ctrl、Alt、空格 + var sprintKeys: [String] { analog != nil ? ["pad:ls", "pad:rs"] : ["ShiftLeft", "ControlLeft", "AltLeft", "Space"] } + + /// 摇杆的哪一种:`wasd`、`arrows`、`dpad`、`left`、`right`(设置里选) + var stickKind: String { + get { + if let analog { return analog } + if keys == GameItem.dpad { return "dpad" } + return keys == GameItem.arrows ? "arrows" : "wasd" + } + set { + switch newValue { + case "left", "right": analog = newValue; keys = GameItem.wasd + case "dpad": analog = nil; keys = GameItem.dpad + case "arrows": analog = nil; keys = GameItem.arrows + default: analog = nil; keys = GameItem.wasd + } + // 换了一种摇杆,原来加按的键不合适了就去掉 + if let s = sprint, !sprintKeys.contains(s) { sprint = nil } + } + } /// 按钮上显示的文字 func title(os: OsKind) -> String { if !label.isEmpty { return label } - if kind == .stick { return keys == GameItem.arrows ? "↑←↓→" : "WASD" } + if kind == .stick { + switch stickKind { + case "left": return L.t("game_pad_left_stick") + case "right": return L.t("game_pad_right_stick") + case "dpad": return L.t("game_pad_dpad") + case "arrows": return "↑←↓→" + default: return "WASD" + } + } return keys.map { GameItem.keyLabel($0, os: os) }.joined(separator: "+") } static func keyLabel(_ k: String, os: OsKind) -> String { + if let b = padButton(k) { return padNames[b] ?? b } switch k { case "mouse:left": return L.t("game_mouse_left") case "mouse:right": return L.t("game_mouse_right") @@ -57,6 +117,9 @@ struct GameLayout: Codable, Identifiable, Equatable { var lookSpeed: Double = 1.0 var haptics = true var items: [GameItem] = [] + + /// 有画面上的手柄的按钮、摇杆(没有了的话拔掉画面上的手柄) + var usesPad: Bool { items.contains { $0.usesPad } } } /// 每台设备的选择:开没开、用哪个方案 @@ -145,7 +208,7 @@ final class GameStore { } } -/// 模板:射击、技能、方向键、空白(坐标按横屏摆) +/// 模板:射击、技能、方向键、手柄、空白(坐标按横屏摆) enum GameTemplates { static func button(_ x: Double, _ y: Double, _ size: Double, _ keys: [String], label: String = "", toggle: Bool = false, look: Bool = false) -> GameItem { GameItem(kind: .button, x: x, y: y, size: size, keys: keys, label: label, toggle: toggle, look: look) @@ -203,5 +266,32 @@ enum GameTemplates { ]) } + /// 画面上的 Xbox 360 手柄(和 Android 版的一样摆):左手左摇杆、方向键,右手 A B X Y、右摇杆, + /// 肩键扳机在上面两角,Back / 西瓜键 / Start 在中间 + static func gamepad() -> GameLayout { + func pad(_ x: Double, _ y: Double, _ size: Double, _ b: String) -> GameItem { button(x, y, size, ["pad:" + b]) } + func analog(_ x: Double, _ y: Double, _ size: Double, _ side: String) -> GameItem { + GameItem(kind: .stick, x: x, y: y, size: size, keys: GameItem.wasd, floating: true, analog: side) + } + return GameLayout(name: L.t("game_tpl_gamepad"), items: [ + analog(0.12, 0.58, 140, "left"), + GameItem(kind: .stick, x: 0.30, y: 0.80, size: 110, keys: GameItem.dpad, floating: false), + analog(0.64, 0.80, 110, "right"), + pad(0.875, 0.76, 54, "a"), + pad(0.949, 0.60, 54, "b"), + pad(0.801, 0.60, 54, "x"), + pad(0.875, 0.44, 54, "y"), + pad(0.06, 0.11, 50, "lt"), + pad(0.15, 0.11, 50, "lb"), + pad(0.82, 0.11, 50, "rb"), + pad(0.91, 0.11, 50, "rt"), + pad(0.42, 0.11, 40, "back"), + pad(0.50, 0.11, 40, "guide"), + pad(0.58, 0.11, 40, "start"), + pad(0.27, 0.45, 42, "ls"), + pad(0.52, 0.66, 42, "rs"), + ]) + } + static func blank() -> GameLayout { GameLayout(name: L.t("game_tpl_blank")) } } diff --git a/ios/Airhand/Session/SessionController.swift b/ios/Airhand/Session/SessionController.swift index 67f32f13..b30899a5 100644 --- a/ios/Airhand/Session/SessionController.swift +++ b/ios/Airhand/Session/SessionController.swift @@ -187,6 +187,8 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private var onScreen = false /// 对方接不了手柄的原因已经说过了(对方重新说了状态时再说) private var gamepadTold = false + /// 画面上的手柄为什么没发出去已经说过了 + private var screenPadTold = false let ui = SessionUIState() init(app: AppModel, session: RemoteSession) { @@ -239,6 +241,8 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract game.os = session.os game.output.send = { [weak self] e in self?.session.input(e) } game.output.look = { [weak self] dx, dy in self?.look(dx, dy) } + // 画面上的手柄:和接着的手柄一样交给 Gamepads(游戏让它震动时 iPhone 跟着震,方案里关了“按下时振动”就不震) + game.output.pad = { [weak self] s in self?.gamepads?.screen(s, rumble: self?.game.layout?.haptics ?? true) } view.addSubview(game) keyField.frame = CGRect(x: -100, y: -100, width: 10, height: 10) @@ -299,6 +303,7 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract session.onRumble = { [weak self] pad, large, small in self?.gamepads.rumble(pad, large: large, small: small) } session.onReleaseAll = { [weak self] in DispatchQueue.main.async { self?.gamepads.resync() } } gamepads.onRefused = { [weak self] in self?.gamepadRefused() } + gamepads.onScreenIdle = { [weak self] in self?.screenPadIdle() } observe { [weak self] in self?.sessionChanged() } observe { [weak self] in self?.gameChanged() } @@ -310,6 +315,8 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract private func gamepadsChanged() { let state = session.gamepadState if state == nil { gamepadTold = false } + // 开关、对方的说法变了:画面上的手柄再发不出去时重新说 + screenPadTold = false gamepads.refuse = state?.usable != true gamepads.active = onScreen && session.phase == .live && state != nil && session.gamepadEnabled } @@ -321,6 +328,21 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract app.show(L.t("gamepad_refused", GamepadPage.hint(s, os: session.os, detail: session.gamepadDetail))) } + /// 按了画面上的手柄,却没有交给对方:开关关着,或者对方没说它能不能接(旧版本)。一样只说一次 + private func screenPadIdle() { + guard !screenPadTold, onScreen, session.phase == .live else { return } + let text: String + if !session.gamepadEnabled { + text = L.t("gamepad_screen_off") + } else if session.gamepadState == nil { + text = L.t("gamepad_screen_unknown") + } else { + return + } + screenPadTold = true + app.show(text) + } + override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) session.decoder.setLayer(video.displayLayer) @@ -419,6 +441,8 @@ final class SessionController: UIViewController, Gestures.Out, UIPointerInteract let l = session.os.isPhone ? nil : app.games.active(session.code) game.apply(l) gestures.lookGain = l.map { CGFloat($0.lookSpeed) } + // 关掉了游戏按键、换成了没有手柄的方案:对方拔掉画面上的手柄(收起、松开时只是放回原位) + if l?.usesPad != true { gamepads?.screen(nil) } } private func updateOverlay() { diff --git a/ios/Airhand/Session/SessionMenu.swift b/ios/Airhand/Session/SessionMenu.swift index 8bc3934c..48bc74e5 100644 --- a/ios/Airhand/Session/SessionMenu.swift +++ b/ios/Airhand/Session/SessionMenu.swift @@ -551,6 +551,7 @@ struct GamePage: View { Button(L.t("game_tpl_shooter")) { create(GameTemplates.shooter()) } Button(L.t("game_tpl_skills")) { create(GameTemplates.skills()) } Button(L.t("game_tpl_arrows")) { create(GameTemplates.arrows()) } + Button(L.t("game_tpl_gamepad")) { create(GameTemplates.gamepad()) } Button(L.t("game_tpl_blank")) { create(GameTemplates.blank()) } } .alert(L.t("rename"), isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) { diff --git a/ios/Shared/L10n.swift b/ios/Shared/L10n.swift index 63943aff..6a329812 100644 --- a/ios/Shared/L10n.swift +++ b/ios/Shared/L10n.swift @@ -123,13 +123,16 @@ enum L { "privacy_note": "对方电脑前的人可以断开它的网络或者重启它来结束防窥模式", "gamepads": "手柄", "gamepad_toggle": "把手柄插到对方电脑上", "gamepad_ready": "这里接着的每个手柄都会作为一个 Xbox 360 手柄插到对方电脑上,游戏可以让它震动", - "gamepad_no_driver_windows": "对方电脑要先装 usbip-win2(免费、有签名的驱动)才能插虚拟手柄:在那台电脑上从 github.com/vadimgrn/usbip-win2/releases 下载安装,不用重启 Airhand", + "gamepad_no_driver_windows": "对方电脑要先装手柄驱动 usbip-win2:在那台电脑上重新运行 Airhand 的安装程序,选择安装它(也可以从 github.com/vadimgrn/usbip-win2/releases 下载),不用重启 Airhand", "gamepad_no_driver_linux": "对方电脑既没有 uinput 也没有 vhci-hcd:在那台电脑上运行 sudo modprobe uinput", "gamepad_no_permission": "对方电脑上的 Airhand 不能用 /dev/uinput:装上 Steam 的手柄规则(steam-devices),或者照 Airhand 文档加一条 udev 规则", "gamepad_failed": "对方电脑没能插上虚拟手柄(%@),再用手柄时会重试", "gamepad_unsupported": "对方电脑不能接手柄", "gamepad_unsupported_mac": "对方是 Mac:macOS 不允许插虚拟手柄", "gamepad_none": "在这台设备接着的手柄上按一下按键就开始用它", "gamepad_no_rumble": "不能震动", "gamepad_refused": "手柄没有发给对方:%@", + "gamepad_screen": "屏幕上的手柄(游戏按键)", + "gamepad_screen_off": "屏幕上的手柄没有发给对方:菜单 → 手柄里的开关关着", + "gamepad_screen_unknown": "屏幕上的手柄没有发给对方:对方电脑上的 Airhand 版本太旧,不能接手柄,在那台电脑上更新一下", "view_only_host": "对方是 iPhone / iPad,只能看不能操作", "files_sent": "已放进对方的剪贴板,到对方那里粘贴即可", "files_received": "对方复制了 %d 项", "files_save": "保存到“文件”", "files_saved": "已保存到“文件 › 我的 iPhone › Airhand”", "files_failed": "%@ 没有保存成功", @@ -152,6 +155,7 @@ enum L { "game_tpl_shooter": "射击(WASD)", "game_tpl_shooter_desc": "摇杆(推出边缘奔跑)、开火(按住拖动瞄准)、开镜、跳、蹲、换弹、武器 1–3", "game_tpl_skills": "技能(MOBA / ARPG)", "game_tpl_skills_desc": "Q W E R、D F、物品 1–4、B、空格;点画面就是点击", "game_tpl_arrows": "方向键(横版 / 模拟器)", "game_tpl_arrows_desc": "方向键摇杆、Z X C、空格、回车、Esc", + "game_tpl_gamepad": "手柄(Xbox)", "game_tpl_gamepad_desc": "画面上的 Xbox 360 手柄:左右摇杆、方向键、A B X Y、LB RB LT RT、Back、Start;对方电脑要能接手柄", "game_tpl_blank": "空白", "game_tpl_blank_desc": "自己添加按钮", "game_add": "添加", "game_layout_settings": "方案设置", "game_edit_hint": "拖动摆放 · 双指捏合调大小 · 点一下修改", "game_discard_title": "放弃修改?", "game_discard_text": "对这个方案的修改不会保存。", "game_discard": "放弃", @@ -160,10 +164,12 @@ enum L { "game_look": "拖动可以转视角", "game_look_desc": "按着的时候,例如一边开火一边瞄准", "game_size": "大小", "game_stick_keys": "方向", "game_sprint": "推出边缘时加按", "game_sprint_none": "不加", "game_floating": "从按下的地方开始", "game_floating_desc": "拇指不用正好落在摇杆中间", + "game_pad_dpad": "手柄方向键", "game_pad_left_stick": "手柄左摇杆", "game_pad_right_stick": "手柄右摇杆", + "game_pad_note": "手柄的按钮、摇杆发给对方电脑上的虚拟 Xbox 360 手柄(和这里接着的手柄一样),对方要能接手柄(Windows 要装 usbip-win2)", "game_opacity": "不透明度", "game_look_speed": "转视角灵敏度", "game_haptics": "按下时振动", "game_pick_title": "选择按键", "game_pick_combo": "组合键(最多 3 个,按顺序一起按下)", "game_group_mouse": "鼠标", "game_group_common": "常用", "game_group_letters": "字母", "game_group_digits": "数字", - "game_group_function": "功能键", "game_group_nav": "方向和编辑", "game_group_symbols": "符号", + "game_group_function": "功能键", "game_group_nav": "方向和编辑", "game_group_symbols": "符号", "game_group_pad": "手柄(Xbox)", "game_mouse_left": "左键", "game_mouse_right": "右键", "game_mouse_middle": "中键", "game_wheel_up": "滚轮↑", "game_wheel_down": "滚轮↓", "game_duplicate_item": "复制", "game_empty_layout_hint": "还没有按钮,点上面的 + 添加", "game_tip": "按住按钮就是按着那个键;空白处拖动在游戏隐藏光标时转视角。菜单 → 游戏按键 → 编辑布局可以自己摆。", // 快捷键 @@ -312,13 +318,16 @@ enum L { "privacy_note": "Someone at the remote computer can end privacy mode by disconnecting it from the network or restarting it", "gamepads": "Gamepads", "gamepad_toggle": "Plug gamepads into the remote computer", "gamepad_ready": "Each gamepad connected here shows up on the remote computer as an Xbox 360 controller. Games can make it vibrate", - "gamepad_no_driver_windows": "The remote computer needs usbip-win2 (a free, signed driver) for virtual gamepads: install it there from github.com/vadimgrn/usbip-win2/releases, no need to restart Airhand", + "gamepad_no_driver_windows": "The remote computer needs the gamepad driver usbip-win2: run the Airhand installer there again and choose to install it (or get it from github.com/vadimgrn/usbip-win2/releases). No need to restart Airhand", "gamepad_no_driver_linux": "The remote computer has neither uinput nor vhci-hcd: run sudo modprobe uinput there", "gamepad_no_permission": "Airhand on the remote computer can't use /dev/uinput: install Steam's controller rules (steam-devices) or add the udev rule from the Airhand docs", "gamepad_failed": "The remote computer couldn't plug in a virtual gamepad (%@). It tries again when you use the gamepad", "gamepad_unsupported": "The remote computer can't take gamepads", "gamepad_unsupported_mac": "The remote is a Mac: macOS doesn't allow virtual gamepads", "gamepad_none": "Press a button on a gamepad connected to this device to use it", "gamepad_no_rumble": "Can't vibrate", "gamepad_refused": "The gamepad isn't sent to the remote computer: %@", + "gamepad_screen": "On-screen gamepad (game keys)", + "gamepad_screen_off": "The on-screen gamepad isn't sent: Gamepads is turned off in the menu", + "gamepad_screen_unknown": "The on-screen gamepad isn't sent: Airhand on the remote computer is too old for gamepads, update it there", "view_only_host": "The remote is an iPhone / iPad: view only", "files_sent": "Put on the remote clipboard — paste it there", "files_received": "The remote copied %d items", "files_save": "Save to Files", "files_saved": "Saved to Files › On My iPhone › Airhand", "files_failed": "Couldn't save %@", @@ -339,6 +348,7 @@ enum L { "game_tpl_shooter": "Shooter (WASD)", "game_tpl_shooter_desc": "Stick (push to the edge to sprint), fire (hold and drag to aim), aim, jump, crouch, reload, weapons 1–3", "game_tpl_skills": "Skills (MOBA / ARPG)", "game_tpl_skills_desc": "Q W E R, D F, items 1–4, B, Space; tap the picture to click", "game_tpl_arrows": "Arrow keys (platformers / emulators)", "game_tpl_arrows_desc": "Arrow-key stick, Z X C, Space, Enter, Esc", + "game_tpl_gamepad": "Gamepad (Xbox)", "game_tpl_gamepad_desc": "An on-screen Xbox 360 controller: both sticks, D-pad, A B X Y, LB RB LT RT, Back, Start. The remote computer needs to take gamepads", "game_tpl_blank": "Blank", "game_tpl_blank_desc": "Add your own buttons", "game_add": "Add", "game_layout_settings": "Layout settings", "game_edit_hint": "Drag to place · pinch to resize · tap to edit", "game_discard_title": "Discard changes?", "game_discard_text": "Changes to this layout won't be saved.", "game_discard": "Discard", @@ -347,10 +357,12 @@ enum L { "game_look": "Drag to turn the view", "game_look_desc": "While held, e.g. aim while firing", "game_size": "Size", "game_stick_keys": "Directions", "game_sprint": "Extra key at the edge", "game_sprint_none": "None", "game_floating": "Start where you touch", "game_floating_desc": "No need to hit the center of the stick", + "game_pad_dpad": "D-pad", "game_pad_left_stick": "Left stick", "game_pad_right_stick": "Right stick", + "game_pad_note": "Gamepad controls go to a virtual Xbox 360 controller on the remote computer (like a gamepad connected here), so it needs to take gamepads (Windows: usbip-win2)", "game_opacity": "Opacity", "game_look_speed": "Look sensitivity", "game_haptics": "Vibrate on press", "game_pick_title": "Choose keys", "game_pick_combo": "Combination (up to 3 keys, pressed together in order)", "game_group_mouse": "Mouse", "game_group_common": "Common", "game_group_letters": "Letters", "game_group_digits": "Digits", - "game_group_function": "Function keys", "game_group_nav": "Navigation & editing", "game_group_symbols": "Symbols", + "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.", "combo_ctrl_alt_del": "Ctrl + Alt + Del", "combo_alt_tab": "Alt + Tab switch windows", "combo_win": "Win Start menu", diff --git a/ios/Tests/GameTests.swift b/ios/Tests/GameTests.swift new file mode 100644 index 00000000..71eb2b98 --- /dev/null +++ b/ios/Tests/GameTests.swift @@ -0,0 +1,88 @@ +import XCTest +@testable import Airhand + +/// 游戏按键里画面上的手柄:按钮、扳机、摇杆拼成整个手柄的样子;摇杆换种类;方案存取(和 Android 的 GameControlsTest 对应) +final class GameTests: XCTestCase { + func testPadButtonsTriggersAndSticksMakeUpThePad() { + let out = GameOutput() + var states: [PadState] = [] + var events: [JSON] = [] + out.pad = { states.append($0) } + out.send = { events += $0 } + + out.press("pad:a") + XCTAssertEqual(states.last, PadState(buttons: XInput.a)) + // 扳机按着是按到底 + out.press("pad:lt") + XCTAssertEqual(states.last, PadState(buttons: XInput.a, leftTrigger: 255)) + // 同一个键两处按着:都松开才松开 + out.press("pad:a") + out.release("pad:a") + XCTAssertEqual(states.count, 2) + out.release("pad:a") + XCTAssertEqual(states.last, PadState(leftTrigger: 255)) + + // 摇杆推到哪里发到哪里(Y 向上为正),放开就回到中间 + let stick = NSObject() + out.stick(stick, side: "left", x: 0, y: 1) + XCTAssertEqual(states.last, PadState(leftTrigger: 255, leftY: 32767)) + out.stick(stick, side: "left", x: 0, y: 0) + XCTAssertEqual(states.last, PadState(leftTrigger: 255)) + out.stick(stick, side: "right", x: -1, y: 0) + XCTAssertEqual(states.last, PadState(leftTrigger: 255, rightX: -32768)) + + // 全部松开:手柄放回原位;已经在原位就不再发 + out.releaseAll() + XCTAssertEqual(states.last, PadState()) + let n = states.count + out.releaseAll() + XCTAssertEqual(states.count, n) + + // 键盘的键照常发,不动手柄 + out.press("KeyW") + XCTAssertEqual(states.count, n) + XCTAssertEqual(events.count, 1) + XCTAssertTrue(events.allSatisfy { $0.str("type") == "key" }) + } + + func testStickKinds() { + var s = GameItem(kind: .stick, x: 0.5, y: 0.5, size: 150, keys: GameItem.wasd, sprint: "ShiftLeft") + XCTAssertFalse(s.usesPad) + XCTAssertEqual(s.stickKind, "wasd") + // Shift 不是手柄摇杆的加按键:换成手柄的摇杆时去掉 + s.stickKind = "left" + XCTAssertEqual(s.analog, "left") + XCTAssertNil(s.sprint) + XCTAssertTrue(s.usesPad) + s.sprint = "pad:ls" + s.stickKind = "right" + XCTAssertEqual(s.sprint, "pad:ls") + s.stickKind = "dpad" + XCTAssertEqual(s.keys, GameItem.dpad) + XCTAssertNil(s.analog) + XCTAssertNil(s.sprint) + XCTAssertTrue(s.usesPad) + XCTAssertEqual(GameItem.padButton("pad:lt"), "lt") + XCTAssertNil(GameItem.padButton("pad:zz")) + XCTAssertNil(GameItem.padButton("KeyA")) + XCTAssertEqual(GameItem.keyLabel("pad:guide", os: .windows), "Xbox") + } + + func testGamepadTemplateRoundTripsAndOldLayoutsStillLoad() throws { + let l = GameTemplates.gamepad() + XCTAssertTrue(l.usesPad) + XCTAssertFalse(GameTemplates.shooter().usesPad) + XCTAssertEqual(l.items.filter { $0.analog != nil }.count, 2) + let back = try JSONDecoder().decode(GameLayout.self, from: JSONEncoder().encode(l)) + XCTAssertEqual(back, l) + + // 以前存的摇杆没有 analog:照样读出来,是按键的摇杆 + let old = """ + {"id":"\(UUID().uuidString)","kind":"stick","x":0.2,"y":0.7,"size":150,"keys":["KeyW","KeyA","KeyS","KeyD"], + "label":"","toggle":false,"look":false,"floating":true} + """ + let item = try JSONDecoder().decode(GameItem.self, from: Data(old.utf8)) + XCTAssertNil(item.analog) + XCTAssertEqual(item.stickKind, "wasd") + } +} From 8d9ae9d1dd40a5b902d91c3f7b589959dfef0515 Mon Sep 17 00:00:00 2001 From: sqlpxc Date: Thu, 3 Dec 2026 00:41:07 +0800 Subject: [PATCH 3/3] fix(gamepads): tell the host about held pads again after input is dropped Gamepad states are only sent when they change. After a network stall the controller drops its queued input or the host drops late input, both replaced by "release all", so a trigger or button held still stayed released on the host until it moved. - link: the controller queue remembers what the UI last said about each pad, recorded as messages are queued so it always matches the queue order. When it drops queued input, its "release all" carries the current state of every pad and the removals it dropped; pads that aren't at rest are resent every 500 ms, which covers input the host dropped. Reading that state and queueing the resend happen under one lock, so a resend never lands after a newer release. - host: a late GamepadRemoved is still carried out (removing late does no harm; dropping it left a phantom pad plugged in). - console and iOS: before a session stops getting the gamepads, its held pads are put back to rest, so the resend of a session not in use never pulls back pads another session of the same controller is using. - Android: the same when gamepads stop going to the host (in the background, window focus lost, TV menu open), and the keys and axes gathered so far are cleared: their releases never arrive, and the next resync pressed them again. - docs: the gamepad notes in the protocol and the architecture. --- .../airhand/android/controller/Gamepads.kt | 33 +- .../android/ui/session/SessionActivity.kt | 15 +- client/src/lib/gamepad.ts | 21 +- client/src/lib/session.ts | 2 +- client/tests/gamepad.test.ts | 7 +- crates/airhand-link/src/controller/mod.rs | 3 +- crates/airhand-link/src/controller/queue.rs | 316 ++++++++++++++++-- crates/airhand-link/src/controller/session.rs | 12 + crates/airhand-link/src/host/streams.rs | 64 +++- crates/airhand-proto/src/session.rs | 4 + docs/architecture.md | 2 +- docs/architecture.zh-CN.md | 2 +- ios/Airhand/Controller/Gamepads.swift | 15 +- 13 files changed, 441 insertions(+), 55 deletions(-) diff --git a/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt b/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt index 222049c0..093c5d98 100644 --- a/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt +++ b/android/app/src/main/java/app/airhand/android/controller/Gamepads.kt @@ -174,17 +174,23 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool /** 这里接着的、用过的手柄(按编号) */ val pads: StateFlow> = _pads.asStateFlow() - /** 把手柄交给对方(会话 Live、对方能接、开关打开)。不是的时候手柄照常给系统 */ + /** 把手柄交给对方(会话 Live、对方能接、开关打开、窗口在前台有焦点)。不是的时候手柄照常给系统 */ @Volatile var active = false set(v) { if (field == v) return + if (!v) settle() field = v if (v) resync() else stopRumble() } - /** 暂时不拦(电视上开着菜单、对话框:用手柄选) */ + /** 暂时不拦(电视上开着菜单、对话框:用手柄选)。开始暂停时和 [active] 变成 false 一样让对方放回原位 */ var paused = false + set(v) { + if (field == v) return + if (v) settle() + field = v + } /** 拦下来了、但对方接不了手柄时(按下按钮):界面说一声为什么 */ var onRefused: (() -> Unit)? = null @@ -220,6 +226,29 @@ class Gamepads(context: Context, private val send: (events: List, now: Bool stopRumble() } + /** + * 不再把手柄交给对方之前([active] 变成 false、[paused]):让对方把按着的手柄放回原位,之后这里的变化它收不到。 + * 攒着的按键、轴也清掉:窗口不在前台、菜单开着时收不到它们的松开,留着的话下次交给对方([resync])会把早就松开的 + * 又按下去。实体手柄从原位重新攒起(摇杆要动一下才知道它在哪);画面上的手柄以 GameControls 说的为准 + */ + private fun settle() { + val events = ArrayList() + for (pad in 0 until MAX_PADS) { + val id = slots[pad] ?: continue + if (id != SCREEN) { + keyButtons[pad] = 0 + hatButtons[pad] = 0 + digitalTriggers[pad] = 0 + axes[pad] = null + } + val prev = sent[pad] ?: continue + if (prev == PadState()) continue + sent[pad] = PadState() + events += Input.gamepad(pad, PadState()) + } + if (active && !paused && !refuse && events.isNotEmpty()) send(events, true) + } + /** 对方把手柄放回了原位(释放所有按键)、刚能接手柄:下次有输入时把完整的状态发一遍 */ fun resync() { sent.fill(null) diff --git a/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt b/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt index ecaaa68f..6e453049 100644 --- a/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt +++ b/android/app/src/main/java/app/airhand/android/ui/session/SessionActivity.kt @@ -94,6 +94,12 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { /** 界面在前台(手柄的输入只在这时候来) */ private val started = MutableStateFlow(false) + /** + * 窗口有焦点:通知栏、对话框、分屏时别的窗口拿走了焦点,手柄的按键、摇杆(包括正按着的那几个的松开)就不来了, + * 这时也不把手柄交给对方(交出去之前让对方放回原位,见 [Gamepads.active]) + */ + private val focused = MutableStateFlow(false) + override val keyboard = KeyboardController( swapCtrlCommand = { session?.let { it.os == OsKind.MAC && it.swapCtrlCommand.value } == true }, ) { events -> session?.input(events, true) } @@ -198,8 +204,8 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { } } lifecycleScope.launch { - combine(s.phase, s.gamepadState, s.gamepadEnabled, started) { phase, st, on, fg -> - Triple(phase == RemoteSession.Phase.Live && st != null && on && fg, st, on) + combine(s.phase, s.gamepadState, s.gamepadEnabled, started, focused) { phase, st, on, fg, focus -> + Triple(phase == RemoteSession.Phase.Live && st != null && on && fg && focus, st, on) }.collect { (active, st, _) -> pads.refuse = st?.usable != true pads.active = active @@ -267,6 +273,11 @@ class SessionActivity : ComponentActivity(), RemoteView.Host { started.value = false } + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + focused.value = hasFocus + } + /** * 不是从界面上离开的([exit])却要结束了:在最近任务里把应用划掉了,而进程还活着(例如本机正在被控,前台服务撑着进程)。 * 这时没人看得到画面、也没处点断开,会话不能留在后台一直连着(对方开着防窥的话一直黑屏、本机的人用不了): diff --git a/client/src/lib/gamepad.ts b/client/src/lib/gamepad.ts index db18da68..6f4d6315 100644 --- a/client/src/lib/gamepad.ts +++ b/client/src/lib/gamepad.ts @@ -2,8 +2,9 @@ // 被控端为每个手柄插上一个虚拟的 Xbox 360 手柄,游戏让它震动时这里的手柄跟着震。 // // * 整个网页一个 GamepadHub(navigator.getGamepads 是全局的),手柄交给当前在操作的会话(正在查看、画面可以操作, -// 见 session.ts 的 syncGamepads):同一时刻只有一个会话收到手柄。换了会话时,新的会话先收到一遍所有手柄的完整状态 -// (之前那个会话失去焦点时已经让对方把手柄放回原位了),以及空着的编号的"拔掉了"(它可能还以为插着); +// 见 session.ts 的 syncGamepads):同一时刻只有一个会话收到手柄。不再交给一个会话之前,先让它把按着的手柄放回原位 +// (之后这里的变化它收不到;控制端服务还会把按着的隔一会儿再告诉它一次,见 airhand_link 的 controller::queue)。 +// 换了会话时,新的会话先收到一遍所有手柄的完整状态,以及空着的编号的"拔掉了"(它可能还以为插着); // * 手柄的编号(pad,0..MAX_PADS-1):先接上的用小的,拔掉之后它的编号空出来给下一个; // * 按 W3C 的标准布局(mapping "standard")对应到 XInput:按钮的顺序、扳机是按钮 6 和 7 的 value、摇杆 Y 向下为正 // (XInput 向上为正,要反过来)。不是标准布局的手柄照同样的顺序猜; @@ -66,6 +67,11 @@ export interface PadState { rightY: number; } +/** 原位:什么也没按,摇杆在正中 */ +const REST: PadState = { buttons: 0, leftTrigger: 0, rightTrigger: 0, leftX: 0, leftY: 0, rightX: 0, rightY: 0 }; + +const atRest = (s: PadState) => (Object.keys(REST) as (keyof PadState)[]).every((k) => s[k] === 0); + type ButtonLike = Pick; /** -1..1 → -32768..32767 */ @@ -205,9 +211,18 @@ export class GamepadHub { this.syncTimer(); } - /** `t` 不再收手柄(不在前台了、断开了)。手柄放回原位由会话自己让对方做(releaseAll) */ + /** + * `t` 不再收手柄(不在前台了、断开了):先让对方把按着的手柄放回原位(之后这里的变化它收不到)。 + * 不能只靠画面失去焦点时的 releaseAll:会话不在前台时画面不一定失去了焦点,而且 releaseAll 之后紧接着会重新发 + * 手柄现在的样子(resync) + */ release(t: GamepadTarget) { if (this.target !== t) return; + const rest: InputEvent[] = []; + this.sent.forEach((s, pad) => { + if (s && !atRest(s)) rest.push(padEvent(pad, REST)); + }); + if (rest.length) t.gamepadInput(rest, true); this.stopRumble(); this.target = null; this.syncTimer(); diff --git a/client/src/lib/session.ts b/client/src/lib/session.ts index c7a448af..f890b4f6 100644 --- a/client/src/lib/session.ts +++ b/client/src/lib/session.ts @@ -1294,7 +1294,7 @@ export class RemoteSession implements GamepadTarget { /** * 手柄:正在查看、画面可以操作、连着、对方说了它能不能接时,本机的手柄交给这个会话(接不了的也要:按下按钮时说一声为什么)。 - * 不再交给它时,对方的手柄在它失去焦点时已经放回了原位(releaseAll) + * 不再交给它时,GamepadHub 先让对方把按着的手柄放回原位 */ private syncGamepads() { const want = this.foreground && this.interactive && this.sid !== null && !this.disposed && this.gamepadState !== null; diff --git a/client/tests/gamepad.test.ts b/client/tests/gamepad.test.ts index b3ecb65b..d92ea4f1 100644 --- a/client/tests/gamepad.test.ts +++ b/client/tests/gamepad.test.ts @@ -100,10 +100,15 @@ test("交给正在操作的会话:编号按接上的先后,变了才发, hub.resync(b); hub.poll(); assert.deepEqual(b.got.at(-1), [[{ type: "gamepad", pad: 0 }, { type: "gamepad", pad: 1, buttons: BUTTONS.a | BUTTONS.b }], true]); + // 不再收手柄:先让对方把按着的放回原位(第 0 个本来就在原位,不用说),之后不再收 hub.release(b); + assert.deepEqual(b.got.at(-1), [[{ type: "gamepad", pad: 1 }], true]); pads[0].press(2); hub.poll(); - assert.equal(b.got.length, 4, "放开之后不再收"); + assert.equal(b.got.length, 5, "放开之后不再收"); + hub.claim(a); + hub.release(a); + assert.deepEqual(a.got.at(-1), [[{ type: "gamepad", pad: 1 }], true], "按着的放回原位"); }); test("震动:只认正在操作的会话的;震着时定时重新放;换了会话、拔掉时停下", () => { diff --git a/crates/airhand-link/src/controller/mod.rs b/crates/airhand-link/src/controller/mod.rs index abfe41f9..d2a94d16 100644 --- a/crates/airhand-link/src/controller/mod.rs +++ b/crates/airhand-link/src/controller/mod.rs @@ -58,7 +58,8 @@ //! 被控端用 [`SessionEvent::Gamepad`] 说明它能不能接手柄(见 `airhand_proto::session` 的"手柄"),能接时界面把本机 //! 手柄的状态当作输入发过去(`{"type":"gamepad","pad":0,...}`、拔掉时 `gamepadRemoved`,和键盘鼠标在同一个 //! [`Command::Input`] 里),游戏让手柄震动时收到 [`SessionEvent::Rumble`]。同一个手柄只有摇杆、扳机变了的相邻几个状态 -//! 在排队时合并(见 [`queue`])。 +//! 在排队时合并;不在原位的手柄每隔一会儿再发一次,丢掉排着的输入时补上每个手柄现在的样子:被控端放回原位之后 +//! 按着不动的不会一直是松开的(见 [`queue`])。 //! //! # 防窥模式 //! diff --git a/crates/airhand-link/src/controller/queue.rs b/crates/airhand-link/src/controller/queue.rs index 382b4071..a6400c85 100644 --- a/crates/airhand-link/src/controller/queue.rs +++ b/crates/airhand-link/src/controller/queue.rs @@ -8,6 +8,7 @@ //! 补发一个"释放所有按键"(丢掉的里面可能有松开按键),会话照常继续——不在网络恢复时把一串过时的远程操作补发出去, //! 也不因为网络卡了一下就断开重连。真正失联由会话的超时处理。 //! 丢掉输入之后还是放不下(例如排满了不能丢的命令)才算会话失败([`Sender::failed`])。 +//! 手柄不一样:它的状态只在变了的时候发,按着不动的被放回原位之后就没人再告诉被控端了,所以另外记着、补上(见 [`Pads`])。 //! //! 这里只管得了还在队列里的输入:断网时往 QUIC 里写不会阻塞,写出去的输入进了 QUIC 的发送缓冲, //! 网络恢复后照样发出去。所以输入还带着排进队列的时刻([`ControllerMsg::Input`] 的 `t`), @@ -18,12 +19,12 @@ use crate::queue::{Item, Limit, Mail, Mailbox}; use crate::transport::Frames; use airhand_proto::{ framing, - session::{ControllerMsg, INPUT_MAX_AGE, InputEvent}, + session::{ControllerMsg, INPUT_MAX_AGE, InputEvent, MAX_GAMEPADS}, }; use bytes::Bytes; -use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Instant; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use tracing::warn; const LIMIT: Limit = Limit { @@ -60,6 +61,80 @@ struct Meta { at: Instant, /// 输入里的 `t`(合并相对移动时用最早的那一个) t: u64, + /// 这条输入拔掉了哪几个手柄(第 `i` 位是第 `i` 个):丢掉它时要另外告诉被控端(见 [`drop_input`]) + removed: u8, +} + +/// 按着的手柄隔这么久再告诉被控端一次(见 [`Pads`]):网络卡过之后,最多这么久被控端就又知道它按着了 +pub(super) const PAD_REFRESH: Duration = Duration::from_millis(500); + +/// 界面最近说的每个手柄现在的样子(`InputEvent::Gamepad`;没有、拔掉了的是 `None`)。 +/// +/// 手柄的状态只在变了的时候发。被控端把手柄放回原位之后——这里丢掉了排着的输入,或者被控端丢掉了晚到的输入, +/// 两种都换成了"释放所有按键"——按着不动的扳机、按钮、推到头的摇杆就再也没人告诉它了(赛车游戏的油门)。所以: +/// +/// * 这里丢掉输入时,补的"释放所有按键"后面跟着丢掉的"拔掉了"和每个手柄现在的样子([`drop_input`]),一条消息; +/// * 被控端丢掉的这里不知道:不在原位的手柄每 [`PAD_REFRESH`] 再说一次([`Sender::refresh_pads`])。 +/// 在原位的不说:被控端放回原位本来就是原位;同一个控制端的另一个会话连着同一台被控端、正在用这几个手柄时 +/// (被控端的手柄按控制端算,几个会话共用),不在用的这个会话也不会每隔一会儿把它们拉回原位——界面不再把手柄交给 +/// 一个会话之前,先让它把手柄放回原位(控制台的 `GamepadHub.release`、手机上的 `Gamepads`)。 +/// +/// 界面的"释放所有按键"同样把这里记着的放回原位(被控端也是这么做的),之后界面再说现在的样子。 +#[derive(Default)] +struct Pads([Option; MAX_GAMEPADS as usize]); + +impl Pads { + /// 界面发了这些输入 + fn saw(&mut self, events: &[InputEvent]) { + for e in events { + match *e { + InputEvent::Gamepad { pad, .. } if pad < MAX_GAMEPADS => { + self.0[pad as usize] = Some(e.clone()); + } + InputEvent::GamepadRemoved { pad } if pad < MAX_GAMEPADS => { + self.0[pad as usize] = None + } + InputEvent::ReleaseAll => { + for (pad, s) in (0..).zip(&mut self.0) { + if s.is_some() { + *s = Some(at_rest(pad)); + } + } + } + _ => {} + } + } + } + + /// 不在原位的手柄([`Sender::refresh_pads`] 再说一次的) + fn held(&self) -> impl Iterator { + self.0 + .iter() + .zip(0..) + .filter_map(|(s, pad)| s.as_ref().filter(|s| **s != at_rest(pad))) + } +} + +/// 第 `pad` 个手柄在原位:什么也没按,摇杆在正中 +fn at_rest(pad: u8) -> InputEvent { + InputEvent::Gamepad { + pad, + buttons: 0, + left_trigger: 0, + right_trigger: 0, + left_x: 0, + left_y: 0, + right_x: 0, + right_y: 0, + } +} + +/// 这批输入拔掉了哪几个手柄([`Meta::removed`]) +fn removed_pads(events: &[InputEvent]) -> u8 { + events.iter().fold(0, |r, e| match *e { + InputEvent::GamepadRemoved { pad } if pad < MAX_GAMEPADS => r | (1 << pad), + _ => r, + }) } /// 只留最新值的槽位:画质设置 @@ -70,6 +145,9 @@ struct Shared { mail: Mailbox, /// 排满了不能丢的命令:会话失败 failed: AtomicBool, + /// 界面说的每个手柄现在的样子。排进 `mail` 时才记(拿着它的锁,[`Sender::queue`]),所以总是队列里最后说的; + /// 和 `mail` 一起锁时先锁 `mail` + pads: Mutex, } #[derive(Clone)] @@ -80,6 +158,7 @@ pub(super) fn channel() -> (Sender, Receiver) { let shared = Arc::new(Shared { mail: Mailbox::new(SLOTS), failed: AtomicBool::new(false), + pads: Mutex::default(), }); (Sender(shared.clone()), Receiver(shared)) } @@ -106,13 +185,6 @@ pub(super) fn input(events: Vec) -> ControllerMsg { } } -fn release_msg(t: u64) -> ControllerMsg { - ControllerMsg::Input { - t, - events: vec![InputEvent::ReleaseAll], - } -} - fn delta_msg(t: u64, (dx, dy): (i32, i32)) -> ControllerMsg { ControllerMsg::Input { t, @@ -120,13 +192,29 @@ fn delta_msg(t: u64, (dx, dy): (i32, i32)) -> ControllerMsg { } } -/// 丢掉排着的输入,补一个"释放所有按键"排在最前面。返回丢掉了几条(没有可丢的就什么也不做) -fn drop_input(m: &mut Mail) -> usize { +/// 丢掉排着的输入,补一个"释放所有按键"排在最前面。返回丢掉了几条(没有可丢的就什么也不做)。 +/// +/// 被控端释放所有按键时把手柄也放回原位,所以同一条消息里接着补上手柄(见 [`Pads`]):先是丢掉的输入里拔掉的手柄 +/// (不说的话被控端会一直插着它),再是每个手柄现在的样子(之后又插上的手柄也在里面)。这条消息也是输入, +/// 它也丢掉的话(网络还没好)下一条照样补上:拔掉的记在它的 [`Meta::removed`] 里 +fn drop_input(m: &mut Mail, pads: &Mutex) -> usize { + let removed = m + .items() + .filter(|i| i.meta.kind.is_input()) + .fold(0, |r, i| r | i.meta.removed); let dropped = m.retain(|i| !i.meta.kind.is_input()); if dropped > 0 { + let mut events = vec![InputEvent::ReleaseAll]; + events.extend( + (0..MAX_GAMEPADS) + .filter(|pad| removed & (1 << pad) != 0) + .map(|pad| InputEvent::GamepadRemoved { pad }), + ); + events.extend(pads.lock().unwrap().0.iter().flatten().cloned()); // 现在的时刻:被控端不会把它当成过时的输入 let t = now_us(); - let release = encode(&release_msg(t)).expect("ReleaseAll always encodes"); + let release = encode(&ControllerMsg::Input { t, events }) + .expect("releasing keys and at most every gamepad fits the control lane"); m.push_front( release, Meta { @@ -134,6 +222,7 @@ fn drop_input(m: &mut Mail) -> usize { delta: (0, 0), at: Instant::now(), t, + removed, }, ); } @@ -211,9 +300,55 @@ impl Sender { self.0.failed.load(Ordering::Relaxed) } + /// 不在原位的手柄再告诉被控端一次(见 [`Pads`])。会话每 [`PAD_REFRESH`] 调用一次。 + /// 一个手柄一条:和排着的、同一个手柄按钮一样的状态合并,网络卡着的时候不会越积越多。 + /// + /// 读记着的样子和排进队列在同一把锁里:记着的总是队列里最后说的([`Sender::queue`] 排进去时才记), + /// 这里排的就是最新的。分开的话,界面刚松开的扳机可能排在这里读到的"按着"前面,被控端就一直按着了 + /// (松开的手柄不会再说) + pub fn refresh_pads(&self) -> Result<(), Problem> { + let mail = &self.0.mail; + let mut m = mail.lock(); + let held: Vec = self.0.pads.lock().unwrap().held().cloned().collect(); + let mut result = Ok(()); + for e in held { + let msg = input(vec![e]); + result = encode(&msg).and_then(|bytes| self.queue(&mut m, &msg, bytes)); + if result.is_err() { + break; + } + } + drop(m); + mail.wake(); + result + } + fn send_one(&self, msg: ControllerMsg) -> Result<(), Problem> { - let slot = matches!(msg, ControllerMsg::Settings(_)).then_some(SETTINGS); - let (kind, delta, t) = match &msg { + // 编码不拿着锁 + let bytes = encode(&msg)?; + let mail = &self.0.mail; + let mut m = mail.lock(); + let result = self.queue(&mut m, &msg, bytes); + drop(m); + mail.wake(); + result + } + + /// 把编好的 `msg` 排进队列(拿着队列的锁)。界面说的手柄的样子在这时记下([`Pads`]):和队列里的先后一致 + fn queue( + &self, + m: &mut Mail, + msg: &ControllerMsg, + mut bytes: Bytes, + ) -> Result<(), Problem> { + if m.closed { + return Err(Problem::SessionEnded); + } + if matches!(msg, ControllerMsg::Settings(_)) { + m.set(SETTINGS, bytes); + return Ok(()); + } + let (kind, delta, t) = match msg { ControllerMsg::Input { t, events } => match events[..] { [InputEvent::MouseMove { .. }] => (Kind::Move, (0, 0), *t), [InputEvent::MouseDelta { dx, dy }] => (Kind::Delta, (dx, dy), *t), @@ -222,23 +357,16 @@ impl Sender { }, _ => (Kind::Command, (0, 0), 0), }; - let mut bytes = encode(&msg)?; - let mail = &self.0.mail; - let mut m = mail.lock(); - if m.closed { - return Err(Problem::SessionEnded); - } - if let Some(slot) = slot { - m.set(slot, bytes); - drop(m); - mail.wake(); - return Ok(()); - } + let removed = match msg { + ControllerMsg::Input { events, .. } => removed_pads(events), + _ => 0, + }; let mut meta = Meta { kind, delta, at: Instant::now(), t, + removed, }; // 移动只和紧挨着的移动合并(队尾只会是输入或命令,确认这类状态不在队列里);手柄只和紧挨着的、 // 同一个手柄按钮一样的状态合并 @@ -259,7 +387,7 @@ impl Sender { } if m.full(LIMIT, bytes.len()) { // 网络卡住了:排着的输入已经没有意义,丢掉它们再放这一条 - let dropped = drop_input(&mut m); + let dropped = drop_input(m, &self.0.pads); warn!( dropped, "controller command queue full, dropped the queued input" @@ -267,8 +395,6 @@ impl Sender { if m.full(LIMIT, bytes.len()) { self.0.failed.store(true, Ordering::Relaxed); m.close(); - drop(m); - mail.wake(); return Err(Problem::failed("controller command queue overflow")); } } @@ -277,8 +403,9 @@ impl Sender { before: None, meta, }); - drop(m); - mail.wake(); + if let ControllerMsg::Input { events, .. } = msg { + self.0.pads.lock().unwrap().saw(events); + } Ok(()) } } @@ -294,7 +421,7 @@ impl Receiver { .find(|i| i.meta.kind.is_input()) .is_some_and(|i| i.meta.at.elapsed() > INPUT_MAX_AGE) { - let dropped = drop_input(m); + let dropped = drop_input(m, &self.0.pads); warn!( dropped, "dropped stale input queued for more than {INPUT_MAX_AGE:?}" @@ -556,6 +683,127 @@ mod tests { ); } + fn gamepad(pad: u8, buttons: u16, left_x: i16) -> InputEvent { + InputEvent::Gamepad { + pad, + buttons, + left_trigger: 0, + right_trigger: 0, + left_x, + left_y: 0, + right_x: 0, + right_y: 0, + } + } + + /// 丢掉排着的输入时,补的"释放所有按键"后面跟着丢掉的"拔掉了"和每个手柄现在的样子:被控端放回原位之后, + /// 按着不动的没人会再说。补的这条也丢掉的话下一条照样补上;界面让释放所有按键之后,补的是原位 + #[tokio::test] + async fn dropping_input_restores_the_gamepads() { + let (tx, mut rx) = channel(); + tx.send(input(vec![gamepad(0, 0x1000, 100)])).unwrap(); + tx.send(input(vec![gamepad(1, 0, 0)])).unwrap(); + tx.send(input(vec![gamepad(2, 0, 5)])).unwrap(); + // 拔掉了、又插上一个:被控端要先拔掉旧的 + tx.send(input(vec![InputEvent::GamepadRemoved { pad: 2 }])) + .unwrap(); + tx.send(input(vec![gamepad(2, 0x2000, 0)])).unwrap(); + let restore = [ + InputEvent::ReleaseAll, + InputEvent::GamepadRemoved { pad: 2 }, + gamepad(0, 0x1000, 100), + gamepad(1, 0, 0), + gamepad(2, 0x2000, 0), + ]; + assert_eq!(drop_input(&mut tx.0.mail.lock(), &tx.0.pads), 5); + assert_eq!(events(&queued(&tx)[0]), restore); + // 网络还没好,补的这条也丢掉了:下一条一样(拔掉的也在) + assert_eq!(drop_input(&mut tx.0.mail.lock(), &tx.0.pads), 1); + assert_eq!(events(&queued(&tx)[0]), restore); + assert_eq!(events(&decode(&rx.recv().await.unwrap())), restore); + + // 界面让释放所有按键:记着的都在原位(被控端也是),之后界面再说现在的样子 + tx.send(input(vec![InputEvent::ReleaseAll])).unwrap(); + drop_input(&mut tx.0.mail.lock(), &tx.0.pads); + assert_eq!( + events(&queued(&tx)[0]), + [ + InputEvent::ReleaseAll, + gamepad(0, 0, 0), + gamepad(1, 0, 0), + gamepad(2, 0, 0) + ] + ); + // 没有手柄的会话:和以前一样只有"释放所有按键" + let (tx, _rx) = channel(); + tx.send(input(vec![InputEvent::Key { + code: "KeyA".into(), + down: true, + }])) + .unwrap(); + drop_input(&mut tx.0.mail.lock(), &tx.0.pads); + assert!(is_release(&queued(&tx)[0])); + } + + /// 不在原位的手柄每隔一会儿再说一次(被控端丢掉了晚到的输入、把它们放回了原位的话,这样就又按上了), + /// 和排着的同一个手柄的状态合并;在原位的、拔掉了的、界面让释放所有按键之后的不说 + #[test] + fn held_gamepads_are_refreshed() { + let (tx, _rx) = channel(); + tx.send(input(vec![gamepad(0, 0x1000, 0), gamepad(1, 0, 0)])) + .unwrap(); + tx.refresh_pads().unwrap(); + let q = queued(&tx); + assert_eq!(q.len(), 2); + assert_eq!(events(&q[1]), [gamepad(0, 0x1000, 0)]); + tx.refresh_pads().unwrap(); + assert_eq!(queued(&tx).len(), 2, "merged with the queued state"); + tx.send(input(vec![InputEvent::ReleaseAll])).unwrap(); + tx.refresh_pads().unwrap(); + assert_eq!(queued(&tx).len(), 3, "at rest after releasing all"); + tx.send(input(vec![gamepad(1, 0, -300)])).unwrap(); + tx.refresh_pads().unwrap(); + let q = queued(&tx); + assert_eq!(q.len(), 4); + assert_eq!(events(&q[3]), [gamepad(1, 0, -300)]); + // 松开了:最后排着的是原位,这里不会再把它推回去 + tx.send(input(vec![gamepad(1, 0, 0)])).unwrap(); + tx.refresh_pads().unwrap(); + assert_eq!(events(queued(&tx).last().unwrap()), [gamepad(1, 0, 0)]); + tx.send(input(vec![InputEvent::GamepadRemoved { pad: 1 }])) + .unwrap(); + let n = queued(&tx).len(); + tx.refresh_pads().unwrap(); + assert_eq!(queued(&tx).len(), n, "unplugged"); + } + + /// 界面松开手柄的同时会话在补发按着的:补发的不会排到松开后面(不然被控端就一直按着了,松开的不会再说) + #[test] + fn refreshing_never_overtakes_a_release() { + for _ in 0..20 { + let (tx, _rx) = channel(); + let refresher = tx.clone(); + let done = Arc::new(AtomicBool::new(false)); + let stop = done.clone(); + let t = std::thread::spawn(move || { + while !stop.load(Ordering::Relaxed) { + refresher.refresh_pads().unwrap(); + } + }); + for x in 0..200 { + tx.send(input(vec![gamepad(0, 0x1000, x)])).unwrap(); + tx.send(input(vec![gamepad(0, 0, 0)])).unwrap(); + } + done.store(true, Ordering::Relaxed); + t.join().unwrap(); + let last = queued(&tx) + .iter() + .flat_map(|m| events(m).to_vec()) + .rfind(|e| matches!(e, InputEvent::Gamepad { pad: 0, .. })); + assert_eq!(last, Some(gamepad(0, 0, 0))); + } + } + /// 输入过时了:丢掉排着的输入、补一个"释放所有按键",其它命令照发,会话继续 #[tokio::test] async fn stale_input_is_dropped_and_keys_released() { @@ -602,7 +850,7 @@ mod tests { [ControllerMsg::Input { t: 100, events }] if events[..] == [InputEvent::MouseDelta { dx: 3, dy: 0 }] )); let before = now_us(); - assert_eq!(drop_input(&mut tx.0.mail.lock()), 1); + assert_eq!(drop_input(&mut tx.0.mail.lock(), &tx.0.pads), 1); let q = queued(&tx); assert!(is_release(&q[0])); assert!(matches!(q[0], ControllerMsg::Input { t, .. } if t >= before)); diff --git a/crates/airhand-link/src/controller/session.rs b/crates/airhand-link/src/controller/session.rs index af42116c..d7c5094a 100644 --- a/crates/airhand-link/src/controller/session.rs +++ b/crates/airhand-link/src/controller/session.rs @@ -583,6 +583,17 @@ pub(super) async fn run( let reporter_stats = stats.clone(); let clip_in = local_clip.clone(); let keyframe_tx = tx.clone(); + // 按着的手柄隔一会儿再告诉被控端一次:它丢掉了晚到的输入、把手柄放回原位的话,这样就又按上了(见 queue 的 Pads) + let pads_tx = tx.clone(); + let pads = async move { + let mut tick = tokio::time::interval(super::queue::PAD_REFRESH); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tick.tick().await; + // 队列失败了、会话结束了:写任务会结束会话 + let _ = pads_tx.refresh_pads(); + } + }; let acker = feedback.clone(); let on_direct = video_direct.clone(); let video_stats = recv.video_stats(); @@ -966,6 +977,7 @@ pub(super) async fn run( () = direct => Ok(()), () = mic => Ok(()), () = notices => Ok(()), + () = pads => Ok(()), r = writer => r.and(Err(Problem::SessionEnded.into())), r = bulk_writer => r.and(Err(Problem::SessionEnded.into())), }; diff --git a/crates/airhand-link/src/host/streams.rs b/crates/airhand-link/src/host/streams.rs index 6952b967..13bb906d 100644 --- a/crates/airhand-link/src/host/streams.rs +++ b/crates/airhand-link/src/host/streams.rs @@ -234,6 +234,23 @@ impl Express { } } +/// 晚到太久的一批输入(见 `airhand_proto::session` 的"过时的输入")还做什么:不在网络恢复后重放过时的操作。 +/// 这一串里的第一批(`released` 为假)换成"释放所有按键"(丢掉的里面可能有松开按键),之后的都不要。 +/// +/// 拔掉手柄(`GamepadRemoved`)照样做:晚一点拔掉不会做错什么,丢掉的话那个虚拟手柄会一直插着——控制端只说一次。 +/// 按着的手柄不用管:控制端每隔一会儿会再说一次(`crate::controller` 的队列)。没什么可做的是 `None` +fn late_input(events: Vec, released: bool) -> Option> { + let removed = events + .into_iter() + .filter(|e| matches!(e, InputEvent::GamepadRemoved { .. })); + let out: Vec = (!released) + .then_some(InputEvent::ReleaseAll) + .into_iter() + .chain(removed) + .collect(); + (!out.is_empty()).then_some(out) +} + /// 控制端的一条消息交给会话时是什么请求(直连的回答不在这里)。没什么可做的是 `None` pub(crate) fn request(m: ControllerMsg) -> Option { Some(match m { @@ -661,16 +678,14 @@ async fn read_all(r: Readers) -> Result<()> { if !stale { released = false; ControllerMsg::Input { t, events } - } else if released { - continue; } else { - // 不在网络恢复后重放过时的操作;丢掉的里面可能有松开按键,所以松开所有按键 - warn!(session_id, "dropping input that arrived too late"); - released = true; - ControllerMsg::Input { - t, - events: vec![InputEvent::ReleaseAll], + if !released { + warn!(session_id, "dropping input that arrived too late"); } + let late = late_input(events, released); + released = true; + let Some(events) = late else { continue }; + ControllerMsg::Input { t, events } } } m => m, @@ -792,6 +807,39 @@ mod tests { ); } + /// 晚到太久的输入:一串里的第一批换成"释放所有按键",之后的不要;拔掉手柄照样做(控制端不会再说) + #[test] + fn late_input_only_releases_and_unplugs() { + let key = InputEvent::Key { + code: "KeyA".into(), + down: true, + }; + let pad = InputEvent::Gamepad { + pad: 1, + buttons: 0x1000, + left_trigger: 0, + right_trigger: 0, + left_x: 0, + left_y: 0, + right_x: 0, + right_y: 0, + }; + let removed = InputEvent::GamepadRemoved { pad: 0 }; + assert_eq!( + late_input(vec![key.clone(), pad.clone()], false), + Some(vec![InputEvent::ReleaseAll]) + ); + assert_eq!(late_input(vec![key.clone(), pad.clone()], true), None); + assert_eq!( + late_input(vec![pad.clone(), removed.clone()], false), + Some(vec![InputEvent::ReleaseAll, removed.clone()]) + ); + assert_eq!( + late_input(vec![key, removed.clone(), pad], true), + Some(vec![removed]) + ); + } + #[derive(Default)] struct Log(Mutex>); diff --git a/crates/airhand-proto/src/session.rs b/crates/airhand-proto/src/session.rs index b18e99c0..1e7eb872 100644 --- a/crates/airhand-proto/src/session.rs +++ b/crates/airhand-proto/src/session.rs @@ -112,6 +112,10 @@ //! * 手柄的状态是输入([`InputEvent::Gamepad`]):和键盘鼠标一样走控制通道、成批发,过时了换成"释放所有按键" //! (被控端把每个虚拟手柄放回原位,不拔掉)。每次发的是这个手柄所有按钮、扳机、摇杆现在的样子(同 XInput 的 //! `XINPUT_GAMEPAD`),不是变化:中间的合并掉了,被控端照样知道现在怎么样; +//! * 状态只在变了的时候发,被控端放回原位之后按着不动的就没人再说了。所以控制端(`airhand_link` 的命令队列)把不在原位的 +//! 手柄每隔一会儿(500 ms)再发一次,自己丢掉了排着的输入时紧接着补上每个手柄现在的样子:网络卡过之后,按着的扳机、 +//! 按钮不会一直是松开的。过时的 [`InputEvent::GamepadRemoved`] 被控端照样执行(晚点拔掉不会做错什么,丢掉的话那个虚拟 +//! 手柄会一直插着)。界面不再把手柄交给一个会话之前,先让它把手柄放回原位; //! * 被控端第一次收到第 `pad` 个手柄时插上虚拟手柄;控制端的手柄拔掉了发 [`InputEvent::GamepadRemoved`], //! 被控端随之拔掉。会话结束时全部拔掉;会话是断掉的(不是控制端断开的)就等一会儿,同一个控制端重连上来接着用: //! 网络抖一下,游戏不会弹出"手柄已断开"; diff --git a/docs/architecture.md b/docs/architecture.md index 48313a2a..1090d7b3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -257,7 +257,7 @@ Gamepads on the controller are plugged into the host as wired Xbox 360 controlle |---|---| | State | After `Hello` a desktop host says whether it can take gamepads (`HostMsg::Gamepad`: unsupported / no driver / no permission / ready / failed, with a technical detail) and again when that changes. Hosts that don't say (phones) take no gamepad input; the controllers don't send any | | Capture | Console: the Gamepad API, polled every 4 ms by one hub for the whole page and handed to the session you're viewing (`client/src/lib/gamepad.ts`); Android: key and joystick events of gamepad input devices (`controller/Gamepads.kt`, TVs included); iOS: GameController (`Controller/Gamepads.swift`). All map to XInput's layout (buttons by position, triggers 0–255, sticks with Y up). The on-screen gamepad of game keys on phones (gamepad buttons and sticks, `GameControls.kt` / `GameLayer.swift`) is one more pad in the same `Gamepads`: its state is put together from the held gamepad buttons and pushed sticks, it takes a number when first pressed and is unplugged when the layout has none left | -| Transport | Input events on the control lane like keys and the mouse (`InputEvent::Gamepad` carries the whole state of one pad, `GamepadRemoved` unplugs it). Only changes are sent (stick noise below 1/1024 of the range isn't); consecutive states of one pad with the same buttons are coalesced at every queue, never across a button change. Stale input becomes "release all", which puts every remote pad back to rest; the controller then resends the current state | +| Transport | Input events on the control lane like keys and the mouse (`InputEvent::Gamepad` carries the whole state of one pad, `GamepadRemoved` unplugs it). Only changes are sent (stick noise below 1/1024 of the range isn't); consecutive states of one pad with the same buttons are coalesced at every queue, never across a button change. Stale input becomes "release all", which puts every remote pad back to rest. Since a pad held still sends nothing new, the controller service resends every pad that isn't at rest every 500 ms, and when it drops queued input itself the "release all" carries the current state of every pad (and the removals it dropped); a stale `GamepadRemoved` is still carried out by the host. A UI puts a session's pads back to rest before it stops handing it the gamepads | | Virtual pad | [airhand-dock](https://github.com/sqlpxc/airhand-dock) (`client/src-tauri/src/host/gamepad.rs`): one dock per process, opened on first use; plugging and unplugging on one worker thread (plugging takes tens of milliseconds). Windows: usbip-win2 attaches the device served on a loopback USB/IP server, Windows binds its own `xusb22`; the installer carries usbip-win2's own installer and offers it (`client/src-tauri/windows/usbip/`). Linux: `vhci-hcd` as root, otherwise `uinput`, where airhand-dock plays the USB host and the `xpad` driver itself. macOS can't | | Ownership | Pads belong to the controller (its identity from the end-to-end handshake), not to a session: a reconnect keeps them. When its last session ends normally they're unplugged at once; when it drops, after 30 s without a reconnect | | Rumble | airhand-dock reports the motors the game set; the host sends `HostMsg::Rumble` to the controller's latest session (latest value per pad, ahead of queued messages). The console uses `vibrationActuator` (refreshed every 4 s while on), Android the input device's vibrators, iOS CoreHaptics on the pad's handles; for the on-screen gamepad, the phone's own motor | diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index d9200b2c..3b0f175f 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -257,7 +257,7 @@ Windows 上这些都运行在系统服务里(见 [Windows 服务](#windows-服 |---|---| | 状态 | 桌面被控端在 `Hello` 之后说它能不能接手柄(`HostMsg::Gamepad`:不支持 / 缺驱动 / 没有权限 / 能接 / 出错了,带技术信息),之后有变化再说。不说的被控端(手机)不接手柄,控制端也就不发 | | 采集 | 控制台:Gamepad API,整个网页一个轮询(每 4 ms),交给正在查看的会话(`client/src/lib/gamepad.ts`);Android:手柄设备的按键和摇杆事件(`controller/Gamepads.kt`,电视也是);iOS:GameController(`Controller/Gamepads.swift`)。都换成 XInput 的格式(按钮按位置、扳机 0–255、摇杆 Y 向上为正)。手机上游戏按键里画面上的手柄(手柄的按钮、摇杆,`GameControls.kt` / `GameLayer.swift`)是同一个 `Gamepads` 里的又一个手柄:按着的手柄按钮、推着的摇杆拼成它的状态,第一次按下时分编号,方案里没有了就拔掉 | -| 传输 | 和键盘鼠标一样是控制通道上的输入(`InputEvent::Gamepad` 是一个手柄完整的状态,`GamepadRemoved` 拔掉它)。只在变了的时候发(摇杆不到量程 1/1024 的抖动不算);每个队列里同一个手柄、按钮一样的相邻状态只留最后一个,不会越过按钮的变化。过时的输入换成“释放所有按键”,对方把手柄都放回原位,控制端随后重发现在的状态 | +| 传输 | 和键盘鼠标一样是控制通道上的输入(`InputEvent::Gamepad` 是一个手柄完整的状态,`GamepadRemoved` 拔掉它)。只在变了的时候发(摇杆不到量程 1/1024 的抖动不算);每个队列里同一个手柄、按钮一样的相邻状态只留最后一个,不会越过按钮的变化。过时的输入换成“释放所有按键”,对方把手柄都放回原位。按着不动的手柄不会再发什么,所以控制端服务把不在原位的手柄每 500 ms 再发一次,自己丢掉排着的输入时补的“释放所有按键”里带着每个手柄现在的样子(以及丢掉的“拔掉了”);过时的 `GamepadRemoved` 被控端照样执行。界面不再把手柄交给一个会话之前,先让它把手柄放回原位 | | 虚拟手柄 | [airhand-dock](https://github.com/sqlpxc/airhand-dock)(`client/src-tauri/src/host/gamepad.rs`):整个进程一个,第一次用时打开;插拔都在一个线程上(插一个要几十毫秒)。Windows:usbip-win2 把本机回环 USB/IP 服务器上的设备插上,系统用自带的 `xusb22` 驱动,安装包带着 usbip-win2 自己的安装程序、安装时问要不要装(`client/src-tauri/windows/usbip/`);Linux:root 时用 `vhci-hcd`,否则用 `uinput`,airhand-dock 自己当 USB 主机、做 `xpad` 驱动做的事。macOS 不行 | | 归属 | 手柄属于控制端(端到端握手里的身份),不属于会话:断线重连接着用。它的最后一个会话正常结束时马上拔掉,断掉的等 30 秒没连回来再拔 | | 震动 | airhand-dock 报告游戏设置的马达,被控端发 `HostMsg::Rumble` 给这个控制端最新的会话(每个手柄只留最新值,排在前面)。控制台用 `vibrationActuator`(震着时每 4 秒重放),Android 用手柄设备的振动器,iOS 用手柄两侧的 CoreHaptics;画面上的手柄用手机自己的马达 | diff --git a/ios/Airhand/Controller/Gamepads.swift b/ios/Airhand/Controller/Gamepads.swift index ee283a50..6049ceb0 100644 --- a/ios/Airhand/Controller/Gamepads.swift +++ b/ios/Airhand/Controller/Gamepads.swift @@ -88,8 +88,9 @@ final class Gamepads { /// 这里接着的、用过的手柄(按编号) private(set) var pads: [LocalPad] = [] - /// 把手柄交给对方(会话 live、对方说了能不能接、开关打开、画面在屏幕上) + /// 把手柄交给对方(会话 live、对方说了能不能接、开关打开、画面在屏幕上)。不再交给对方之前先让它把按着的放回原位 @ObservationIgnored var active = false { + willSet { if active && !newValue { settle() } } didSet { guard active != oldValue else { return } if active { resync() } else { stopRumble() } @@ -146,6 +147,18 @@ final class Gamepads { stopRumble() } + /// 不再把手柄交给对方之前:让它把按着的放回原位,之后这里的变化它收不到(控制端服务还会把按着的隔一会儿再告诉它一次)。 + /// 再交给它时 [resync] 从手柄上读现在的样子 + private func settle() { + var events: [JSON] = [] + for pad in 0..