diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5d8fa689..3fa954c1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -324,9 +324,21 @@ jobs: - uses: gradle/actions/setup-gradle@v6 + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: npm + cache-dependency-path: client/package-lock.json + - name: Set version run: node .github/scripts/set-version.mjs "$VERSION" + # 远程终端的页面用 client/node_modules 里的 xterm.js(和桌面控制台同一个版本,见 app/build.gradle.kts 的 terminalAssets): + # 只要运行时的依赖 + - name: xterm.js + working-directory: client + run: npm ci --no-audit --no-fund --omit=dev --ignore-scripts + - name: Signing key env: KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} @@ -384,9 +396,20 @@ jobs: - name: Install XcodeGen run: brew install xcodegen + - uses: actions/setup-node@v6 + with: + node-version: 24 + cache: npm + cache-dependency-path: client/package-lock.json + - name: Set version run: node .github/scripts/set-version.mjs "$VERSION" + # 远程终端的页面用 client/node_modules 里的 xterm.js(见 ios/scripts/terminal-page.sh):只要运行时的依赖 + - name: xterm.js + working-directory: client + run: npm ci --no-audit --no-fund --omit=dev --ignore-scripts + # 不设 TEAM_ID:ad-hoc 签名、带 App Group 权限的 IPA,安装前要重新签名(见 docs/ios.md) - name: Build run: ios/scripts/build-ipa.sh diff --git a/README.md b/README.md index 60b89fe7..3b757c28 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ See [How it works → Video](docs/architecture.md#video) for details. - **Fixed control codes**: they survive restarts, upgrades and even server restarts until you change them yourself - **Console**: browser-style tabs to control several computers at once, plus a multi-screen overview to watch them all. Computers you've connected to are saved and reconnect with one click; if one is offline, it connects as soon as it comes back - **Web console**: the controller can also run in Docker and be used from a browser, with nothing to install on the computer you control from -- **Remote terminal**: when you only want to run command-line programs such as `claude`, `codex` or `pi` on the other computer, open just a terminal there instead of the screen (Windows / macOS / Linux hosts, running as the signed-in user): next to no bandwidth, and after a dropped connection you get the same terminal back with its programs still running. [Details](docs/usage.md#remote-terminal) +- **Remote terminal**: when you only want to run command-line programs such as `claude`, `codex` or `pi` on the other computer, open just a terminal there instead of the screen (Windows / macOS / Linux hosts, running as the signed-in user), from the desktop app or from a phone (Android / iOS): next to no bandwidth, and after a dropped connection you get the same terminal back with its programs still running. [Details](docs/usage.md#remote-terminal) - **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 diff --git a/README.zh-CN.md b/README.zh-CN.md index d951bc27..4b5eb7c5 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -40,7 +40,7 @@ Airhand 是一个**高性能、低延迟**的远程桌面:画面用 GPU 硬件 - **固定的控制码**:重启、升级,甚至服务器重启之后都不变,直到你主动更换 - **控制台**:浏览器式标签页,同时控制多台电脑,多屏总览同时看所有画面。连接过的设备自动保存,下次点一下就连;对方离线时,等它上线自动连上 - **网页控制台**:控制端也能用 Docker 部署,浏览器打开就能用,操作的电脑上什么都不用装 -- **远程终端**:只想在对方电脑上跑 `claude`、`codex`、`pi` 这类命令行程序时,不传画面、只开一个终端(Windows / macOS / Linux 被控端,以登录的用户的身份运行):几乎不占带宽,断线重连后接回原来的终端,里面的程序一直在跑。[详细说明](docs/usage.zh-CN.md#远程终端) +- **远程终端**:只想在对方电脑上跑 `claude`、`codex`、`pi` 这类命令行程序时,不传画面、只开一个终端(Windows / macOS / Linux 被控端,以登录的用户的身份运行),电脑和手机(Android / iOS)上都能开:几乎不占带宽,断线重连后接回原来的终端,里面的程序一直在跑。[详细说明](docs/usage.zh-CN.md#远程终端) - **Android**:在手机上用触控板或触屏的方式控制电脑、手机,也能共享自己的屏幕让别人协助(对方第一次连接时要输入手机上显示的配对码,有设备连上来时会提醒你);在电视上用遥控器看画面 - **iPhone / iPad**:和 Android 一样控制电脑、手机(触控板 / 触屏手势、键盘、外接鼠标,iPad 上可以锁定指针、游戏按键),也能用系统的屏幕广播共享自己的屏幕(只能被看:iOS 不允许别的应用操作本机) - **声音**:被控端的系统声音同步到控制端(Opus + 自适应抖动缓冲),看视频时可以打开音画同步。反过来,控制端的麦克风可以转发给 Windows、macOS 14.2+ 和 Linux(PipeWire)被控端,供那里的会议软件和语音输入使用。Mac 和 Linux 会在转发期间提供一个 **Airhand Microphone** 录音设备 diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 35892c1f..27a8207f 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -109,6 +109,8 @@ android { buildConfig = true } sourceSets["main"].jniLibs.srcDir(layout.buildDirectory.dir("rustJniLibs")) + // 远程终端的页面(见下面的 terminalAssets) + sourceSets["main"].assets.srcDir(layout.buildDirectory.dir("generated/terminalAssets")) packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" } @@ -166,6 +168,34 @@ val cargoBuild by tasks.registering(Exec::class) { } tasks.named("preBuild") { dependsOn(cargoBuild) } +// ───────────── 远程终端的页面:client/mobile-terminal 加上 xterm.js,拷到 build/generated/terminalAssets/terminal/ ───────────── +// xterm.js 从 client/node_modules 拷(和桌面控制台同一个版本):先在 client 里 npm ci +val terminalAssets by tasks.registering(Sync::class) { + description = "Copies the remote terminal page (client/mobile-terminal) and xterm.js into the app's assets" + group = "build" + val client = rootProject.file("../client") + val xterm = client.resolve("node_modules/@xterm") + val required = listOf( + xterm.resolve("xterm/lib/xterm.js"), + xterm.resolve("xterm/css/xterm.css"), + xterm.resolve("addon-unicode11/lib/addon-unicode11.js"), + ) + from(client.resolve("mobile-terminal")) { include("*.html", "*.js") } + from(required) + // 没有拷 .map:去掉指向它的注释 + filesMatching("*.js") { filter { line -> if (line.startsWith("//# sourceMappingURL=")) "" else line } } + into(layout.buildDirectory.dir("generated/terminalAssets/terminal")) + doFirst { + val missing = required.filter { !it.isFile } + if (missing.isNotEmpty()) { + throw GradleException( + "The remote terminal page needs xterm.js from client/node_modules: run `npm ci` in client/ first (missing ${missing.joinToString()})", + ) + } + } +} +tasks.named("preBuild") { dependsOn(terminalAssets) } + dependencies { implementation(libs.androidx.core.ktx) implementation(libs.androidx.activity.compose) diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro index 081f8ecd..a46eb3ac 100644 --- a/android/app/proguard-rules.pro +++ b/android/app/proguard-rules.pro @@ -3,3 +3,8 @@ -keepclasseswithmembernames class * { native ; } + +# 远程终端的页面按名字调用原生的方法(AirhandAndroid.post,见 ui/terminal/TerminalWebView.kt) +-keepclassmembers class * { + @android.webkit.JavascriptInterface ; +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 0a5f52f9..125a90b1 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -78,6 +78,14 @@ android:theme="@style/Theme.Airhand.Session" tools:ignore="DiscouragedApi" /> + + + = _session.asStateFlow() + private val _terminal = MutableStateFlow(null) + + /** 当前的远程终端(同一时间一个,和远程画面的会话互不影响) */ + val terminal: StateFlow = _terminal.asStateFlow() + override fun onCreate() { super.onCreate() // 最先装上:之后哪里崩了(包括加载 Rust 库)都记得下来 @@ -97,6 +103,25 @@ class AirhandApp : Application() { if (s != null && _session.value === s) _session.value = null } + /** + * 在一台电脑上开远程终端(不传画面)。之前的终端会话先关掉(界面上先问过用户)。 + * 主线程上调用(显示终端的页面要在主线程上建) + */ + fun startTerminal(code: String, pairing: String? = null): TerminalSession { + android.util.Log.i("airhand", "opening a terminal on $code") + _terminal.value?.close() + val s = TerminalSession(this, code, pairing) + _terminal.value = s + s.start() + return s + } + + /** 关掉终端会话(里面的程序随之结束) */ + fun endTerminal(s: TerminalSession? = _terminal.value) { + s?.close() + if (s != null && _terminal.value === s) _terminal.value = null + } + /** 忘掉配对过的控制端:在共享就交给 Rust(它改完发回来再保存),没在共享就直接改保存的 */ fun forgetPaired() { if (!HostService.forgetPaired()) pairing.forget() @@ -112,6 +137,7 @@ class AirhandApp : Application() { val trustReset = old.trustedFp.isNotEmpty() && now.trustedFp.isEmpty() if (old.server != now.server || old.fingerprint != now.fingerprint || old.deviceName != now.deviceName || trustReset) { endSession() + endTerminal() controller.restart() HostService.restartIfRunning(this) } diff --git a/android/app/src/main/java/app/airhand/android/controller/Protocol.kt b/android/app/src/main/java/app/airhand/android/controller/Protocol.kt index 22e55ab7..c6cd33b8 100644 --- a/android/app/src/main/java/app/airhand/android/controller/Protocol.kt +++ b/android/app/src/main/java/app/airhand/android/controller/Protocol.kt @@ -109,7 +109,7 @@ object Commands { * `resume`:之前连上时得到的重连凭证(十六进制,见 [Resume]);`hostKey`:之前记下的对方公钥(只认它); * `pairing`:配对码(对方要求配对时用户输入的);`settings` / `audio`:开始时的画质和要不要声音(在端到端握手里 * 交给对方,它一开始就按这个建编码器);`privacy`:要不要防窥模式(重连时带上现在的开关,对方一开始就保持着, - * 它的屏幕不会在重连的间隙露出来) + * 它的屏幕不会在重连的间隙露出来);`terminal`:终端会话(不要画面和声音,只开终端,见 [TerminalSession]) */ fun connect( code: String, @@ -119,7 +119,9 @@ object Commands { pairing: String? = null, audio: Boolean = false, privacy: Boolean = false, + terminal: Boolean = false, ): JSONObject = options(resume, settings, hostKey, pairing, audio, privacy).put("cmd", "connect").put("code", code) + .apply { if (terminal) put("terminal", true) } /** 连接选项(`ConnectOptions`) */ fun options(resume: String?, settings: Quality, hostKey: String?, pairing: String?, audio: Boolean, privacy: Boolean): JSONObject = @@ -141,6 +143,23 @@ object Commands { fun privacy(sid: Int, on: Boolean): JSONObject = cmd("privacy", sid).put("on", on) fun clipboard(sid: Int, text: String): JSONObject = cmd("clipboard", sid).put("text", text) fun disconnect(sid: Int): JSONObject = cmd("disconnect", sid) + + // ── 远程终端(见 [TerminalSession] 和 Rust 的 airhand_proto::terminal)── + + private fun size(cols: Int, rows: Int): JSONObject = JSONObject().put("cols", cols).put("rows", rows) + + /** 开第 `term` 个终端。`resume`:接回断线前的那个(对方给的凭证,收到了哪里) */ + fun terminalOpen(sid: Int, term: Int, cols: Int, rows: Int, resume: Pair?): JSONObject = + cmd("terminalOpen", sid).put("term", term).put("size", size(cols, rows)) + .put("resume", resume?.let { JSONObject().put("token", it.first).put("offset", it.second) } ?: JSONObject.NULL) + + fun terminalInput(sid: Int, term: Int, data: String): JSONObject = cmd("terminalInput", sid).put("term", term).put("data", data) + fun terminalResize(sid: Int, term: Int, cols: Int, rows: Int): JSONObject = + cmd("terminalResize", sid).put("term", term).put("size", size(cols, rows)) + + /** 界面显示了到 `offset` 为止的输出(累积的位置) */ + fun terminalAck(sid: Int, term: Int, offset: Long): JSONObject = cmd("terminalAck", sid).put("term", term).put("offset", offset) + fun terminalClose(sid: Int, term: Int): JSONObject = cmd("terminalClose", sid).put("term", term) } /** 重连凭证:Rust 那边是 16 个字节(JSON 数组),这里存成十六进制字符串("我的设备"里) */ diff --git a/android/app/src/main/java/app/airhand/android/controller/TerminalSession.kt b/android/app/src/main/java/app/airhand/android/controller/TerminalSession.kt new file mode 100644 index 00000000..29abfac3 --- /dev/null +++ b/android/app/src/main/java/app/airhand/android/controller/TerminalSession.kt @@ -0,0 +1,629 @@ +package app.airhand.android.controller + +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.util.Log +import app.airhand.android.AirhandApp +import app.airhand.android.R +import app.airhand.android.core.Codec +import app.airhand.android.core.Native +import app.airhand.android.core.OsKind +import app.airhand.android.core.Problem +import app.airhand.android.core.Quality +import app.airhand.android.core.ServerState +import app.airhand.android.core.optStringOrNull +import app.airhand.android.data.Settings +import app.airhand.android.ui.terminal.TerminalWebView +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import org.json.JSONObject +import kotlin.concurrent.thread + +/** + * 远程终端(终端会话,见 Rust 的 `airhand_proto::terminal`):不传画面,在对方电脑上开一个终端,用 xterm.js 显示 + * ([TerminalWebView])。和桌面控制台的 `client/src/lib/terminal.ts` 是同一套做法。 + * + * * 连接、断线重连、等对方上线和 [RemoteSession] 一样(重连凭证、配对码),只是连接选项里带着 `terminal`: + * 对方不采集画面。第一次就没连上(控制码不对、要配对码、对方没开远程终端……)是 [RemoteSession.Phase.Failed], + * 回到首页说明原因; + * * 会话断了(网络断了)对方把终端留着(最多 30 分钟)、里面的程序照常运行;重连之后带着对方给的凭证(token)和 + * 收到了哪里再开,就接回原来的终端,断开期间的输出补上; + * * 流量控制:页面里的 xterm 处理完一段输出才确认(terminalAck)。对方发出去、没确认的输出有上限, + * `cat` 大文件时输出不会在中间越积越多,Ctrl+C 也马上起作用。 + * + * 连接在自己的线程上;终端的状态(开着第几个、收到了哪里……)都在主线程上改,和页面的消息一个顺序。 + * 同一时间一个终端会话(和远程画面的会话互不影响),属于整个应用:离开终端界面再回来还是它。 + */ +class TerminalSession( + private val app: AirhandApp, + val code: String, + /** 配对码(对方要求配对、或者对方的身份变了要重新配对时用户输入的),只用于这一次连接 */ + pairing: String? = null, +) : TerminalWebView.Listener { + /** 终端现在怎么样(会话连着的时候):正在开 / 接回、开着、里面的程序退出了、开不了 */ + enum class TermState { OPENING, OPEN, EXITED, FAILED } + + /** 开不了的原因(Rust 的 `TermError`:unavailable / noUser / tooMany / expired / spawnFailed)和技术信息 */ + data class TermError(val error: String, val detail: String?) + + /** 页面上的手势,界面来处理 */ + enum class Gesture { TAP, LONG_PRESS, BELL } + + private val client = app.controller + private val main = Handler(Looper.getMainLooper()) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + + private val _phase = MutableStateFlow(RemoteSession.Phase.Connecting) + val phase: StateFlow = _phase.asStateFlow() + + private val saved = app.devices.get(code) + val hostName = MutableStateFlow(saved?.title() ?: "") + val hostOs = MutableStateFlow(saved?.hostOs ?: "") + + /** 对方报告的平台(Hello 之后才有) */ + val platform = MutableStateFlow(OsKind.UNKNOWN) + + /** 往返时延(输入、输出都走控制通道) */ + val rttMs = MutableStateFlow(null) + + /** 安全码(连上之后才有):对方屏幕上显示的是同一个 */ + val safety = MutableStateFlow(null) + val termState = MutableStateFlow(TermState.OPENING) + + /** 里面的程序的退出码([TermState.EXITED],不知道时为 null) */ + val exitCode = MutableStateFlow(null) + val termError = MutableStateFlow(null) + val fontSize = MutableStateFlow(app.settings.value.terminalFont) + + private val _gestures = MutableSharedFlow(extraBufferCapacity = 8) + val gestures: SharedFlow = _gestures.asSharedFlow() + + private val _web = MutableStateFlow(TerminalWebView(app, fontSize.value, this)) + + /** + * 显示终端的页面:会话一开始就建好(主线程),界面只是把它放进来。页面的进程没了(系统在后台收回了内存)时换一个新的 + * ([onGone]),界面跟着换 + */ + val webView: StateFlow = _web.asStateFlow() + private val web: TerminalWebView get() = _web.value + + @Volatile + private var resume: String? = saved?.resume + + @Volatile + private var hostKey: String? = saved?.hostKey + + @Volatile + private var pairing: String? = pairing + + @Volatile + private var handle = 0L + + @Volatile + private var sid = -1 + + @Volatile + private var closed = false + private var connectedOnce = false + private val wake = Object() + private var woken = false + + // ── 终端的状态(主线程)── + + /** 这个会话里的终端的编号(每开一次、接回一次加一) */ + private var termId = 0 + + /** 接回终端用的凭证(对方开好时给的) */ + private var token: String? = null + + /** 交给页面的输出到了哪里(下一个字节的位置):接回终端时从这里接着要 */ + private var received = 0L + + /** 页面量出来的终端大小(字符数),还没量时是 0 */ + private var cols = 0 + private var rows = 0 + private var openTimeout: Runnable? = null + + fun start() { + // 等的被控端上线了 / 与服务器重新连上了:叫醒等待中的连接线程 + scope.launch { client.hostOnline.collect { if (it == code) signal() } } + scope.launch { + var was: ServerState? = null + client.server.collect { + if (it is ServerState.Connected && was !is ServerState.Connected) signal() + was = it + } + } + thread(name = "airhand-terminal") { run() } + } + + // ───────────────────────────── 连接 ───────────────────────────── + + private fun signal() = synchronized(wake) { + woken = true + wake.notifyAll() + } + + private fun sleep(ms: Long) = synchronized(wake) { + if (!woken && !closed) wake.wait(ms) + woken = false + } + + private fun ui(f: () -> Unit) { + main.post { if (!closed) f() } + } + + private fun run() { + client.acquire() + try { + var attempts = 0 + while (!closed) { + val serverProblem = waitServer(if (connectedOnce) Long.MAX_VALUE else FIRST_SERVER_WAIT_MS) + if (closed) break + if (serverProblem != null) { + _phase.value = RemoteSession.Phase.Failed(serverProblem) + break + } + val h = client.handle() + // 终端会话用不上画质和声音(对方不采集画面) + val cmd = Commands.connect(code, resume, SETTINGS, hostKey, pairing, terminal = true) + val r = runCatching { JSONObject(Native.ctlCall(h, cmd.toString())) } + .getOrElse { JSONObject().put("err", JSONObject().put("kind", "failed").put("detail", it.toString())) } + if (closed) { + r.optJSONObject("ok")?.let { Native.ctlCall(h, Commands.disconnect(it.getInt("sid")).toString()) } + break + } + val ok = r.optJSONObject("ok") + if (ok != null) { + attempts = 0 + onConnected(h, ok) + val end = pump(h, ok.getInt("sid")) ?: break + sid = -1 + rttMs.value = null + if (closed) break + if (!end.second) { + // 对方断开了我们、换了控制码:终端也结束了,凭证不再有用 + if (end.first.kind == "kicked" || end.first.kind == "codeChanged") { + resume = null + ui { token = null } + } + _phase.value = RemoteSession.Phase.Ended(end.first) + break + } + _phase.value = RemoteSession.Phase.Reconnecting(end.first) + sleep(RETRY_MS) + continue + } + val p = Problem.parse(r.optJSONObject("err")) + attempts++ + when (p.kind) { + // 和远程画面一样:带着凭证而对方不在线时等它上线 + "hostOffline" -> { + _phase.value = RemoteSession.Phase.WaitingHost(p) + sleep(OFFLINE_RECHECK_MS) + } + // 重连凭证作废了:还没连上过就丢掉凭证、用控制码直接连;连上过就不再自动重连 + "kicked" -> { + val retryPlain = resume != null && !connectedOnce + resume = null + if (retryPlain) continue + _phase.value = if (connectedOnce) RemoteSession.Phase.Ended(p) else RemoteSession.Phase.Failed(p) + break + } + "notConnected", "serverTimeout", "serverLost" -> { + if (!connectedOnce && attempts >= 3) { + _phase.value = RemoteSession.Phase.Failed(p) + break + } + if (connectedOnce) _phase.value = RemoteSession.Phase.Reconnecting(p) + sleep(RETRY_MS * 2) + } + else -> { + _phase.value = if (connectedOnce) RemoteSession.Phase.Ended(p) else RemoteSession.Phase.Failed(p) + break + } + } + } + } catch (e: Exception) { + Log.e(TAG, "terminal thread failed", e) + _phase.value = RemoteSession.Phase.Failed(Problem("failed", e.toString())) + } finally { + client.release() + if (closed) _phase.value = RemoteSession.Phase.Closed + } + } + + /** 等到连上服务器。返回 null 表示连上了;第一次连接时等不到就返回原因(和 [RemoteSession] 一样) */ + private fun waitServer(limitMs: Long): Problem? { + val start = SystemClock.elapsedRealtime() + while (!closed) { + when (val s = client.server.value) { + is ServerState.Connected -> if (client.handle() != 0L) return null + is ServerState.Disconnected -> { + if (!connectedOnce && s.reason.kind in listOf("incompatible", "certMismatch", "failed")) return s.reason + if (SystemClock.elapsedRealtime() - start > limitMs) return s.reason + } + else -> if (SystemClock.elapsedRealtime() - start > limitMs) return Problem("serverTimeout") + } + Thread.sleep(100) + } + return null + } + + /** 连上了(第一次和每次重连):记进"我的设备",开终端(断线前开着的就接回来) */ + private fun onConnected(h: Long, ok: JSONObject) { + handle = h + sid = ok.getInt("sid") + resume = Resume.fromJson(ok.optJSONArray("resume")) ?: resume + ok.optString("hostKey").takeIf { it.isNotBlank() }?.let { hostKey = it } + safety.value = ok.optString("safety").takeIf { it.isNotBlank() } + pairing = null + val name = ok.optString("hostName") + val os = ok.optString("hostOs") + if (name.isNotBlank() && saved?.alias.isNullOrBlank()) hostName.value = name + if (os.isNotBlank()) hostOs.value = os + // 和桌面一样:画质这些远程画面的偏好不动,只记下这台电脑和重连凭证 + app.devices.connected(code, name, os, resume ?: "", hostKey) + connectedOnce = true + _phase.value = RemoteSession.Phase.Live + ui { openTerminal() } + Log.i(TAG, "terminal session connected to $code ($name, $os)") + } + + /** 读会话数据直到会话结束。返回 (原因, 是否重连);用户关闭时返回 null */ + private fun pump(h: Long, sid: Int): Pair? { + var quickNulls = 0 + while (!closed) { + if (client.handle() != h) return Problem("serverLost", "connection restarted") to true + val t0 = SystemClock.elapsedRealtime() + val b = Native.ctlPollSession(h, sid, 250) + if (b == null) { + if (SystemClock.elapsedRealtime() - t0 < 50 && ++quickNulls > 20) return Problem("sessionEnded") to true + continue + } + quickNulls = 0 + // 终端会话只有事件(JSON),没有画面、声音 + if (b.isEmpty() || b[0] != '{'.code.toByte()) continue + val e = runCatching { JSONObject(String(b, Charsets.UTF_8)) }.getOrNull() ?: continue + if (e.optString("type") == "closed") { + Native.ctlCall(h, Commands.disconnect(sid).toString()) + return Problem.parse(e.optJSONObject("reason")) to e.optBoolean("retry", true) + } + handleEvent(e) + } + return null + } + + private fun handleEvent(e: JSONObject) { + when (e.optString("type")) { + "hello" -> { + val p = OsKind.fromWire(e.optString("platform")) + val name = e.optString("hostname") + ui { + platform.value = p + // 对方是 Windows:输出来自 ConPTY(换行、改大小时的重排由它做) + web.call("windows", p == OsKind.WINDOWS) + if (name.isNotBlank() && saved?.alias.isNullOrBlank()) hostName.value = name + } + } + "stats" -> rttMs.value = if (e.isNull("rttMs")) null else e.optDouble("rttMs").toFloat() + "terminalOpened" -> { + val term = e.optInt("term") + val tok = e.optString("token") + val offset = e.optLong("offset") + val resumed = e.optBoolean("resumed") + ui { onOpened(term, tok, offset, resumed) } + } + "terminalOutput" -> { + val term = e.optInt("term") + val data = e.optString("data") + val bytes = e.optLong("bytes") + ui { onOutput(term, data, bytes) } + } + "terminalExited" -> { + val term = e.optInt("term") + val c = if (e.isNull("code")) null else e.optInt("code") + ui { onExited(term, c) } + } + "terminalFailed" -> { + val term = e.optInt("term") + val err = TermError(e.optString("error").ifBlank { "unavailable" }, e.optStringOrNull("detail")) + ui { onFailed(term, err) } + } + } + } + + // ───────────────────────────── 终端(主线程)───────────────────────────── + + /** 会话连上了:开终端,断线前开着的就接回来。程序退出了、开不了的不再开(用户点"重新打开"才开新的) */ + private fun openTerminal() { + if (sid < 0) return + if (termState.value == TermState.EXITED || termState.value == TermState.FAILED) return + termState.value = TermState.OPENING + termId++ + val id = termId + val (c, r) = size() + val t = token + Log.d(TAG, "terminal $id: opening ${c}x$r${if (t != null) " (resuming from $received)" else ""}") + command { Commands.terminalOpen(it, id, c, r, t?.let { tok -> tok to received }) } + openTimeout?.let(main::removeCallbacks) + val timeout = Runnable { + if (termId != id || termState.value != TermState.OPENING || sid < 0) return@Runnable + // 对方的 Airhand 多半太旧,不认识终端的消息 + termError.value = TermError("unavailable", "no answer (the remote Airhand may be too old for terminals)") + termState.value = TermState.FAILED + } + openTimeout = timeout + main.postDelayed(timeout, OPEN_TIMEOUT_MS) + } + + /** 终端的大小:页面量出来的;还没量(终端界面还没打开)时按屏幕的大小估一个,打开之后再改 */ + private fun size(): Pair { + if (cols > 0 && rows > 0) return cols to rows + val dm = app.resources.displayMetrics + val w = dm.widthPixels / dm.density + val h = dm.heightPixels / dm.density + val font = fontSize.value.toFloat() + // 等宽字大约 0.6 个字号宽,一行大约 1.3 个字号高;上下还有状态栏、标题栏、快捷键栏 + return ((w - 8) / (font * 0.6f)).toInt().coerceIn(20, 500) to ((h - 170) / (font * 1.3f)).toInt().coerceIn(5, 300) + } + + private fun onOpened(term: Int, tok: String, offset: Long, resumed: Boolean) { + if (term != termId) return + if (resumed && offset > received) { + // 断开太久,中间有一段输出对方没留住 + web.call("note", app.getString(R.string.terminal_gap)) + } else if (!resumed && token != null) { + // 原来的终端已经不在了,这是新开的 + web.call("note", app.getString(R.string.terminal_new_shell)) + } + openTimeout?.let(main::removeCallbacks) + token = tok + received = offset + web.call("begin", termId, offset) + termState.value = TermState.OPEN + // 对方开的时候按的是那时的大小:期间可能变了 + sendResize() + } + + private fun onOutput(term: Int, data: String, bytes: Long) { + if (term != termId) return + received += bytes + web.call("write", data, received, termId) + } + + private fun onExited(term: Int, c: Int?) { + if (term != termId) return + exitCode.value = c + termState.value = TermState.EXITED + token = null + } + + private fun onFailed(term: Int, err: TermError) { + if (term != termId) return + openTimeout?.let(main::removeCallbacks) + if (err.error == "expired" && token != null) { + // 要接回的终端不在了(断开太久、对方重启过):开一个新的 + token = null + web.call("note", app.getString(R.string.terminal_expired)) + openTerminal() + return + } + termError.value = err + termState.value = TermState.FAILED + } + + /** 程序退出了 / 开不了之后,开一个新的终端 */ + fun restart() { + token = null + exitCode.value = null + termError.value = null + termState.value = TermState.OPENING + web.call("reset") + openTerminal() + } + + private fun sendResize() { + if (sid < 0 || termState.value != TermState.OPEN || cols <= 0 || rows <= 0) return + val id = termId + val (c, r) = cols to rows + Log.d(TAG, "terminal $id: ${c}x$r") + command { Commands.terminalResize(it, id, c, r) } + } + + // ── 页面发来的(TerminalWebView.Listener,主线程)── + + override fun onReady(cols: Int, rows: Int, measured: Boolean) { + if (measured) onSize(cols, rows) + } + + override fun onData(data: String) { + if (sid < 0 || termState.value != TermState.OPEN) return + val id = termId + for (part in chunks(data, INPUT_CHUNK)) command { Commands.terminalInput(it, id, part) } + } + + override fun onSize(cols: Int, rows: Int) { + if (cols <= 0 || rows <= 0) return + this.cols = cols + this.rows = rows + if (redraw && rows > 1 && sid >= 0 && termState.value == TermState.OPEN) { + // 大小变一下(再变回来):程序收到 SIGWINCH 会重画整个屏幕 + redraw = false + val id = termId + command { Commands.terminalResize(it, id, cols, rows - 1) } + } + sendResize() + } + + override fun onAck(term: Int, offset: Long) { + if (term != termId || sid < 0 || termState.value != TermState.OPEN) return + command { Commands.terminalAck(it, term, offset) } + } + + override fun onTap() { + _gestures.tryEmit(Gesture.TAP) + } + + override fun onLongPress() { + _gestures.tryEmit(Gesture.LONG_PRESS) + } + + override fun onFont(size: Int) { + val s = size.coerceIn(Settings.TERMINAL_FONT_MIN, Settings.TERMINAL_FONT_MAX) + fontSize.value = s + if (app.settings.value.terminalFont != s) app.updateSettings { it.copy(terminalFont = s) } + } + + override fun onBell() { + _gestures.tryEmit(Gesture.BELL) + } + + override fun onGone() { + if (closed) return + // 页面的进程没了(系统在后台收回了内存、崩溃了):换一个新的页面,终端照常。之前显示的没了, + // 交给旧页面、还没确认的输出也没了:都确认掉(不然对方的窗口满了就不再发),再让终端里的程序重画一遍 + Log.w(TAG, "the terminal page is gone, starting a new one") + val old = web + _web.value = TerminalWebView(app, fontSize.value, this) + old.release() + web.call("windows", platform.value == OsKind.WINDOWS) + web.call("inset", inset) + web.call("note", app.getString(R.string.terminal_redrawn)) + web.call("begin", termId, received) + if (sid >= 0 && termState.value == TermState.OPEN) { + val (id, at) = termId to received + command { Commands.terminalAck(it, id, at) } + redraw = true + } + } + + /** 新的页面量出大小之后让程序重画([onGone]) */ + private var redraw = false + + // ───────────────────────────── 输入(界面调用,主线程)───────────────────────────── + + /** 快捷键栏 / 外接键盘的特殊键(W3C 的 KeyboardEvent.key,见 client/mobile-terminal/keys.js) */ + fun key(name: String, ctrl: Boolean = false, alt: Boolean = false, shift: Boolean = false) = + web.call("key", name, mods(ctrl, alt, shift)) + + /** 软键盘 / 外接键盘打的字 */ + fun text(s: String, ctrl: Boolean = false, alt: Boolean = false) { + if (s.isNotEmpty()) web.call("text", s, mods(ctrl, alt, false)) + } + + /** 粘贴(太长的截掉:本机和对方之间的队列放不下) */ + fun paste(s: String) { + if (s.isEmpty()) return + web.call("paste", if (s.length <= MAX_PASTE) s else s.substring(0, cut(s, MAX_PASTE))) + } + + fun setFont(size: Int) { + val s = size.coerceIn(Settings.TERMINAL_FONT_MIN, Settings.TERMINAL_FONT_MAX) + web.call("font", s) + onFont(s) + } + + /** 软键盘挡住的高度(dp,就是页面的 CSS 像素):终端不改大小,页面把光标所在的行挪到键盘上面 */ + fun setInset(dp: Int) { + if (dp == inset) return + inset = dp + web.call("inset", dp) + } + + private var inset = 0 + + /** 回到最新的输出 */ + fun scrollToBottom() = web.call("bottom") + + /** 最近的输出的文字("复制文字") */ + fun copyText(done: (String) -> Unit) = web.copyText(COPY_LINES, done) + + private fun mods(ctrl: Boolean, alt: Boolean, shift: Boolean): JSONObject = + JSONObject().put("ctrl", ctrl).put("alt", alt).put("shift", shift) + + // ───────────────────────────── 其他 ───────────────────────────── + + /** 给当前会话发命令(`make` 拿到会话的 sid)。没连上时丢掉 */ + private fun command(make: (sid: Int) -> JSONObject) { + val h = handle + val s = sid + if (h == 0L || s < 0 || closed) return + val cmd = make(s) + val r = Native.ctlCall(h, cmd.toString()) + if (r.contains("\"err\"")) Log.w(TAG, "${cmd.optString("cmd")} failed: $r") + } + + /** 立即重试(等对方上线时用户点了"重试") */ + fun retryNow() = signal() + + /** 结束:关掉终端(里面的程序随之结束),再断开 */ + fun close() { + if (closed) return + val (h, s, id) = Triple(handle, sid, termId) + closed = true + signal() + openTimeout?.let(main::removeCallbacks) + if (h != 0L && s >= 0) { + thread(name = "airhand-close") { + Native.ctlCall(h, Commands.terminalClose(s, id).toString()) + Native.ctlCall(h, Commands.disconnect(s).toString()) + } + } + scope.cancel() + web.release() + if (_phase.value !is RemoteSession.Phase.Failed) _phase.value = RemoteSession.Phase.Closed + } + + companion object { + private const val TAG = "airhand" + private const val FIRST_SERVER_WAIT_MS = 12_000L + private const val RETRY_MS = 800L + private const val OFFLINE_RECHECK_MS = 60_000L + + /** 开终端之后这么久没有回答:对方的 Airhand 多半太旧,不认识终端的消息 */ + private const val OPEN_TIMEOUT_MS = 15_000L + + /** 一次最多粘贴这么多(和桌面一样) */ + const val MAX_PASTE = 512 * 1024 + + /** 一条输入最多这么长(长的粘贴分几条发) */ + private const val INPUT_CHUNK = 64 * 1024 + + /** "复制文字"最多拿最近这么多行 */ + private const val COPY_LINES = 2000 + + /** 终端会话用不上画质,Rust 那边要一个:按默认的 */ + private val SETTINGS = Quality(30, 4000, 1080, true, Codec.H264) + + /** 切开的位置不在代理对中间(和桌面的 term-text.ts 一样):不超过 `max`,`max` 落在代理对中间时往前退一个 */ + fun cut(s: String, max: Int): Int { + if (max >= s.length) return s.length + if (max <= 0) return 0 + return if (Character.isHighSurrogate(s[max - 1]) && Character.isLowSurrogate(s[max])) max - 1 else max + } + + /** 长的输入切成几条,每条都是完整的字符 */ + fun chunks(s: String, max: Int): List { + val out = ArrayList() + var i = 0 + while (i < s.length) { + var n = cut(s.substring(i), max) + if (n == 0) n = minOf(2, s.length - i) + out += s.substring(i, i + n) + i += n + } + return out + } + } +} diff --git a/android/app/src/main/java/app/airhand/android/data/Stores.kt b/android/app/src/main/java/app/airhand/android/data/Stores.kt index 9568953b..9f446658 100644 --- a/android/app/src/main/java/app/airhand/android/data/Stores.kt +++ b/android/app/src/main/java/app/airhand/android/data/Stores.kt @@ -127,6 +127,13 @@ data class Settings( val updateChannel: UpdateChannel = UpdateChannel.STABLE, /** 打开 Airhand 时自动检查更新(最多 6 小时一次) */ val checkUpdates: Boolean = true, + /** 远程终端的字号(终端页面的 CSS 像素,[TERMINAL_FONT_MIN]..[TERMINAL_FONT_MAX]):双指缩放、菜单里改,所有终端共用 */ + val terminalFont: Int = TERMINAL_FONT_DEFAULT, + /** + * 首页输满控制码(、粘贴控制码)时开终端而不是远程画面:跟着最近一次点的是"终端"还是"连接" + * (和桌面控制台按回车接着最近一次的连法一样) + */ + val preferTerminal: Boolean = false, ) { /** 为现在的服务器记下的指纹(换了服务器就不算) */ val learnedFp: String? get() = trustedFp.takeIf { it.isNotBlank() && trustedServer.trim() == server.trim() } @@ -162,6 +169,8 @@ data class Settings( .put("identity", identity) .put("updateChannel", updateChannel.id) .put("checkUpdates", checkUpdates) + .put("terminalFont", terminalFont) + .put("preferTerminal", preferTerminal) companion object { const val WHEEL_SPEED_MIN = 5 @@ -173,6 +182,11 @@ data class Settings( /** 存着的双指滑动速度认到多少(屏幕密度 5 的上限);这台能设到多少见 Gestures.maxScrollPercent */ const val TOUCH_SCROLL_MAX = 1000 + /** 远程终端的字号(和终端页面 client/mobile-terminal/terminal.js 的 FONT_MIN / FONT_MAX 一样) */ + const val TERMINAL_FONT_MIN = 8 + const val TERMINAL_FONT_MAX = 28 + const val TERMINAL_FONT_DEFAULT = 13 + fun parse(o: JSONObject): Settings { val d = Settings() val tips = o.optJSONArray("tipsSeen") @@ -203,6 +217,9 @@ data class Settings( identity = o.optString("identity", ""), updateChannel = UpdateChannel.of(o.optStringOrNull("updateChannel")), checkUpdates = o.optBoolean("checkUpdates", d.checkUpdates), + terminalFont = o.optInt("terminalFont", d.terminalFont) + .takeIf { it in TERMINAL_FONT_MIN..TERMINAL_FONT_MAX } ?: d.terminalFont, + preferTerminal = o.optBoolean("preferTerminal", d.preferTerminal), ) } } diff --git a/android/app/src/main/java/app/airhand/android/ui/MainActivity.kt b/android/app/src/main/java/app/airhand/android/ui/MainActivity.kt index 3c7b6d58..c441064a 100644 --- a/android/app/src/main/java/app/airhand/android/ui/MainActivity.kt +++ b/android/app/src/main/java/app/airhand/android/ui/MainActivity.kt @@ -43,6 +43,7 @@ import app.airhand.android.ui.phone.ConnectTab import app.airhand.android.ui.phone.SettingsTab import app.airhand.android.ui.phone.ShareTab import app.airhand.android.ui.session.SessionActivity +import app.airhand.android.ui.terminal.TerminalActivity import app.airhand.android.ui.theme.AirhandTheme import app.airhand.android.ui.tv.TvActivity import kotlinx.coroutines.Dispatchers @@ -97,6 +98,7 @@ private fun PhoneHome(tab: Int, onTab: (Int) -> Unit) { val snackbar = remember { SnackbarHostState() } val host by HostState.flow.collectAsState() val session by app.session.collectAsState() + val terminal by app.terminal.collectAsState() // 连上了(或者在等对方上线时对方上线了):打开远程画面 LaunchedEffect(session) { @@ -110,6 +112,18 @@ private fun PhoneHome(tab: Int, onTab: (Int) -> Unit) { } } + // 远程终端也一样:连上了(或者等的电脑上线了)打开终端界面 + LaunchedEffect(terminal) { + val s = terminal ?: return@LaunchedEffect + var opened = false + s.phase.collect { p -> + if (p is RemoteSession.Phase.Live && !opened) { + opened = true + ctx.startActivity(Intent(ctx, TerminalActivity::class.java)) + } + } + } + // 自动检查更新(打开了的话,最多 6 小时一次)。自动检查找到了新版本:提示一次,点"更新"就下载安装 LaunchedEffect(Unit) { app.updater.autoCheck() 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 2d7d4336..3e1a81a2 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 @@ -59,7 +59,7 @@ object Messages { "pairingUnavailable" -> R.string.problem_pairing_unavailable "peerIncompatible" -> if ((p.peer ?: 0) > (p.ours ?: 0)) R.string.problem_peer_incompatible_update_app else R.string.problem_peer_incompatible_update_peer - // 手机不开远程终端,只有控制台会遇到;照样有文案 + // 开远程终端时对方不提供(没有允许,或者对方是手机) "terminalUnavailable" -> R.string.problem_terminal_unavailable "hostEnded" -> R.string.problem_host_ended "hostUnresponsive" -> R.string.problem_host_unresponsive @@ -72,6 +72,18 @@ object Messages { else -> null } + /** 远程终端开不了的原因(Rust 的 `TermError`,不认识的当作 unavailable),带 `detail` 的用 `%1$s` 显示它 */ + @StringRes + fun termErrorRes(error: String): Int = when (error) { + "noUser" -> R.string.terminal_error_no_user + "tooMany" -> R.string.terminal_error_too_many + "expired" -> R.string.terminal_error_expired + "spawnFailed" -> R.string.terminal_error_spawn_failed + else -> R.string.terminal_error_unavailable + } + + fun termError(ctx: Context, error: String, detail: String?): String = ctx.getString(termErrorRes(error), detail ?: "—") + fun problem(ctx: Context, p: Problem): String { val res = problemRes(p) ?: return ctx.getString(R.string.problem_failed, p.detail ?: p.kind) return ctx.getString(res, p.detail ?: "") diff --git a/android/app/src/main/java/app/airhand/android/ui/phone/ConnectTab.kt b/android/app/src/main/java/app/airhand/android/ui/phone/ConnectTab.kt index 0cd88e70..ec086829 100644 --- a/android/app/src/main/java/app/airhand/android/ui/phone/ConnectTab.kt +++ b/android/app/src/main/java/app/airhand/android/ui/phone/ConnectTab.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -27,6 +28,7 @@ import androidx.compose.material.icons.outlined.DeleteOutline import androidx.compose.material.icons.outlined.DevicesOther import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.MoreVert +import androidx.compose.material.icons.outlined.Terminal import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults @@ -35,7 +37,9 @@ import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Text @@ -53,6 +57,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource @@ -78,6 +83,7 @@ import app.airhand.android.ui.OsAvatar import app.airhand.android.ui.SectionTitle import app.airhand.android.ui.ServerPill import app.airhand.android.ui.session.SessionActivity +import app.airhand.android.ui.terminal.TerminalActivity import app.airhand.android.ui.theme.Brand import kotlinx.coroutines.launch @@ -86,6 +92,9 @@ import kotlinx.coroutines.launch * * 连接的过程留在这一页(按钮 / 设备上转圈),连上了才进入远程画面;连不上就在原地说明原因。 * 连接过的设备不在线时,在设备上显示"等待上线",对方一上线就自动连上。 + * + * "终端"(控制码下面的按钮、设备旁边的终端图标):不传画面,只在对方电脑上开一个终端([TerminalActivity]), + * 连接的过程和远程画面一样留在这一页。同一时间一个终端,和远程画面互不影响。 */ @Composable fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: () -> Unit) { @@ -97,15 +106,20 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: val devices by app.devices.flow.collectAsState() val session by app.session.collectAsState() val phase = session?.phase?.collectAsState()?.value + val terminal by app.terminal.collectAsState() + val termPhase = terminal?.phase?.collectAsState()?.value var code by rememberSaveable { mutableStateOf("") } var error by remember { mutableStateOf(null) } var errorCode by remember { mutableStateOf(null) } var serverDetails by remember { mutableStateOf(false) } var renaming by remember { mutableStateOf(null) } - // 端到端握手要用户决定的失败(要配对码 / 对方的身份变了):哪个控制码、什么问题 - var askUser by remember { mutableStateOf?>(null) } + // 端到端握手要用户决定的失败(要配对码 / 对方的身份变了):哪个控制码、什么问题、是不是在开终端 + var askUser by remember { mutableStateOf?>(null) } var deleting by remember { mutableStateOf(null) } + // 开着一个终端又要在别的电脑上开:先问一下(同一时间一个,原来的里面的程序会结束) + var replacing by remember { mutableStateOf(null) } + var closingTerminal by remember { mutableStateOf(false) } val clipHasText = rememberClipHasText() // 第一次连接失败:在原地显示原因,会话作废 @@ -114,12 +128,23 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: if (phase is RemoteSession.Phase.Failed) { error = Messages.problem(ctx, phase.reason) errorCode = s.code - if (phase.reason.needsPairing) askUser = s.code to phase.reason + if (phase.reason.needsPairing) askUser = Triple(s.code, phase.reason, false) app.endSession(s) } // 连上了:这台已经在“我的设备”里,输入框清空 if (phase is RemoteSession.Phase.Live && Code.parse(code) == s.code) code = "" } + // 终端也一样 + LaunchedEffect(terminal, termPhase) { + val t = terminal ?: return@LaunchedEffect + if (termPhase is RemoteSession.Phase.Failed) { + error = Messages.problem(ctx, termPhase.reason) + errorCode = t.code + if (termPhase.reason.needsPairing) askUser = Triple(t.code, termPhase.reason, true) + app.endTerminal(t) + } + if (termPhase is RemoteSession.Phase.Live && Code.parse(code) == t.code) code = "" + } fun connect(c: String) { val parsed = Code.parse(c) @@ -137,8 +162,51 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: focus.clearFocus() } + /** 在这台电脑上开远程终端。已经开着它的就回到终端;开着别的先问一下([replacing]) */ + fun openTerminal(c: String, confirmed: Boolean = false) { + val parsed = Code.parse(c) + if (parsed == null) { + error = ctx.getString(R.string.problem_invalid_code) + errorCode = c + return + } + val cur = app.terminal.value + val p = cur?.phase?.value + if (cur != null && cur.code == parsed && p != null && p !is RemoteSession.Phase.Failed && + p !is RemoteSession.Phase.Ended && p !is RemoteSession.Phase.Closed + ) { + if (p is RemoteSession.Phase.Live) ctx.startActivity(Intent(ctx, TerminalActivity::class.java)) + return + } + if (!confirmed && (p is RemoteSession.Phase.Live || p is RemoteSession.Phase.Reconnecting)) { + replacing = parsed + return + } + error = null + errorCode = null + app.startTerminal(parsed) + focus.clearFocus() + } + val busyCode = session?.code.takeIf { phase is RemoteSession.Phase.Connecting } val waitingCode = session?.code.takeIf { phase is RemoteSession.Phase.WaitingHost } + val termBusyCode = terminal?.code.takeIf { termPhase is RemoteSession.Phase.Connecting } + val termWaitingCode = terminal?.code.takeIf { termPhase is RemoteSession.Phase.WaitingHost } + + // 输满控制码、粘贴控制码时怎么连:跟着最近一次点的是"终端"还是"连接"(实心的按钮就是它) + val preferTerminal = app.settings.flow.collectAsState().value.preferTerminal + val codeFocus = remember { FocusRequester() } + fun go(c: String) = if (preferTerminal) openTerminal(c) else connect(c) + + /** 点了"终端" / "连接":记住这种连法;控制码输满了就连,没输满就回到输入框(输满时按这种连法连) */ + fun choose(terminalMode: Boolean) { + if (preferTerminal != terminalMode) app.updateSettings { it.copy(preferTerminal = terminalMode) } + if (code.length == 6) { + if (terminalMode) openTerminal(code) else connect(code) + } else { + runCatching { codeFocus.requestFocus() } + } + } LazyColumn(modifier, contentPadding = PaddingValues(bottom = 24.dp)) { item { @@ -181,10 +249,11 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: errorCode = null } }, - onComplete = { connect(it) }, - enabled = busyCode == null, + onComplete = { go(it) }, + enabled = busyCode == null && termBusyCode == null, isError = error != null && errorCode == code, modifier = Modifier.fillMaxWidth(), + focusRequester = codeFocus, ) AnimatedVisibility(error != null && (errorCode == null || errorCode == code || code.isEmpty())) { Text( @@ -195,36 +264,61 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: ) } Spacer(Modifier.height(16.dp)) - Row(verticalAlignment = Alignment.CenterVertically) { - if (clipHasText && busyCode == null) { - TextButton(onClick = { + if (clipHasText && busyCode == null && termBusyCode == null) { + TextButton( + onClick = { val found = Code.find(app.clipboard.read()) if (found != null) { code = found - connect(found) + go(found) } else { scope.launch { snackbar.showSnackbar(ctx.getString(R.string.connect_no_code_in_clipboard)) } } - }) { - Icon(Icons.Outlined.ContentPaste, null, Modifier.size(18.dp)) - Spacer(Modifier.width(8.dp)) - Text(stringResource(R.string.connect_paste)) + }, + modifier = Modifier.padding(bottom = 8.dp), + ) { + Icon(Icons.Outlined.ContentPaste, null, Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.connect_paste)) + } + } + // 终端(不传画面)和连接(远程画面),和桌面控制台一样并排 + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + ModeButton( + primary = preferTerminal, + enabled = busyCode == null && termBusyCode == null, + onClick = { choose(true) }, + modifier = Modifier.weight(1f), + ) { + if (termBusyCode != null && termBusyCode == Code.parse(code)) { + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp, color = LocalContentColor.current) + } else { + Icon(Icons.Outlined.Terminal, null, Modifier.size(18.dp)) } + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.terminal), maxLines = 1) } - Spacer(Modifier.weight(1f)) - Button( - onClick = { connect(code) }, - enabled = code.length == 6 && busyCode == null, + ModeButton( + primary = !preferTerminal, + enabled = busyCode == null && termBusyCode == null, + onClick = { choose(false) }, + modifier = Modifier.weight(1f), ) { if (busyCode != null && busyCode == Code.parse(code)) { - CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp, color = MaterialTheme.colorScheme.onPrimary) + CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp, color = LocalContentColor.current) Spacer(Modifier.width(10.dp)) - Text(stringResource(R.string.connecting)) + Text(stringResource(R.string.connecting), maxLines = 1) } else { - Text(stringResource(R.string.connect)) + Text(stringResource(R.string.connect), maxLines = 1) } } } + Text( + stringResource(R.string.terminal_connect_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 10.dp), + ) } } } @@ -241,6 +335,20 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: ) } } + // 终端也还开着(返回键离开了终端):一键回去 + val t = terminal + if (t != null && (termPhase is RemoteSession.Phase.Live || termPhase is RemoteSession.Phase.Reconnecting)) { + item { + ActiveSessionCard( + name = t.hostName.collectAsState().value.ifBlank { Code.format(t.code) }, + os = t.hostOs.collectAsState().value, + status = stringResource(R.string.terminal_active), + action = stringResource(R.string.terminal_close), + onOpen = { ctx.startActivity(Intent(ctx, TerminalActivity::class.java)) }, + onDisconnect = { closingTerminal = true }, + ) + } + } if (server is ServerState.Disconnected) { item { @@ -255,14 +363,18 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: items(devices, key = { it.code }) { d -> DeviceRow( d, - connecting = busyCode == d.code, - waiting = waitingCode == d.code, + connecting = busyCode == d.code || termBusyCode == d.code, + waiting = waitingCode == d.code || termWaitingCode == d.code, error = if (errorCode == d.code && code != d.code) error else null, onClick = { if (waitingCode == d.code || busyCode == d.code) return@DeviceRow connect(d.code) }, - onCancel = { app.endSession() }, + onTerminal = { + if (termWaitingCode == d.code || termBusyCode == d.code) return@DeviceRow + openTerminal(d.code) + }, + onCancel = { if (termWaitingCode == d.code) app.endTerminal() else app.endSession() }, onRename = { renaming = d }, onCopy = { app.clipboard.write(Code.format(d.code)) @@ -274,7 +386,7 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: } // 对方要配对码、或者对方的身份变了(用户确认是重装了之后重新配对):输入对方托盘菜单里的配对码再连 - askUser?.let { (c, p) -> + askUser?.let { (c, p, term) -> val hint = stringResource(R.string.pairing_hint) EditTextDialog( title = stringResource(R.string.pairing_title), @@ -289,7 +401,45 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: askUser = null error = null errorCode = null - app.startSession(c, viewOnly = false, pairing = it.filter(Char::isDigit)) + if (term) { + app.startTerminal(c, pairing = it.filter(Char::isDigit)) + } else { + app.startSession(c, viewOnly = false, pairing = it.filter(Char::isDigit)) + } + }, + ) + } + replacing?.let { c -> + val cur = terminal + ConfirmDialog( + title = stringResource(R.string.terminal_replace_title), + text = stringResource( + R.string.terminal_replace_text, + cur?.hostName?.collectAsState()?.value?.ifBlank { null } ?: Code.format(cur?.code ?: ""), + ), + confirm = stringResource(R.string.terminal_close), + destructive = true, + onDismiss = { replacing = null }, + onConfirm = { + replacing = null + openTerminal(c, confirmed = true) + }, + ) + } + if (closingTerminal) { + val cur = terminal + ConfirmDialog( + title = stringResource(R.string.terminal_close_title), + text = stringResource( + R.string.terminal_close_text, + cur?.hostName?.collectAsState()?.value?.ifBlank { null } ?: Code.format(cur?.code ?: ""), + ), + confirm = stringResource(R.string.terminal_close), + destructive = true, + onDismiss = { closingTerminal = false }, + onConfirm = { + closingTerminal = false + app.endTerminal(cur) }, ) } @@ -345,8 +495,31 @@ fun ConnectTab(modifier: Modifier, snackbar: SnackbarHostState, onOpenSettings: } } +/** 首页的"终端" / "连接":输满控制码时用的那种是实心的 */ +@Composable +private fun ModeButton( + primary: Boolean, + enabled: Boolean, + onClick: () -> Unit, + modifier: Modifier, + content: @Composable RowScope.() -> Unit, +) { + if (primary) { + Button(onClick = onClick, modifier = modifier, enabled = enabled, content = content) + } else { + OutlinedButton(onClick = onClick, modifier = modifier, enabled = enabled, content = content) + } +} + @Composable -private fun ActiveSessionCard(name: String, os: String, onOpen: () -> Unit, onDisconnect: () -> Unit) { +private fun ActiveSessionCard( + name: String, + os: String, + onOpen: () -> Unit, + onDisconnect: () -> Unit, + status: String = stringResource(R.string.session_active), + action: String = stringResource(R.string.disconnect), +) { Card( onClick = onOpen, modifier = Modifier @@ -360,9 +533,9 @@ private fun ActiveSessionCard(name: String, os: String, onOpen: () -> Unit, onDi Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { Text(name, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text(stringResource(R.string.session_active), style = MaterialTheme.typography.bodySmall) + Text(status, style = MaterialTheme.typography.bodySmall) } - TextButton(onClick = onDisconnect) { Text(stringResource(R.string.disconnect)) } + TextButton(onClick = onDisconnect) { Text(action) } } } } @@ -418,6 +591,7 @@ private fun DeviceRow( waiting: Boolean, error: String?, onClick: () -> Unit, + onTerminal: () -> Unit, onCancel: () -> Unit, onRename: () -> Unit, onCopy: () -> Unit, @@ -461,9 +635,17 @@ private fun DeviceRow( CircularProgressIndicator(Modifier.size(22.dp), strokeWidth = 2.dp) } waiting -> TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } - else -> Box { + else -> Row { + // 只开终端(不传画面) + IconButton(onClick = onTerminal) { Icon(Icons.Outlined.Terminal, stringResource(R.string.terminal_open)) } + Box { IconButton(onClick = { menu = true }) { Icon(Icons.Outlined.MoreVert, stringResource(R.string.more)) } DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) { + DropdownMenuItem( + text = { Text(stringResource(R.string.terminal_open)) }, + leadingIcon = { Icon(Icons.Outlined.Terminal, null) }, + onClick = { menu = false; onTerminal() }, + ) DropdownMenuItem( text = { Text(stringResource(R.string.device_rename)) }, leadingIcon = { Icon(Icons.Outlined.Edit, null) }, @@ -480,6 +662,7 @@ private fun DeviceRow( onClick = { menu = false; onDelete() }, ) } + } } } } diff --git a/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalActivity.kt b/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalActivity.kt new file mode 100644 index 00000000..e5c45d68 --- /dev/null +++ b/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalActivity.kt @@ -0,0 +1,807 @@ +package app.airhand.android.ui.terminal + +import android.annotation.SuppressLint +import android.graphics.Color as AndroidColor +import android.os.Bundle +import android.os.SystemClock +import android.view.HapticFeedbackConstants +import android.view.KeyEvent +import android.widget.Toast +import androidx.activity.ComponentActivity +import androidx.activity.SystemBarStyle +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.isImeVisible +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.outlined.ArrowBack +import androidx.compose.material.icons.automirrored.outlined.HelpOutline +import androidx.compose.material.icons.outlined.Add +import androidx.compose.material.icons.outlined.ContentCopy +import androidx.compose.material.icons.outlined.ContentPaste +import androidx.compose.material.icons.outlined.Keyboard +import androidx.compose.material.icons.outlined.KeyboardDoubleArrowDown +import androidx.compose.material.icons.outlined.KeyboardHide +import androidx.compose.material.icons.outlined.LinkOff +import androidx.compose.material.icons.outlined.CloudOff +import androidx.compose.material.icons.outlined.MoreVert +import androidx.compose.material.icons.outlined.PowerSettingsNew +import androidx.compose.material.icons.outlined.Refresh +import androidx.compose.material.icons.outlined.Remove +import androidx.compose.material.icons.outlined.Terminal +import androidx.compose.material.icons.outlined.WarningAmber +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +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.RemoteSession +import app.airhand.android.controller.TerminalSession +import app.airhand.android.core.Code +import app.airhand.android.data.Settings +import app.airhand.android.ui.ConfirmDialog +import app.airhand.android.ui.Messages +import app.airhand.android.ui.session.KeyboardController.Sticky +import app.airhand.android.ui.theme.AirhandTheme +import app.airhand.android.ui.theme.Brand +import app.airhand.android.ui.theme.Mono +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlin.math.roundToInt + +/** + * 远程终端(全屏):上面一条标题栏(连的是哪台、延迟、菜单),中间是终端([TerminalWebView]), + * 下面是快捷键栏(Esc、Tab、Ctrl、Alt、方向键……),弹出软键盘时终端缩到键盘上面(对方跟着改终端的大小)。 + * + * 会话本身在 [TerminalSession] 里(属于整个应用),这个界面只是显示它:返回键回到首页、终端保持打开 + * (首页上点一下回来),菜单里"关闭终端"才结束它(里面的程序随之结束)。 + */ +class TerminalActivity : ComponentActivity() { + private val app get() = AirhandApp.instance + private var session: TerminalSession? = null + private var keys: TerminalKeys? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val s = app.terminal.value + if (s == null) { + finish() + return + } + session = s + val k = TerminalKeys(s) + keys = k + val input = TerminalInputView(this, k) + enableEdgeToEdge( + statusBarStyle = SystemBarStyle.dark(AndroidColor.TRANSPARENT), + navigationBarStyle = SystemBarStyle.dark(AndroidColor.TRANSPARENT), + ) + setContent { + AirhandTheme(dark = true) { + TerminalScreen(s, k, input, onLeave = ::finish) + } + } + // 焦点放在接键盘的视图上(还不弹出软键盘):外接键盘按键时界面上的按钮不会出现焦点框 + input.post { input.requestFocus() } + } + + /** + * 外接键盘(和别的应用模拟的按键):连着的时候发给终端(特殊键按名字,别的按打出来的字),不管焦点在哪: + * 回车、方向键不会去按界面上的按钮。返回、音量键这些留给本机。 + * 输入法要的键(打拼音)在这之前已经给了它,软键盘发来的按键走输入连接([TerminalInputView])。 + * + * RestrictedApi:androidx 的 ComponentActivity 把它重写的这个方法标成了库内部的,其实是 Activity 的公开方法 + */ + @SuppressLint("RestrictedApi") + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + val s = session + val k = keys + val st = s?.termState?.value + if (s != null && k != null && s.phase.value == RemoteSession.Phase.Live && + st != TerminalSession.TermState.EXITED && st != TerminalSession.TermState.FAILED && + event.keyCode !in TerminalInputView.LOCAL_KEYS && k.hardKey(event) + ) { + return true + } + return super.dispatchKeyEvent(event) + } +} + +private val BG = Color(0xFF0B0D14) +private val BAR = Color(0xFF151925) +private val KEY = Color(0xFF2C3244) +private val KEY_DOWN = Color(0xFF474A53) + +@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class) +@Composable +private fun TerminalScreen(s: TerminalSession, keys: TerminalKeys, input: TerminalInputView, onLeave: () -> Unit) { + val app = AirhandApp.instance + val ctx = LocalContext.current + val view = LocalView.current + val phase by s.phase.collectAsState() + val termState by s.termState.collectAsState() + val name by s.hostName.collectAsState() + val rtt by s.rttMs.collectAsState() + val web by s.webView.collectAsState() + val who = name.ifBlank { Code.format(s.code) } + val live = phase == RemoteSession.Phase.Live + + var menu by remember { mutableStateOf(false) } + var copying by remember { mutableStateOf(null) } + var confirmClose by remember { mutableStateOf(false) } + var help by remember { mutableStateOf(false) } + var keyboard by remember { mutableStateOf(false) } + + LaunchedEffect(phase) { if (phase is RemoteSession.Phase.Closed) onLeave() } + + // 键盘:点一下终端、快捷键栏上的按钮打开;用系统的返回收起时同步状态 + val imeVisible = WindowInsets.isImeVisible + var imeWasVisible by remember { mutableStateOf(false) } + LaunchedEffect(keyboard, live) { if (keyboard && live) input.showKeyboard() else input.hideKeyboard() } + // 程序退出了、开不了:收起键盘(不然挡着卡片上的按钮) + LaunchedEffect(termState) { + if (termState == TerminalSession.TermState.EXITED || termState == TerminalSession.TermState.FAILED) keyboard = false + } + LaunchedEffect(imeVisible) { + if (imeWasVisible && !imeVisible) keyboard = false + imeWasVisible = imeVisible + } + + fun openCopy() = s.copyText { copying = it } + fun paste() { + val text = app.clipboard.read() + if (text.isNullOrEmpty()) { + Toast.makeText(ctx, R.string.problem_no_clipboard_text, Toast.LENGTH_SHORT).show() + } else { + s.paste(text) + } + } + + // 页面上的手势:点一下弹出键盘,长按复制文字,响铃时震一下(最多一秒一次) + LaunchedEffect(s) { + var lastBell = 0L + s.gestures.collect { g -> + when (g) { + TerminalSession.Gesture.TAP -> { + val st = s.termState.value + if (s.phase.value == RemoteSession.Phase.Live && (st == TerminalSession.TermState.OPEN || st == TerminalSession.TermState.OPENING)) { + keyboard = true + } + } + TerminalSession.Gesture.LONG_PRESS -> { + view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) + openCopy() + } + TerminalSession.Gesture.BELL -> { + val now = SystemClock.uptimeMillis() + if (now - lastBell > 1000) { + lastBell = now + view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK) + } + } + } + } + } + + // 返回键:回到首页,终端保持打开(软键盘开着时是系统先收起键盘) + BackHandler { onLeave() } + + // 软键盘盖在终端上、终端不改大小(不然每开关一次键盘对方就重排一次,见 terminal.js):快捷键栏挪到键盘上面, + // 盖住终端底下这么高(键盘比导航栏高出的部分),页面把光标所在的行挪到它上面 + val density = LocalDensity.current + val lift = (WindowInsets.ime.getBottom(density) - WindowInsets.navigationBars.getBottom(density)).coerceAtLeast(0) + val liftDp = with(density) { lift.toDp() } + LaunchedEffect(lift) { s.setInset(liftDp.value.roundToInt()) } + + Column( + Modifier + .fillMaxSize() + .background(BG) + .windowInsetsPadding(WindowInsets.systemBars.union(WindowInsets.displayCutout)), + ) { + TopBar( + s = s, + who = who, + live = live, + rtt = rtt, + menu = menu, + onMenu = { menu = it }, + onBack = onLeave, + onCopy = { + menu = false + openCopy() + }, + onPaste = { + menu = false + paste() + }, + onBottom = { + menu = false + s.scrollToBottom() + }, + onHelp = { + menu = false + help = true + }, + onClose = { + menu = false + confirmClose = true + }, + ) + Box( + Modifier + .weight(1f) + .fillMaxWidth(), + ) { + // 页面换了(页面的进程没了,会话换了一个新的)时换上新的 + key(web) { + AndroidView( + factory = { c -> web.also { it.attach(c) } }, + modifier = Modifier.fillMaxSize(), + onRelease = { it.detach() }, + ) + } + AndroidView(factory = { input }, modifier = Modifier.size(1.dp).align(Alignment.BottomStart)) + + if (live && termState == TerminalSession.TermState.OPENING) { + Surface( + shape = RoundedCornerShape(16.dp), + color = Color.Black.copy(alpha = 0.75f), + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = 12.dp), + ) { + Row(Modifier.padding(horizontal = 14.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp, color = Color.White) + Spacer(Modifier.width(10.dp)) + Text(stringResource(R.string.terminal_opening), color = Color.White, style = MaterialTheme.typography.bodyMedium) + } + } + } + + if (live && (termState == TerminalSession.TermState.EXITED || termState == TerminalSession.TermState.FAILED)) { + TermDone(s, termState, onClose = { app.endTerminal(s) }) + } + + ConnectionStatus(s, phase, who, onClose = { app.endTerminal(s) }) + + // 组字中的文字(拼音等),显示在快捷键栏上方 + if (keys.composing.isNotEmpty()) { + Surface( + shape = RoundedCornerShape(10.dp), + color = Color.Black.copy(alpha = 0.85f), + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(bottom = liftDp + 8.dp), + ) { + Text(keys.composing, color = Color.White, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp), fontSize = 18.sp) + } + } + } + KeyBar( + keys = keys, + keyboardOpen = keyboard, + onPaste = ::paste, + onKeyboard = { keyboard = !keyboard }, + modifier = Modifier.offset { IntOffset(0, -lift) }, + ) + } + + copying?.let { text -> + CopySheet(text, onCopy = { t -> + app.clipboard.write(t) + Toast.makeText(ctx, R.string.copied, Toast.LENGTH_SHORT).show() + copying = null + }, onDismiss = { copying = null }) + } + if (help) { + AlertDialog( + onDismissRequest = { help = false }, + title = { Text(stringResource(R.string.terminal)) }, + text = { Text(stringResource(R.string.terminal_help)) }, + confirmButton = { TextButton(onClick = { help = false }) { Text(stringResource(R.string.close)) } }, + ) + } + if (confirmClose) { + ConfirmDialog( + title = stringResource(R.string.terminal_close_title), + text = stringResource(R.string.terminal_close_text, who), + confirm = stringResource(R.string.terminal_close), + destructive = true, + onDismiss = { confirmClose = false }, + onConfirm = { + confirmClose = false + app.endTerminal(s) + }, + ) + } +} + +@Composable +private fun TopBar( + s: TerminalSession, + who: String, + live: Boolean, + rtt: Float?, + menu: Boolean, + onMenu: (Boolean) -> Unit, + onBack: () -> Unit, + onCopy: () -> Unit, + onPaste: () -> Unit, + onBottom: () -> Unit, + onHelp: () -> Unit, + onClose: () -> Unit, +) { + val font by s.fontSize.collectAsState() + val phase by s.phase.collectAsState() + val dot = when (phase) { + RemoteSession.Phase.Live -> Brand.good + is RemoteSession.Phase.Reconnecting, is RemoteSession.Phase.WaitingHost, RemoteSession.Phase.Connecting -> Brand.warn + else -> Brand.bad + } + Row( + Modifier + .fillMaxWidth() + .background(BAR) + .height(48.dp) + .padding(end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + IconButton(onClick = onBack) { + Icon(Icons.AutoMirrored.Outlined.ArrowBack, stringResource(R.string.terminal_minimize), tint = Color.White) + } + Box( + Modifier + .size(8.dp) + .clip(CircleShape) + .background(dot), + ) + Spacer(Modifier.width(8.dp)) + Icon(Icons.Outlined.Terminal, null, tint = Color.White.copy(alpha = 0.7f), modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(6.dp)) + Text( + who, + color = Color.White, + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + if (live) { + Spacer(Modifier.width(8.dp)) + val ms = rtt?.toInt() + Text( + if (ms != null) "$ms ms" else "— ms", + color = when { + ms == null -> Color.White.copy(alpha = 0.5f) + ms < 60 -> Brand.good + ms < 150 -> Brand.warn + else -> Brand.bad + }, + style = MaterialTheme.typography.bodySmall, + ) + } + Spacer(Modifier.weight(1f)) + Box { + IconButton(onClick = { onMenu(true) }) { + Icon(Icons.Outlined.MoreVert, stringResource(R.string.more), tint = Color.White) + } + DropdownMenu(expanded = menu, onDismissRequest = { onMenu(false) }) { + DropdownMenuItem( + text = { Text(stringResource(R.string.terminal_copy)) }, + leadingIcon = { Icon(Icons.Outlined.ContentCopy, null) }, + onClick = onCopy, + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.terminal_paste)) }, + leadingIcon = { Icon(Icons.Outlined.ContentPaste, null) }, + onClick = onPaste, + ) + DropdownMenuItem( + text = { Text(stringResource(R.string.terminal_bottom)) }, + leadingIcon = { Icon(Icons.Outlined.KeyboardDoubleArrowDown, null) }, + onClick = onBottom, + ) + // 字号:− 13 + + Row(Modifier.padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = { s.setFont(font - 1) }, enabled = font > Settings.TERMINAL_FONT_MIN) { + Icon(Icons.Outlined.Remove, stringResource(R.string.terminal_font_smaller)) + } + Text( + stringResource(R.string.terminal_font_size, font), + style = MaterialTheme.typography.bodyMedium, + textAlign = TextAlign.Center, + modifier = Modifier.widthIn(min = 72.dp), + ) + IconButton(onClick = { s.setFont(font + 1) }, enabled = font < Settings.TERMINAL_FONT_MAX) { + Icon(Icons.Outlined.Add, stringResource(R.string.terminal_font_larger)) + } + } + DropdownMenuItem( + text = { Text(stringResource(R.string.menu_help)) }, + leadingIcon = { Icon(Icons.AutoMirrored.Outlined.HelpOutline, null) }, + onClick = onHelp, + ) + HorizontalDivider() + DropdownMenuItem( + text = { Text(stringResource(R.string.terminal_close), color = MaterialTheme.colorScheme.error) }, + leadingIcon = { Icon(Icons.Outlined.PowerSettingsNew, null, tint = MaterialTheme.colorScheme.error) }, + onClick = onClose, + ) + } + } + } +} + +/** 终端里的程序退出了 / 开不了终端:重新打开一个,或者关掉 */ +@Composable +private fun TermDone(s: TerminalSession, state: TerminalSession.TermState, onClose: () -> Unit) { + val ctx = LocalContext.current + val code by s.exitCode.collectAsState() + val err by s.termError.collectAsState() + Box( + Modifier + .fillMaxSize() + .background(Color.Black.copy(alpha = 0.6f)) + // 盖住的时候点不到终端 + .pointerInput(Unit) { detectTapGestures { } }, + contentAlignment = Alignment.Center, + ) { + Surface(shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceContainerHigh, modifier = Modifier.padding(24.dp)) { + Column(Modifier.padding(24.dp).widthIn(max = 380.dp), horizontalAlignment = Alignment.CenterHorizontally) { + val failed = state == TerminalSession.TermState.FAILED + Icon( + if (failed) Icons.Outlined.WarningAmber else Icons.Outlined.Terminal, + null, + tint = if (failed) Brand.warn else Color.White, + modifier = Modifier.size(36.dp), + ) + Spacer(Modifier.height(12.dp)) + Text( + when { + failed -> stringResource(R.string.terminal_failed) + code != null -> stringResource(R.string.terminal_exited_code, code!!) + else -> stringResource(R.string.terminal_exited) + }, + style = MaterialTheme.typography.titleMedium, + textAlign = TextAlign.Center, + ) + val e = err + if (failed && e != null) { + Spacer(Modifier.height(6.dp)) + Text( + Messages.termError(ctx, e.error, e.detail), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + Spacer(Modifier.height(20.dp)) + Button(onClick = { s.restart() }) { + Icon(Icons.Outlined.Refresh, null, Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text(stringResource(R.string.terminal_restart)) + } + TextButton(onClick = onClose) { Text(stringResource(R.string.terminal_close)) } + } + } + } +} + +/** 会话不在正常连着时盖在终端上的说明:正在连接、断线重连、等对方上线、已结束(和远程画面的 SessionStatus 一样) */ +@Composable +private fun ConnectionStatus(s: TerminalSession, phase: RemoteSession.Phase, who: String, onClose: () -> Unit) { + val ctx = LocalContext.current + + data class St(val busy: Boolean, val title: String, val detail: String?, val ended: Boolean) + + val st: St? = when (phase) { + RemoteSession.Phase.Connecting -> St(true, ctx.getString(R.string.session_connecting, who), null, false) + RemoteSession.Phase.Live, RemoteSession.Phase.Closed -> null + is RemoteSession.Phase.Reconnecting -> St(true, ctx.getString(R.string.session_reconnecting), Messages.problem(ctx, phase.reason), false) + is RemoteSession.Phase.WaitingHost -> St(false, ctx.getString(R.string.session_waiting_host, who), ctx.getString(R.string.session_waiting_host_detail), false) + is RemoteSession.Phase.Ended -> St(false, ctx.getString(R.string.session_ended), Messages.problem(ctx, phase.reason), true) + is RemoteSession.Phase.Failed -> St(false, ctx.getString(R.string.session_ended), Messages.problem(ctx, phase.reason), true) + } + AnimatedVisibility(st != null, enter = fadeIn(), exit = fadeOut()) { + val v = st ?: return@AnimatedVisibility + Box( + Modifier + .fillMaxSize() + .background(Color.Black.copy(alpha = 0.72f)) + // 盖住的时候点不到终端 + .pointerInput(Unit) { detectTapGestures { } }, + contentAlignment = Alignment.Center, + ) { + Column( + Modifier + .widthIn(max = 420.dp) + .padding(32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + when { + v.busy -> CircularProgressIndicator(Modifier.size(40.dp), color = Color.White) + v.ended -> Icon(Icons.Outlined.LinkOff, null, tint = Color.White, modifier = Modifier.size(48.dp)) + else -> Icon(Icons.Outlined.CloudOff, null, tint = Color.White, modifier = Modifier.size(48.dp)) + } + Spacer(Modifier.height(20.dp)) + Text(v.title, color = Color.White, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center) + v.detail?.let { + Spacer(Modifier.height(8.dp)) + Text(it, color = Color.White.copy(alpha = 0.75f), style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Center) + } + Spacer(Modifier.height(24.dp)) + if (v.ended) { + Button(onClick = onClose, shape = RoundedCornerShape(24.dp)) { Text(stringResource(R.string.back)) } + } else { + if (phase is RemoteSession.Phase.WaitingHost) { + OutlinedButton(onClick = { s.retryNow() }) { Text(stringResource(R.string.retry)) } + Spacer(Modifier.height(8.dp)) + } + OutlinedButton(onClick = onClose) { Text(stringResource(R.string.terminal_close), color = Color.White) } + } + } + } + } +} + +/** 快捷键栏:终端里常用、软键盘上没有的键;最右边是粘贴和键盘的开关 */ +@Composable +private fun KeyBar(keys: TerminalKeys, keyboardOpen: Boolean, onPaste: () -> Unit, onKeyboard: () -> Unit, modifier: Modifier) { + Row( + modifier + .fillMaxWidth() + .height(44.dp) + .background(BAR), + verticalAlignment = Alignment.CenterVertically, + ) { + Row( + Modifier + .weight(1f) + .horizontalScroll(rememberScrollState()) + .padding(horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Key("Esc") { keys.key("Escape") } + Key("Tab") { keys.key("Tab") } + // Shift + Tab:反向(claude code 用它切换模式) + Key("⇧Tab") { keys.key("Tab", shift = true) } + ModKey("Ctrl", keys.ctrl) { keys.toggleCtrl() } + ModKey("Alt", keys.alt) { keys.toggleAlt() } + Key("←", repeat = true) { keys.key("ArrowLeft") } + Key("↑", repeat = true) { keys.key("ArrowUp") } + Key("↓", repeat = true) { keys.key("ArrowDown") } + Key("→", repeat = true) { keys.key("ArrowRight") } + Key("↵") { keys.key("Enter") } + Key("^C") { keys.text("c", ctrl = true) } + Key("Home") { keys.key("Home") } + Key("End") { keys.key("End") } + Key("PgUp", repeat = true) { keys.key("PageUp") } + Key("PgDn", repeat = true) { keys.key("PageDown") } + for (c in listOf("~", "|", "/", "-", "`")) Key(c) { keys.text(c) } + for (i in 1..12) Key("F$i") { keys.key("F$i") } + } + IconButton(onClick = onPaste, modifier = Modifier.size(44.dp)) { + Icon(Icons.Outlined.ContentPaste, stringResource(R.string.terminal_paste), tint = Color.White) + } + IconButton(onClick = onKeyboard, modifier = Modifier.size(44.dp)) { + Icon( + if (keyboardOpen) Icons.Outlined.KeyboardHide else Icons.Outlined.Keyboard, + stringResource(if (keyboardOpen) R.string.hide_keyboard else R.string.menu_keyboard), + tint = Color.White, + ) + } + } +} + +/** + * 快捷键栏上的一个键:松手时按一下(在键上开始横着滑是滚动快捷键栏,不算按);`repeat` 的按住不放一会儿之后连着按 + */ +@Composable +private fun Key(label: String, repeat: Boolean = false, onClick: () -> Unit) { + val click by rememberUpdatedState(onClick) + val view = LocalView.current + val scope = rememberCoroutineScope() + var pressed by remember { mutableStateOf(false) } + Box( + Modifier + .padding(horizontal = 2.dp, vertical = 4.dp) + .widthIn(min = 44.dp) + .height(36.dp) + .clip(RoundedCornerShape(8.dp)) + .background(if (pressed) KEY_DOWN else KEY) + .semantics { role = Role.Button } + .pointerInput(repeat) { + detectTapGestures(onPress = { + pressed = true + var repeated = false + val job = if (repeat) { + scope.launch { + delay(REPEAT_DELAY_MS) + repeated = true + while (true) { + click() + delay(REPEAT_EVERY_MS) + } + } + } else { + null + } + val released = tryAwaitRelease() + job?.cancel() + pressed = false + if (released && !repeated) { + click() + view.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP) + } + }) + } + .padding(horizontal = 10.dp), + contentAlignment = Alignment.Center, + ) { + Text(label, color = Color.White, fontSize = 14.sp) + } +} + +/** Ctrl / Alt:点一下对下一个键有效,再点锁定,再点取消(和远程画面的快捷键栏一样) */ +@Composable +private fun ModKey(label: String, state: Sticky, onClick: () -> Unit) { + Box( + Modifier + .padding(horizontal = 2.dp, vertical = 4.dp) + .widthIn(min = 48.dp) + .height(36.dp) + .clip(RoundedCornerShape(8.dp)) + .background( + when (state) { + Sticky.LOCK -> Brand.accent + Sticky.ONCE -> Brand.accent.copy(alpha = 0.45f) + Sticky.OFF -> KEY + }, + ) + .then(if (state == Sticky.LOCK) Modifier.border(2.dp, Color.White.copy(alpha = 0.7f), RoundedCornerShape(8.dp)) else Modifier) + .clickable(onClick = onClick) + .padding(horizontal = 10.dp), + contentAlignment = Alignment.Center, + ) { + Text(label, color = Color.White, fontSize = 14.sp, fontWeight = if (state != Sticky.OFF) FontWeight.Bold else FontWeight.Normal) + } +} + +/** 复制文字:终端里最近的输出,选中一段复制,或者全部复制 */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) +@Composable +private fun CopySheet(text: String, onCopy: (String) -> Unit, onDismiss: () -> Unit) { + val sheet = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.65f).dp + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheet, containerColor = MaterialTheme.colorScheme.surfaceContainer) { + Column( + Modifier + .fillMaxWidth() + .padding(start = 16.dp, end = 16.dp, bottom = 24.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.terminal_copy), style = MaterialTheme.typography.titleMedium) + Text( + stringResource(R.string.terminal_copy_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (text.isNotEmpty()) { + TextButton(onClick = { onCopy(text) }) { Text(stringResource(R.string.terminal_copy_all)) } + } + } + Spacer(Modifier.height(12.dp)) + if (text.isEmpty()) { + Text(stringResource(R.string.terminal_copy_empty), color = MaterialTheme.colorScheme.onSurfaceVariant) + } else { + // 一打开就在最后(最新的输出) + val scroll = rememberScrollState() + var atEnd by remember { mutableStateOf(false) } + LaunchedEffect(scroll.maxValue) { + if (!atEnd && scroll.maxValue > 0) { + scroll.scrollTo(scroll.maxValue) + atEnd = true + } + } + Box( + Modifier + .fillMaxWidth() + .heightIn(max = maxHeight) + .clip(RoundedCornerShape(12.dp)) + .background(BG) + .verticalScroll(scroll) + .padding(10.dp), + ) { + SelectionContainer { + Text(text, color = Color(0xFFE3E6EF), fontFamily = Mono, fontSize = 12.sp, lineHeight = 16.sp) + } + } + } + } + } +} + +private const val REPEAT_DELAY_MS = 400L +private const val REPEAT_EVERY_MS = 60L diff --git a/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalInput.kt b/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalInput.kt new file mode 100644 index 00000000..b760ac8d --- /dev/null +++ b/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalInput.kt @@ -0,0 +1,238 @@ +package app.airhand.android.ui.terminal + +import android.annotation.SuppressLint +import android.content.Context +import android.view.KeyCharacterMap +import android.view.KeyEvent +import android.view.View +import android.view.inputmethod.BaseInputConnection +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputMethodManager +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import app.airhand.android.controller.TerminalSession +import app.airhand.android.ui.session.KeyboardController.Sticky + +/** + * 远程终端的键盘:软键盘打的字、快捷键栏的特殊键、外接键盘,都交给 [TerminalSession](页面里换成终端的字节)。 + * + * Ctrl / Alt 在快捷键栏上是"粘滞"的(和远程画面的快捷键栏一样):点一下只对下一个键有效,再点一下锁定,再点取消。 + * 比如点 Ctrl 再在软键盘上打 c,发出去的就是 Ctrl+C(0x03)。 + */ +class TerminalKeys(private val session: TerminalSession) { + var ctrl by mutableStateOf(Sticky.OFF) + var alt by mutableStateOf(Sticky.OFF) + + /** 输入法正在组字(例如拼音)的内容,还没有发出去,界面上显示出来 */ + var composing by mutableStateOf("") + + fun toggleCtrl() { + ctrl = next(ctrl) + } + + fun toggleAlt() { + alt = next(alt) + } + + private fun next(s: Sticky) = when (s) { + Sticky.OFF -> Sticky.ONCE + Sticky.ONCE -> Sticky.LOCK + Sticky.LOCK -> Sticky.OFF + } + + private fun consumeOnce() { + if (ctrl == Sticky.ONCE) ctrl = Sticky.OFF + if (alt == Sticky.ONCE) alt = Sticky.OFF + } + + /** 按一个特殊键(W3C 的 KeyboardEvent.key:Escape、ArrowUp……),带上快捷键栏上点了的修饰键 */ + fun key(name: String, shift: Boolean = false, ctrl: Boolean = false, alt: Boolean = false) { + session.key(name, ctrl || this.ctrl != Sticky.OFF, alt || this.alt != Sticky.OFF, shift) + consumeOnce() + } + + /** 打的字 */ + fun text(s: String, ctrl: Boolean = false, alt: Boolean = false) { + if (s.isEmpty()) return + session.text(s, ctrl || this.ctrl != Sticky.OFF, alt || this.alt != Sticky.OFF) + consumeOnce() + } + + /** + * 外接键盘(和输入法发来的)按键事件:特殊键按名字发,别的按打出来的字发(按着 Ctrl / Alt 的换成控制字符 / 加 ESC)。 + * 返回是否处理了(抬起也算:按下处理了的键,抬起不要再给别人) + */ + fun hardKey(e: KeyEvent): Boolean { + // 一串字(键盘上没有的字,其他应用模拟输入时会这样发) + @Suppress("DEPRECATION") + if (e.action == KeyEvent.ACTION_MULTIPLE && e.keyCode == KeyEvent.KEYCODE_UNKNOWN) { + val s = e.characters ?: return false + text(s) + return true + } + val name = NAMES[e.keyCode] + if (e.action != KeyEvent.ACTION_DOWN) return e.action == KeyEvent.ACTION_UP && (name != null || printable(e) != 0) + if (name != null) { + key(name, shift = e.isShiftPressed, ctrl = e.isCtrlPressed, alt = e.isAltPressed) + return true + } + val ch = printable(e) + if (ch == 0) return false + text(String(Character.toChars(ch)), ctrl = e.isCtrlPressed, alt = e.isAltPressed) + return true + } + + /** 这个键打出来的字(不算 Ctrl / Alt / Meta);没有字的、死键(组合重音)是 0 */ + private fun printable(e: KeyEvent): Int { + val meta = e.metaState and (KeyEvent.META_CTRL_MASK or KeyEvent.META_ALT_MASK or KeyEvent.META_META_MASK).inv() + val c = e.getUnicodeChar(meta) + return if (c == 0 || c and KeyCharacterMap.COMBINING_ACCENT != 0) 0 else c + } + + companion object { + private val NAMES: Map = buildMap { + put(KeyEvent.KEYCODE_DPAD_UP, "ArrowUp") + put(KeyEvent.KEYCODE_DPAD_DOWN, "ArrowDown") + put(KeyEvent.KEYCODE_DPAD_LEFT, "ArrowLeft") + put(KeyEvent.KEYCODE_DPAD_RIGHT, "ArrowRight") + put(KeyEvent.KEYCODE_MOVE_HOME, "Home") + put(KeyEvent.KEYCODE_MOVE_END, "End") + put(KeyEvent.KEYCODE_PAGE_UP, "PageUp") + put(KeyEvent.KEYCODE_PAGE_DOWN, "PageDown") + put(KeyEvent.KEYCODE_INSERT, "Insert") + put(KeyEvent.KEYCODE_FORWARD_DEL, "Delete") + put(KeyEvent.KEYCODE_DEL, "Backspace") + put(KeyEvent.KEYCODE_ENTER, "Enter") + put(KeyEvent.KEYCODE_NUMPAD_ENTER, "Enter") + put(KeyEvent.KEYCODE_TAB, "Tab") + put(KeyEvent.KEYCODE_ESCAPE, "Escape") + for (i in 0 until 12) put(KeyEvent.KEYCODE_F1 + i, "F${i + 1}") + } + } +} + +/** + * 接软键盘的视图(看不见,1×1):终端的页面不拿键盘焦点,键盘输入都从这里来。 + * 输入法的连接和远程画面的一样([app.airhand.android.ui.session.RemoteInputConnection]):本地的编辑框始终是空的, + * 提交的文字马上发出去,拼音这类组字留在输入法里、提交时才发,删除键变成退格键。 + */ +@SuppressLint("ViewConstructor") +class TerminalInputView(context: Context, private val keys: TerminalKeys) : View(context) { + private var wanted = false + private var showPending = false + + init { + isFocusable = true + isFocusableInTouchMode = true + } + + override fun onCheckIsTextEditor(): Boolean = wanted + + override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? { + if (!wanted) return null + // 不要联想(不然打的字会被输入法改掉),也不要全屏的编辑框。不用"密码"类型(那样每个字马上发出去): + // 很多中文输入法在密码框里只能打英文 + outAttrs.inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS + outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_ACTION_NONE + outAttrs.initialSelStart = 0 + outAttrs.initialSelEnd = 0 + return TerminalInputConnection(this, keys) + } + + /** 弹出软键盘。菜单(另一个窗口)刚关上时窗口还没拿回焦点,等拿到焦点再弹 */ + fun showKeyboard() { + wanted = true + requestFocus() + if (hasWindowFocus()) doShow() else showPending = true + } + + private fun doShow() { + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + imm.restartInput(this) + imm.showSoftInput(this, 0) + (context as? android.app.Activity)?.window?.let { + WindowCompat.getInsetsController(it, this).show(WindowInsetsCompat.Type.ime()) + } + } + + fun hideKeyboard() { + showPending = false + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager + imm.hideSoftInputFromWindow(windowToken, 0) + wanted = false + keys.composing = "" + } + + override fun onWindowFocusChanged(hasWindowFocus: Boolean) { + super.onWindowFocusChanged(hasWindowFocus) + if (hasWindowFocus && showPending && wanted) { + showPending = false + post { doShow() } + } + } + + /** 直接送到这里的按键(输入法没有处理的、其他应用模拟的):和外接键盘一样发给终端。返回、音量键这些留给本机 */ + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean = + keyCode !in LOCAL_KEYS && keys.hardKey(event) || super.onKeyDown(keyCode, event) + + override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean = + keyCode !in LOCAL_KEYS && keys.hardKey(event) || super.onKeyUp(keyCode, event) + + companion object { + /** 留给本机的键 */ + val LOCAL_KEYS = setOf( + KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE, + KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_APP_SWITCH, + ) + } +} + +/** 软键盘的输入连接(见 [TerminalInputView]) */ +private class TerminalInputConnection(view: View, private val keys: TerminalKeys) : BaseInputConnection(view, true) { + private fun clear() { + editable?.let { + removeComposingSpans(it) + it.clear() + } + keys.composing = "" + } + + override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean { + val s = text?.toString() ?: "" + clear() + keys.text(s) + return true + } + + override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean { + super.setComposingText(text, newCursorPosition) + keys.composing = text?.toString() ?: "" + return true + } + + override fun finishComposingText(): Boolean { + val pending = editable?.toString() ?: "" + clear() + super.finishComposingText() + if (pending.isNotEmpty()) keys.text(pending) + return true + } + + override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { + if (keys.composing.isNotEmpty()) return super.deleteSurroundingText(beforeLength, afterLength) + repeat(beforeLength.coerceAtMost(64)) { keys.key("Backspace") } + repeat(afterLength.coerceAtMost(64)) { keys.key("Delete") } + return true + } + + override fun sendKeyEvent(event: KeyEvent): Boolean = keys.hardKey(event) || super.sendKeyEvent(event) + + override fun performEditorAction(actionCode: Int): Boolean { + keys.key("Enter") + return true + } +} diff --git a/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalWebView.kt b/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalWebView.kt new file mode 100644 index 00000000..f7241bb1 --- /dev/null +++ b/android/app/src/main/java/app/airhand/android/ui/terminal/TerminalWebView.kt @@ -0,0 +1,188 @@ +package app.airhand.android.ui.terminal + +import android.annotation.SuppressLint +import android.content.Context +import android.content.MutableContextWrapper +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.util.Log +import android.view.ViewGroup +import android.webkit.JavascriptInterface +import android.webkit.RenderProcessGoneDetail +import android.webkit.WebResourceRequest +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import androidx.annotation.RequiresApi +import app.airhand.android.BuildConfig +import org.json.JSONObject +import org.json.JSONTokener + +/** + * 显示远程终端的页面:xterm.js(`client/mobile-terminal/`,构建时和 xterm.js 一起拷进 assets/terminal, + * 见 app/build.gradle.kts),和桌面控制台是同一个终端。消息的格式见那里的 terminal.js。 + * + * 属于 [app.airhand.android.controller.TerminalSession](整个应用一份),界面只是把它放进来、拿走:转屏、离开终端界面再回来, + * 终端里显示的内容都还在。所以 Context 是可以换的([MutableContextWrapper]):放进界面时换成那个 Activity,拿走时换回应用。 + * + * 不拿键盘焦点([isFocusable] = false):键盘在原生那边([TerminalInputView]),页面里的 xterm 只负责显示和手势。 + * 都在主线程上用;[Listener] 也在主线程上调用。 + */ +@SuppressLint("SetJavaScriptEnabled", "ViewConstructor") +class TerminalWebView(app: Context, fontSize: Int, private val listener: Listener) : WebView(MutableContextWrapper(app)) { + interface Listener { + /** 页面好了。`measured`:已经按页面的大小算过几列几行(还没放进界面时是 false) */ + fun onReady(cols: Int, rows: Int, measured: Boolean) + + /** 要发给终端的输入 */ + fun onData(data: String) + + /** 终端的大小(字符数)变了 */ + fun onSize(cols: Int, rows: Int) + + /** 显示了第 `term` 个终端到 `offset` 为止的输出 */ + fun onAck(term: Int, offset: Long) + fun onTap() + fun onLongPress() + + /** 双指缩放换了字号 */ + fun onFont(size: Int) + fun onBell() + + /** 页面的进程没了(系统收回了内存、崩溃):这个页面不能再用了 */ + fun onGone() + } + + private val main = Handler(Looper.getMainLooper()) + private val appContext = app.applicationContext + private var ready = false + private var released = false + + /** 页面好之前要调用的(按顺序):好了一起执行 */ + private val pending = ArrayList() + + init { + // 调试版可以用电脑上的 Chrome(chrome://inspect)看页面 + if (BuildConfig.DEBUG) setWebContentsDebuggingEnabled(true) + setBackgroundColor(BACKGROUND) + isFocusable = false + isFocusableInTouchMode = false + isLongClickable = false + setOnLongClickListener { true } + overScrollMode = OVER_SCROLL_NEVER + isVerticalScrollBarEnabled = false + isHorizontalScrollBarEnabled = false + settings.apply { + javaScriptEnabled = true + // 只打开 file:///android_asset 里的页面(这个设置不管 assets) + allowFileAccess = false + allowContentAccess = false + domStorageEnabled = false + setSupportZoom(false) + builtInZoomControls = false + displayZoomControls = false + // 字号由终端自己管:系统的字体大小设置不放大网页里的字(不然算出来的几列几行不对) + textZoom = 100 + setSupportMultipleWindows(false) + javaScriptCanOpenWindowsAutomatically = false + cacheMode = WebSettings.LOAD_NO_CACHE + } + addJavascriptInterface(Bridge(), "AirhandAndroid") + webViewClient = object : WebViewClient() { + // 页面里没有链接要打开:一律不跳走 + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = true + + @RequiresApi(Build.VERSION_CODES.O) + override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { + Log.w(TAG, "the terminal page's renderer is gone (crashed: ${detail.didCrash()})") + if (!released) listener.onGone() + return true + } + } + loadUrl("file:///android_asset/terminal/index.html?font=$fontSize") + } + + private inner class Bridge { + /** 页面发来的消息(在 WebView 自己的线程上):交给主线程 */ + @JavascriptInterface + fun post(json: String) { + main.post { if (!released) handle(json) } + } + } + + private fun handle(json: String) { + val m = runCatching { JSONObject(json) }.getOrNull() ?: return + when (m.optString("t")) { + "ready" -> { + ready = true + pending.forEach { evaluateJavascript(it, null) } + pending.clear() + listener.onReady(m.optInt("cols"), m.optInt("rows"), m.optBoolean("measured")) + } + "data" -> m.optString("d").takeIf { it.isNotEmpty() }?.let(listener::onData) + "size" -> listener.onSize(m.optInt("cols"), m.optInt("rows")) + "ack" -> listener.onAck(m.optInt("term"), m.optLong("offset")) + "tap" -> listener.onTap() + "longPress" -> listener.onLongPress() + "font" -> listener.onFont(m.optInt("size")) + "bell" -> listener.onBell() + } + } + + /** 调用页面里的 `airhand.(args…)`。页面还没好时先记下来 */ + fun call(fn: String, vararg args: Any?) { + if (released) return + val script = "airhand.$fn(" + args.joinToString(",") { js(it) } + ")" + if (ready) evaluateJavascript(script, null) else pending += script + } + + /** 最近 `max` 行的文字("复制文字")。页面还没好时是空的 */ + fun copyText(max: Int, done: (String) -> Unit) { + if (!ready || released) { + done("") + return + } + evaluateJavascript("airhand.copyText($max)") { r -> + done(runCatching { JSONTokener(r).nextValue() as? String }.getOrNull() ?: "") + } + } + + /** 放进 `activity` 的界面(Compose 的 AndroidView 里)之前:之前在别的界面里的话先拿出来 */ + fun attach(activity: Context) { + (parent as? ViewGroup)?.removeView(this) + (context as MutableContextWrapper).baseContext = activity + } + + /** 从界面里拿走(Activity 没了也不会被它拖住) */ + fun detach() { + (parent as? ViewGroup)?.removeView(this) + (context as MutableContextWrapper).baseContext = appContext + } + + /** 会话结束了:页面不要了 */ + fun release() { + if (released) return + released = true + pending.clear() + detach() + removeJavascriptInterface("AirhandAndroid") + stopLoading() + destroy() + } + + companion object { + private const val TAG = "airhand" + + /** 和页面的背景一样(index.html),页面出来之前不闪白 */ + const val BACKGROUND = 0xFF0B0D14.toInt() + + /** Kotlin 的值 → JS 字面量 */ + private fun js(v: Any?): String = when (v) { + null -> "null" + is Boolean, is Int, is Long -> v.toString() + is JSONObject -> v.toString() + else -> JSONObject.quote(v.toString()) + } + } +} diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml index 55453849..b843c637 100644 --- a/android/app/src/main/res/values-zh/strings.xml +++ b/android/app/src/main/res/values-zh/strings.xml @@ -281,6 +281,42 @@ 对方重新上线后会自动连接 连接已结束 正在连接 · 点按回到远程画面 + + + 终端 + 打开终端(不传画面) + 终端:不传画面,在对方电脑上运行命令行程序(claude、codex、pi……) + 终端 · 点按回到终端 + 正在打开终端… + 终端里的程序已退出 + 终端里的程序已退出(退出码 %1$d) + 打不开终端 + 重新打开终端 + ……断开期间的输出太多,有一段没有留住…… + (原来的终端已经不在了,这是一个新的终端) + 原来的终端已经不在了(断开太久,或者对方重启过),正在打开一个新的…… + (显示重新开始了,之前的输出不再显示) + 缩小字号 + 放大字号 + 字号 %1$d + 复制文字 + 选中要复制的部分,或者全部复制 + 全部复制 + 还没有可以复制的文字 + 粘贴 + 回到最新的输出 + 返回(终端保持打开) + 关闭终端 + 关闭终端? + “%1$s”上终端里正在运行的程序会随之结束。 + 关闭现在的终端? + 同一时间只能开一个终端。“%1$s”上终端里正在运行的程序会随之结束。 + 上下滑动看前面的输出,双指捏合改字号,长按复制文字。快捷键栏上的 Ctrl、Alt 对下一个键有效(点两下锁定)。断线后自动重连,终端里的程序照常运行,重连后接着显示 + 对方开不了终端(%1$s) + 对方电脑上没有登录的用户(停在登录界面):终端要以登录的用户的身份运行 + 对方开的终端太多了,先关掉几个 + 要接回的终端已经不在了 + 启动 shell 失败:%1$s 断开连接? 断开与“%1$s”的连接。 延迟 %1$d ms @@ -563,7 +599,7 @@ 对方暂停了配对(有人多次输错配对码):请对方换一个配对码 与对方设备的版本不兼容:对方较新,请更新这台手机上的 Airhand 与对方设备的版本不兼容:对方较旧,请对方更新 Airhand - 对方没有开启远程终端(请对方在 Airhand 的托盘菜单里勾选“允许远程终端”) + 对方没有开启远程终端(请对方在 Airhand 的托盘菜单里勾选“允许远程终端”),或者那台设备(手机)不支持 对方结束了会话 对方无响应 对方断开了你的连接 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index eb921d28..31bf408c 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -288,6 +288,42 @@ It connects again automatically when the device is back online The connection ended Connected · tap to return to the remote screen + + + Terminal + Open a terminal (no screen) + Terminal: run command-line programs (claude, codex, pi…) on the computer without streaming its screen + Terminal · tap to return + Opening the terminal… + The program in the terminal exited + The program in the terminal exited (exit code %1$d) + Can\'t open the terminal + Open the terminal again + … some output while disconnected was too much to keep … + (The previous terminal is gone, this is a new one) + The previous terminal is gone (disconnected for too long, or the remote computer restarted), opening a new one… + (The display restarted, earlier output isn\'t shown) + Smaller text + Larger text + Text size %1$d + Copy text + Select the part you want, or copy it all + Copy all + Nothing to copy yet + Paste + Jump to the latest output + Back (the terminal stays open) + Close terminal + Close the terminal? + Programs running in the terminal on “%1$s” will end. + Close the open terminal? + Only one terminal can be open at a time. Programs running in the terminal on “%1$s” will end. + Swipe to scroll back, pinch to change the text size, long-press to copy text. Ctrl and Alt on the key bar apply to the next key (tap twice to lock). If the connection drops it reconnects by itself: the programs keep running and the output catches up + The remote computer can\'t open a terminal (%1$s) + Nobody is signed in on the remote computer (it\'s at the sign-in screen): the terminal runs as the signed-in user + Too many terminals are open on the remote computer, close some first + The terminal to resume is gone + Couldn\'t start the shell: %1$s Disconnect? Disconnect from “%1$s”. %1$d ms @@ -570,7 +606,7 @@ The other device paused pairing after too many wrong codes: ask its user to pick a new pairing code Incompatible with the other device: it\'s newer, please update Airhand on this phone Incompatible with the other device: it\'s older, ask its user to update Airhand - The other device doesn\'t offer a remote terminal (its user can turn on “Allow remote terminal” in the Airhand tray menu) + The other device doesn\'t offer a remote terminal (its user can turn on “Allow remote terminal” in the Airhand tray menu), or it can\'t (phones) The other side ended the session The other device stopped responding The other side disconnected you 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 67607963..28f26048 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 @@ -118,18 +118,54 @@ class ProtocolTest { assertSame(want["clipboard"], Commands.clipboard(3, "hi")) assertSame(want["privacy"], Commands.privacy(3, true)) assertSame(want["disconnect"], Commands.disconnect(3)) + // 远程终端(TerminalSession) + assertSame(want["terminalOpen"], Commands.terminalOpen(3, 1, 120, 40, "0f".repeat(16) to 4096L)) + assertSame(want["terminalInput"], Commands.terminalInput(3, 1, "ls\r")) + assertSame(want["terminalResize"], Commands.terminalResize(3, 1, 80, 24)) + assertSame(want["terminalAck"], Commands.terminalAck(3, 1, 8192)) + assertSame(want["terminalClose"], Commands.terminalClose(3, 1)) + // 新开的终端:resume 是 null(Rust 那边可以不写) + assertTrue(Commands.terminalOpen(3, 2, 80, 24, null).isNull("resume")) // Android 不用的:画面确认走 Native.ctlAck,剪贴板由自己同步,还不能把手机的麦克风交给对方, - // 只看对方的一个显示器(同时看几个是 view),手机的剪贴板换成文字时不用撤回分享的文件(分享不是复制), - // 还没有远程终端的界面(terminal*) + // 只看对方的一个显示器(同时看几个是 view),手机的剪贴板换成文字时不用撤回分享的文件(分享不是复制) assertEquals( - setOf( - "ack", "clipboardSync", "clipboardCleared", "mic", "view", + setOf("ack", "clipboardSync", "clipboardCleared", "mic", "view"), + want.keys - setOf( + "input", "settings", "keyframe", "display", "audio", "clipboard", "privacy", "disconnect", "terminalOpen", "terminalInput", "terminalResize", "terminalAck", "terminalClose", ), - want.keys - setOf("input", "settings", "keyframe", "display", "audio", "clipboard", "privacy", "disconnect"), ) } + /** 终端会话:连接选项里带着 terminal(ConnectOptions::terminal),不带时是普通的远程画面 */ + @Test + fun terminalConnectOption() { + val q = Quality(30, 4000, 1080, true, Codec.H264) + assertTrue(Commands.connect("123456", null, q, terminal = true).getBoolean("terminal")) + assertFalse(Commands.connect("123456", null, q).has("terminal")) + } + + /** 终端的输入切成几条发时不拆开代理对(和桌面的 term-text.ts 一样) */ + @Test + fun terminalInputChunks() { + val s = "ab\uD83D\uDE42cd" + assertEquals(2, TerminalSession.cut(s, 3)) + assertEquals(2, TerminalSession.cut(s, 2)) + assertEquals(4, TerminalSession.cut(s, 4)) + assertEquals(s.length, TerminalSession.cut(s, 99)) + val long = "命令\uD83D\uDE42".repeat(1000) + "\r" + for (max in listOf(1, 2, 3, 7, 64, 4096)) { + val parts = TerminalSession.chunks(long, max) + assertEquals("max $max", long, parts.joinToString("")) + for (p in parts) { + assertTrue("max $max: ${p.length}", p.length <= maxOf(max, 2)) + assertFalse(Character.isHighSurrogate(p.last())) + assertFalse(Character.isLowSurrogate(p.first())) + } + } + assertEquals(emptyList(), TerminalSession.chunks("", 10)) + } + /** 会话事件 `privacy` 的状态(Rust 的 `PrivacyState`,camelCase);不认识的当作开不了 */ @Test fun privacyStatesMatchRust() { diff --git a/client/mobile-terminal/index.html b/client/mobile-terminal/index.html new file mode 100644 index 00000000..bba8fa10 --- /dev/null +++ b/client/mobile-terminal/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + +
+ + + + + + diff --git a/client/mobile-terminal/keys.js b/client/mobile-terminal/keys.js new file mode 100644 index 00000000..3ae933c8 --- /dev/null +++ b/client/mobile-terminal/keys.js @@ -0,0 +1,111 @@ +// 手机上的远程终端(index.html):快捷键栏上的特殊键、软键盘打的字(带着快捷键栏上点了的 Ctrl / Alt) +// 换成发给终端的字节,和 xterm.js 自己处理键盘时发的一样(xterm 的 src/common/input/Keyboard.ts)。 +// +// 普通脚本(不是模块):Android 的 WebView 从 file:///android_asset 打开页面,模块脚本加载不了。 +// 测试在 client/tests/mobile-terminal.test.ts。 +(function (root) { + "use strict"; + var ESC = "\x1b"; + + /** 光标键:CSI / SS3 后面的字母(Home、End 和方向键一样跟着"应用光标键"模式) */ + var CURSOR = { ArrowUp: "A", ArrowDown: "B", ArrowRight: "C", ArrowLeft: "D", Home: "H", End: "F" }; + /** F1–F4:SS3 P–S */ + var SS3 = { F1: "P", F2: "Q", F3: "R", F4: "S" }; + /** CSI n ~ 的键 */ + var TILDE = { + Insert: 2, Delete: 3, PageUp: 5, PageDown: 6, + F5: 15, F6: 17, F7: 18, F8: 19, F9: 20, F10: 21, F11: 23, F12: 24, + }; + + /** 修饰键参数(CSI 1;m X 里的 m):1 + Shift 1 + Alt 2 + Ctrl 4 */ + function modParam(m) { + return 1 + (m.shift ? 1 : 0) + (m.alt ? 2 : 0) + (m.ctrl ? 4 : 0); + } + + /** + * 特殊键 → 字节。`name` 是 W3C 的 KeyboardEvent.key(ArrowUp、Escape、F5……),`mods` 是 {ctrl, alt, shift}, + * `appCursor`:终端在"应用光标键"模式(vim、less 这类程序打开的)。不认识的键返回 null + */ + function key(name, mods, appCursor) { + var m = mods || {}; + var p = modParam(m); + if (Object.prototype.hasOwnProperty.call(CURSOR, name)) { + if (p > 1) return ESC + "[1;" + p + CURSOR[name]; + return ESC + (appCursor ? "O" : "[") + CURSOR[name]; + } + if (Object.prototype.hasOwnProperty.call(SS3, name)) { + return p > 1 ? ESC + "[1;" + p + SS3[name] : ESC + "O" + SS3[name]; + } + if (Object.prototype.hasOwnProperty.call(TILDE, name)) { + return ESC + "[" + TILDE[name] + (p > 1 ? ";" + p : "") + "~"; + } + var alt = m.alt ? ESC : ""; + switch (name) { + case "Escape": + return alt + ESC; + case "Tab": + return m.shift ? ESC + "[Z" : alt + "\t"; + case "Enter": + return alt + "\r"; + case "Backspace": + return alt + (m.ctrl ? "\b" : "\x7f"); + case " ": + case "Space": + return alt + (m.ctrl ? "\x00" : " "); + } + return null; + } + + /** Ctrl + 一个字符:字母是 0x01–0x1a,几个符号和数字照 xterm 的规矩;别的不变(返回 null) */ + function ctrlChar(ch) { + var c = ch.charCodeAt(0); + if (ch.length !== 1) return null; + if (c >= 97 && c <= 122) return String.fromCharCode(c - 96); + if (c >= 65 && c <= 90) return String.fromCharCode(c - 64); + switch (ch) { + case "@": + case " ": + case "2": + return "\x00"; + case "[": + case "3": + return ESC; + case "\\": + case "4": + return "\x1c"; + case "]": + case "5": + return "\x1d"; + case "^": + case "6": + return "\x1e"; + case "_": + case "-": + case "/": + case "7": + return "\x1f"; + case "?": + case "8": + return "\x7f"; + } + return null; + } + + /** + * 软键盘打的字 → 字节:换行变成回车(和按回车键一样)。点了 Ctrl 的每个字符换成控制字符(Ctrl + c → 0x03), + * 点了 Alt 的每个字符前面加 ESC(和 xterm 的"Alt 当作 Meta"一样)。Shift 不管:字已经是输入法按 Shift 打出来的 + */ + function text(s, mods) { + var m = mods || {}; + s = String(s).replace(/\r?\n/g, "\r"); + if (!m.ctrl && !m.alt) return s; + var out = ""; + for (var ch of s) { + var c = m.ctrl ? ctrlChar(ch) || ch : ch; + out += (m.alt ? ESC : "") + c; + } + return out; + } + + root.AirhandKeys = { key: key, text: text }; +})(globalThis); diff --git a/client/mobile-terminal/terminal.js b/client/mobile-terminal/terminal.js new file mode 100644 index 00000000..6f0eb813 --- /dev/null +++ b/client/mobile-terminal/terminal.js @@ -0,0 +1,507 @@ +// 手机上的远程终端页面(Android 的 WebView、iOS 的 WKWebView 打开 index.html):用 xterm.js 显示对方电脑的终端, +// 和桌面控制台(client/src/lib/terminal.ts)是同一个 xterm.js、同样的配色。 +// +// 连接、断线重连、开终端都在原生那边(Android 的 TerminalSession.kt、iOS 的 TerminalSession.swift),这里只管显示、 +// 手势和把按键换成字节。和原生之间互相传消息: +// +// * 原生 → 页面:调用 window.airhand 的方法(见最后的 api); +// * 页面 → 原生:JSON 字符串,Android 是 AirhandAndroid.post(json),iOS 是 webkit.messageHandlers.airhand.postMessage(json): +// - {t:"ready", cols, rows, measured}:页面好了(在这之前原生调的方法不算数,原生要等它)。measured:已经按页面的大小 +// 算过几列几行了(页面还没显示出来时是 false,cols、rows 是默认的 80×24) +// - {t:"data", d}:要发给终端的输入(按键、粘贴、终端回答程序的查询) +// - {t:"size", cols, rows}:终端的大小(字符数)变了 +// - {t:"ack", term, offset}:显示了到 offset 为止的输出(流量控制:xterm 处理完才确认,见 airhand_proto::terminal) +// - {t:"tap"} / {t:"longPress"}:点了一下(原生弹出键盘)/ 长按(原生打开"复制文字") +// - {t:"font", size}:双指缩放换了字号(原生记下来,下次用) +// - {t:"bell"}:终端响铃 +// +// 键盘在原生那边(输入法、快捷键栏、外接键盘):打的字、按的特殊键交给 airhand.text / airhand.key,这里按终端现在的 +// 模式(应用光标键)换成字节(keys.js),和终端自己的回答一样从 onData 发出去。xterm 自己的输入框不用:手机上一碰它 +// 就会弹出网页的键盘,输入法在网页里也不好用。 +// +// 普通脚本(不是模块):Android 的 WebView 从 file:///android_asset 打开页面,模块脚本加载不了。 +(function () { + "use strict"; + + /** 终端的配色:和桌面控制台一样 */ + var THEME = { + background: "#0b0d14", + foreground: "#e3e6ef", + cursor: "#aab8ff", + cursorAccent: "#0b0d14", + selectionBackground: "rgba(124, 149, 255, 0.35)", + black: "#1b1e28", + red: "#ff5d6c", + green: "#35d49a", + yellow: "#f5b84a", + blue: "#7c95ff", + magenta: "#c792ea", + cyan: "#5ccfe6", + white: "#d5d8e2", + brightBlack: "#5c6370", + brightRed: "#ff7a86", + brightGreen: "#5ee3b0", + brightYellow: "#ffcc6b", + brightBlue: "#9aaeff", + brightMagenta: "#dcb0f5", + brightCyan: "#86e1f0", + brightWhite: "#ffffff", + }; + var FONT_MIN = 8; + var FONT_MAX = 28; + var FONT_DEFAULT = 13; + /** 显示了这么多还没确认就马上确认,不然攒一会儿(对方的窗口是 128 KiB),和桌面一样 */ + var ACK_BYTES = 32 * 1024; + var ACK_DELAY_MS = 30; + /** 大小停下来这么久才告诉原生(弹出键盘、转屏的动画里不用每一帧都让对方重排) */ + var RESIZE_DELAY_MS = 80; + /** 手指移动超过这么多(CSS 像素)才算滑动,不算点 */ + var SLOP = 10; + var LONG_PRESS_MS = 550; + /** 甩一下之后的惯性:速度(像素 / 毫秒)每这么多毫秒衰减到 1/e,低于 MIN 停下 */ + var FLING_DECAY_MS = 325; + var FLING_START = 0.25; + var FLING_MIN = 0.02; + /** #term 的边(index.html 的 padding) */ + var PAD_X = 4; + var PAD_Y = 2; + + function post(msg) { + var s = JSON.stringify(msg); + try { + if (window.AirhandAndroid) { + window.AirhandAndroid.post(s); + } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.airhand) { + window.webkit.messageHandlers.airhand.postMessage(s); + } + } catch (e) { + // 原生那边不在了(页面正在关):没关系 + } + } + + function clampFont(px) { + px = Math.round(Number(px)); + if (!isFinite(px) || px <= 0) return FONT_DEFAULT; + return Math.min(FONT_MAX, Math.max(FONT_MIN, px)); + } + + var fontSize = clampFont(new URLSearchParams(location.search).get("font") || FONT_DEFAULT); + + var term = new Terminal({ + allowProposedApi: true, + cursorBlink: false, + // 终端一直没有键盘焦点(键盘在原生那边):光标照样画成实心的方块,不画成空心的 + cursorInactiveStyle: "block", + fontFamily: + 'ui-monospace, Menlo, "SF Mono", "Roboto Mono", "Droid Sans Mono", "Noto Sans Mono", "Cascadia Mono", monospace', + fontSize: fontSize, + lineHeight: 1.1, + scrollback: 10000, + smoothScrollDuration: 0, + theme: THEME, + }); + term.loadAddon(new Unicode11Addon.Unicode11Addon()); + term.unicode.activeVersion = "11"; + var box = document.getElementById("term"); + term.open(box); + // xterm 的输入框不用(见文件开头):碰到了也不弹出网页的键盘 + if (term.textarea) { + term.textarea.setAttribute("inputmode", "none"); + term.textarea.readOnly = true; + term.textarea.tabIndex = -1; + } + var screen = term.element.querySelector(".xterm-screen") || term.element; + + term.onData(function (d) { + post({ t: "data", d: d }); + }); + term.onBell(function () { + post({ t: "bell" }); + }); + + // ───────────────────────── 大小 ───────────────────────── + + /** 一个字符格的大小(CSS 像素)。和 xterm 的 FitAddon 一样从内部的 renderService 取 */ + function cell() { + var core = term._core; + var d = core && core._renderService && core._renderService.dimensions; + return d && d.css && d.css.cell && d.css.cell.width > 0 && d.css.cell.height > 0 ? d.css.cell : null; + } + + /** 页面里放得下几列几行。不用 FitAddon:它给滚动条留了一列的位置,手机上没有滚动条 */ + function fit() { + var c = cell(); + if (!c && box.clientWidth > 0) { + // 页面刚打开时还没显示出来(大小是 0),xterm 量不出字符格:显示出来之后再量一次 + try { + term._core._charSizeService.measure(); + } catch (e) { + // 量不了:等下一次 + } + c = cell(); + } + var w = box.clientWidth - 2 * PAD_X; + var h = box.clientHeight - 2 * PAD_Y; + if (!c || w <= 0 || h <= 0) return false; + var cols = Math.max(2, Math.floor(w / c.width)); + var rows = Math.max(1, Math.floor(h / c.height)); + if (cols !== term.cols || rows !== term.rows) { + term._core._renderService.clear(); + term.resize(cols, rows); + } + return true; + } + + var reportTimer = 0; + var reported = ""; + function report() { + clearTimeout(reportTimer); + reportTimer = 0; + var s = term.cols + "x" + term.rows; + if (s === reported) return; + reported = s; + post({ t: "size", cols: term.cols, rows: term.rows }); + } + term.onResize(function () { + clearTimeout(reportTimer); + reportTimer = setTimeout(report, RESIZE_DELAY_MS); + }); + new ResizeObserver(function () { + fit(); + }).observe(box); + window.addEventListener("resize", fit); + if (document.fonts && document.fonts.ready) document.fonts.ready.then(fit); + + function setFont(px) { + px = clampFont(px); + if (px === fontSize) return; + fontSize = px; + term.options.fontSize = px; + fit(); + // 字符格的大小有时下一帧才量好 + requestAnimationFrame(fit); + } + + // ───────────────────────── 软键盘挡住的部分 ───────────────────────── + // 弹出软键盘时终端不改大小(不然每开关一次键盘对方就重排一次:claude 这类程序会整屏重画,Windows 的 ConPTY + // 改多了光标还会对不上):键盘盖在终端上,原生说挡住了底下多高(inset),这里把终端往上挪,刚好让光标所在的 + // 那一行露在键盘上面(光标在上面、本来就看得到的不挪) + + var inset = 0; + var shift = 0; + + function updateShift() { + var want = 0; + var c = cell(); + if (inset > 0 && c) { + var b = term.buffer.active; + // 往回看着的时候光标不在屏幕上:露出最底下 + var row = b.viewportY === b.baseY ? b.cursorY : term.rows - 1; + var bottom = PAD_Y + (row + 1) * c.height + 4; + want = Math.max(0, Math.min(inset, bottom - (box.clientHeight - inset))); + } + if (want === shift) return; + shift = want; + box.style.transform = want ? "translateY(" + -want + "px)" : ""; + } + term.onCursorMove(updateShift); + term.onScroll(updateShift); + term.onResize(updateShift); + + // ───────────────────────── 输出和确认 ───────────────────────── + + /** 原生那边第几个终端(开一个、接回一次加一):换了之后之前的写入完成了也不再确认 */ + var gen = 0; + var processed = 0; + var acked = 0; + var ackTimer = 0; + + function scheduleAck() { + if (processed - acked >= ACK_BYTES) sendAck(); + else if (!ackTimer) ackTimer = setTimeout(sendAck, ACK_DELAY_MS); + } + + function sendAck() { + clearTimeout(ackTimer); + ackTimer = 0; + if (processed <= acked) return; + acked = processed; + post({ t: "ack", term: gen, offset: acked }); + } + + // ───────────────────────── 手势 ───────────────────────── + // 一个手指滑:看前面的输出(全屏的程序里是上下键,程序要鼠标时是滚轮),甩一下有惯性;点一下:弹出键盘; + // 长按:复制文字;两个手指捏:改字号。网页自己的点击(xterm 拿它选字、弹键盘)都不要 + + var touch = null; + var pinch = null; + /** 捏完了还有手指在屏幕上:等都抬起来再算新的手势 */ + var waitAllUp = false; + var longTimer = 0; + var scrollRest = 0; + var flingFrame = 0; + + /** 程序要鼠标的滚轮(vim 的 set mouse=a、htop……) */ + function wheelReports() { + var m = term.modes.mouseTrackingMode; + return m === "vt200" || m === "drag" || m === "any"; + } + + /** 滚 `n` 行:n > 0 是手指往下(看前面的) */ + function scrollLines(n, x, y) { + if (!n) return; + var count = Math.abs(n); + if (wheelReports()) { + // 照样做成滚轮事件交给 xterm:它按程序要的格式、在手指的位置报告 + for (var i = 0; i < count; i++) { + screen.dispatchEvent( + new WheelEvent("wheel", { + deltaY: n > 0 ? -1 : 1, + deltaMode: 1, + clientX: x, + clientY: y, + bubbles: true, + cancelable: true, + }), + ); + } + return; + } + if (term.buffer.active.type === "alternate") { + // 全屏的程序(vim、less……)没有可以往回看的输出:和 xterm 处理滚轮一样换成上下键 + var seq = "\x1b" + (term.modes.applicationCursorKeysMode ? "O" : "[") + (n > 0 ? "A" : "B"); + var s = ""; + for (var j = 0; j < count; j++) s += seq; + term.input(s, true); + return; + } + term.scrollLines(-n); + } + + function scrollPixels(dy, x, y) { + scrollRest += dy; + var c = cell(); + var h = c ? c.height : fontSize * 1.1; + var n = scrollRest > 0 ? Math.floor(scrollRest / h) : Math.ceil(scrollRest / h); + if (n) { + scrollRest -= n * h; + scrollLines(n, x, y); + } + } + + /** 惯性只在能往回看的时候有(上下键、滚轮报告一甩就是一大串) */ + function canFling() { + return term.buffer.active.type === "normal" && !wheelReports(); + } + + function stopFling() { + if (flingFrame) cancelAnimationFrame(flingFrame); + flingFrame = 0; + } + + function startFling(v, x, y) { + stopFling(); + if (Math.abs(v) < FLING_START || !canFling()) return; + var last = performance.now(); + function step(now) { + var dt = Math.min(now - last, 50); + last = now; + scrollPixels(v * dt, x, y); + v *= Math.exp(-dt / FLING_DECAY_MS); + flingFrame = Math.abs(v) > FLING_MIN && canFling() ? requestAnimationFrame(step) : 0; + } + flingFrame = requestAnimationFrame(step); + } + + function distance(e) { + var a = e.touches[0]; + var b = e.touches[1]; + return Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY) || 1; + } + + /** 最近 100 毫秒的移动算出的速度(像素 / 毫秒,往下为正) */ + function velocity(samples) { + if (samples.length < 2) return 0; + var a = samples[0]; + var b = samples[samples.length - 1]; + var dt = b.t - a.t; + return dt > 0 ? (b.y - a.y) / dt : 0; + } + + box.addEventListener( + "touchstart", + function (e) { + e.preventDefault(); + stopFling(); + clearTimeout(longTimer); + if (e.touches.length >= 2) { + touch = null; + pinch = { d: distance(e), size: fontSize }; + return; + } + if (waitAllUp || pinch) return; + var t = e.touches[0]; + var now = performance.now(); + touch = { x: t.clientX, y: t.clientY, lastY: t.clientY, start: now, moved: false, long: false, samples: [] }; + scrollRest = 0; + longTimer = setTimeout(function () { + if (touch && !touch.moved) { + touch.long = true; + post({ t: "longPress" }); + } + }, LONG_PRESS_MS); + }, + { passive: false }, + ); + + box.addEventListener( + "touchmove", + function (e) { + e.preventDefault(); + if (pinch) { + if (e.touches.length >= 2) setFont(Math.round((pinch.size * distance(e)) / pinch.d)); + return; + } + if (!touch || touch.long) return; + var t = e.touches[0]; + if (!touch.moved) { + if (Math.hypot(t.clientX - touch.x, t.clientY - touch.y) < SLOP) return; + touch.moved = true; + clearTimeout(longTimer); + } + var now = performance.now(); + touch.samples.push({ t: now, y: t.clientY }); + while (touch.samples.length > 2 && now - touch.samples[0].t > 100) touch.samples.shift(); + var dy = t.clientY - touch.lastY; + touch.lastY = t.clientY; + scrollPixels(dy, t.clientX, t.clientY); + }, + { passive: false }, + ); + + function touchEnd(e, cancelled) { + e.preventDefault(); + clearTimeout(longTimer); + if (pinch) { + if (e.touches.length < 2) { + post({ t: "font", size: fontSize }); + pinch = null; + waitAllUp = e.touches.length > 0; + } + return; + } + if (waitAllUp) { + waitAllUp = e.touches.length > 0; + return; + } + var t = touch; + touch = null; + if (!t || cancelled) return; + if (t.moved) { + var last = e.changedTouches[0]; + startFling(velocity(t.samples), last ? last.clientX : t.x, last ? last.clientY : t.y); + } else if (!t.long) { + post({ t: "tap" }); + } + } + box.addEventListener("touchend", function (e) { + touchEnd(e, false); + }, { passive: false }); + box.addEventListener("touchcancel", function (e) { + touchEnd(e, true); + }, { passive: false }); + box.addEventListener("contextmenu", function (e) { + e.preventDefault(); + }); + + // ───────────────────────── 给原生调用的 ───────────────────────── + + window.airhand = { + /** 第 `g` 个终端开好了 / 接回来了:接下来的输出从第 `offset` 个字节开始 */ + begin: function (g, offset) { + gen = g; + processed = acked = offset; + clearTimeout(ackTimer); + ackTimer = 0; + }, + /** 第 `g` 个终端的一段输出(解好的文字),`end`:这段之后收到了哪里。xterm 处理完了才确认 */ + write: function (data, end, g) { + term.write(data, function () { + if (g !== gen) return; + if (end > processed) processed = end; + scheduleAck(); + }); + }, + /** 本机的提示(断开期间丢了一段输出、换了一个新的终端……):暗色的一行,不算终端的输出 */ + note: function (text) { + term.write("\r\n\x1b[2m" + text + "\x1b[0m\r\n"); + }, + /** 清掉一切(开一个新的终端之前) */ + reset: function () { + term.reset(); + }, + /** 快捷键栏 / 外接键盘的特殊键(见 keys.js) */ + key: function (name, mods) { + var s = AirhandKeys.key(name, mods, term.modes.applicationCursorKeysMode); + if (s) term.input(s, true); + }, + /** 软键盘 / 外接键盘打的字 */ + text: function (s, mods) { + var d = AirhandKeys.text(s, mods); + if (d) term.input(d, true); + }, + /** 粘贴(程序打开了括号粘贴模式时 xterm 会加上标记) */ + paste: function (s) { + term.paste(s); + }, + font: setFont, + /** 软键盘(和它上面的快捷键栏)挡住了页面底下多高(CSS 像素),0 是没挡住 */ + inset: function (px) { + inset = Math.max(0, Number(px) || 0); + updateShift(); + }, + /** 对方是 Windows:输出来自 ConPTY(换行、改大小时的重排由它做),和桌面一样告诉 xterm */ + windows: function (on) { + term.options.windowsPty = on ? { backend: "conpty", buildNumber: 22000 } : {}; + }, + /** 最近 `max` 行的文字("复制文字"用):折行的行接起来,末尾的空行去掉 */ + copyText: function (max) { + var b = term.buffer.active; + var n = b.length; + var lines = []; + var cur = null; + for (var i = Math.max(0, n - (max || 2000)); i < n; i++) { + var line = b.getLine(i); + if (!line) continue; + var next = b.getLine(i + 1); + var s = line.translateToString(!(next && next.isWrapped)); + if (line.isWrapped && cur !== null) { + cur += s; + } else { + if (cur !== null) lines.push(cur); + cur = s; + } + } + if (cur !== null) lines.push(cur); + while (lines.length && !lines[lines.length - 1].trim()) lines.pop(); + return lines.join("\n"); + }, + /** 回到最新的输出 */ + bottom: function () { + stopFling(); + term.scrollToBottom(); + }, + /** 排查问题用(调试版用电脑上的 Chrome 连上来看):终端现在的大小、光标、滚到了哪里 */ + state: function () { + var b = term.buffer.active; + return { cols: term.cols, rows: term.rows, cursorX: b.cursorX, cursorY: b.cursorY, baseY: b.baseY, viewportY: b.viewportY, type: b.type, gen: gen, processed: processed, acked: acked }; + }, + }; + + // 不用 requestAnimationFrame:页面还没显示出来时(Android 的 WebView 还没放进界面)它不会被调用 + setTimeout(function () { + var measured = fit(); + reported = term.cols + "x" + term.rows; + post({ t: "ready", cols: term.cols, rows: term.rows, measured: measured }); + }, 0); +})(); diff --git a/client/tests/mobile-terminal.test.ts b/client/tests/mobile-terminal.test.ts new file mode 100644 index 00000000..262139c9 --- /dev/null +++ b/client/tests/mobile-terminal.test.ts @@ -0,0 +1,67 @@ +// 手机远程终端的按键换成的字节(mobile-terminal/keys.js,Android 和 iOS 的终端页面共用):和 xterm.js 自己处理键盘时发的一样 +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import { runInNewContext } from "node:vm"; + +type Mods = { ctrl?: boolean; alt?: boolean; shift?: boolean }; +type Keys = { + key(name: string, mods?: Mods, appCursor?: boolean): string | null; + text(s: string, mods?: Mods): string; +}; + +// 页面里的普通脚本(不是模块):照页面那样运行,从全局拿 +function load(): Keys { + const ctx: { globalThis?: unknown; AirhandKeys?: Keys } = {}; + ctx.globalThis = ctx; + runInNewContext(readFileSync(new URL("../mobile-terminal/keys.js", import.meta.url), "utf8"), ctx); + return ctx.AirhandKeys!; +} + +const keys = load(); + +test("方向键跟着应用光标键模式,带修饰键时是 CSI 1;m", () => { + assert.equal(keys.key("ArrowUp"), "\x1b[A"); + assert.equal(keys.key("ArrowUp", {}, true), "\x1bOA"); + assert.equal(keys.key("ArrowLeft", { ctrl: true }), "\x1b[1;5D"); + assert.equal(keys.key("ArrowRight", { shift: true, alt: true }, true), "\x1b[1;4C"); + assert.equal(keys.key("Home"), "\x1b[H"); + assert.equal(keys.key("End", {}, true), "\x1bOF"); +}); + +test("编辑键、翻页键、功能键", () => { + assert.equal(keys.key("Delete"), "\x1b[3~"); + assert.equal(keys.key("PageUp", { ctrl: true }), "\x1b[5;5~"); + assert.equal(keys.key("F1"), "\x1bOP"); + assert.equal(keys.key("F4", { shift: true }), "\x1b[1;2S"); + assert.equal(keys.key("F5"), "\x1b[15~"); + assert.equal(keys.key("F12"), "\x1b[24~"); + assert.equal(keys.key("Nope"), null); +}); + +test("Esc、Tab、回车、退格", () => { + assert.equal(keys.key("Escape"), "\x1b"); + assert.equal(keys.key("Tab"), "\t"); + // Shift + Tab:反向(claude code 用它切换模式) + assert.equal(keys.key("Tab", { shift: true }), "\x1b[Z"); + assert.equal(keys.key("Enter"), "\r"); + assert.equal(keys.key("Enter", { alt: true }), "\x1b\r"); + assert.equal(keys.key("Backspace"), "\x7f"); + assert.equal(keys.key("Backspace", { ctrl: true }), "\b"); + assert.equal(keys.key("Backspace", { alt: true }), "\x1b\x7f"); +}); + +test("打的字:换行变成回车,Ctrl 换成控制字符,Alt 前面加 ESC", () => { + assert.equal(keys.text("ls -la\n"), "ls -la\r"); + assert.equal(keys.text("你好🙂"), "你好🙂"); + assert.equal(keys.text("c", { ctrl: true }), "\x03"); + assert.equal(keys.text("C", { ctrl: true }), "\x03"); + assert.equal(keys.text("[", { ctrl: true }), "\x1b"); + assert.equal(keys.text(" ", { ctrl: true }), "\x00"); + assert.equal(keys.text("?", { ctrl: true }), "\x7f"); + assert.equal(keys.text("b", { alt: true }), "\x1bb"); + assert.equal(keys.text("x", { ctrl: true, alt: true }), "\x1b\x18"); + // 没有控制字符的照原样 + assert.equal(keys.text("好", { ctrl: true }), "好"); + assert.equal(keys.text("A", { shift: true }), "A"); +}); diff --git a/docs/android.md b/docs/android.md index 04cfc5e2..f17fbb9b 100644 --- a/docs/android.md +++ b/docs/android.md @@ -17,6 +17,7 @@ On a TV, the phone entry point also switches to the TV interface. - **Pairing code**: the first time you connect to a computer or a phone it asks for the 6-digit pairing code shown there (a computer's tray menu, a phone's Share screen tab; a dialog pops up, on TVs the keypad switches to the pairing code). Once paired, it remembers this phone. If a device's identity changed since the last connection (reinstalled, or someone impersonating it), you need to enter its current pairing code to pair again. Sessions are end-to-end encrypted: the relay server can't see the screen or what you type - **My devices**: every device you connect to is saved (name, OS, control code, last connection, resume token, its end-to-end public key), so next time it's **one tap**. If it's offline the row says "Offline · connects automatically when it's back" and the remote screen opens by itself when it comes online; you can cancel any time. Devices can be renamed, their code copied, or removed (with undo) - A card at the top leads back to a session that's still running +- **Terminal**: next to **Connect** there's **Terminal**, and a terminal icon next to each device in My devices: it opens just a command-line terminal on the computer, without its screen (for `claude`, `codex`, `pi`, builds…). The filled one of the two buttons is the one you tapped last, and it's what a completed code opens. See [Remote terminal](usage.md#remote-terminal) for the key bar, gestures and copying The remote screen is full screen with just one **draggable round button** (it snaps to the left / right edge) that opens the menu (with "Double-tap menu button for keyboard" on in Settings, double-tapping it shows / hides the keyboard). The top of the menu shows the device's name, video format, resolution, frame rate, latency, bitrate and path; below are the four most used actions: keyboard, sound, to portrait / landscape, disconnect; then six categories, the same as in Settings on the home screen: diff --git a/docs/android.zh-CN.md b/docs/android.zh-CN.md index b11cce16..02bc9f15 100644 --- a/docs/android.zh-CN.md +++ b/docs/android.zh-CN.md @@ -17,6 +17,7 @@ - **配对码**:第一次连接一台电脑或手机时,它会要求输入对方显示的 6 位配对码(电脑在托盘菜单里,手机在“共享本机”页;弹出对话框,电视上数字键盘改成输入配对码),配对之后对方记住这台手机。一台设备的身份和上次连接时不一样(重装过,或者有人冒充它)时,要输入它现在的配对码重新配对。会话是端到端加密的:中转服务器看不到画面,也看不到你打的字 - **我的设备**:连接成功的设备自动保存(名称、系统、控制码、上次连接时间、重连凭证、对方的端到端加密公钥),下次**点一下就连**。对方不在线时设备上显示“对方不在线 · 上线后自动连接”,对方一上线就自动进入远程画面,可以随时取消。每台设备可以重命名、复制控制码、删除(删除后可以撤销) - 正在连接的会话在首页顶部有一张卡片,点一下回到远程画面 +- **终端**:**连接**旁边有**终端**,我的设备里每台设备右边也有终端图标:不传画面,只在对方电脑上开一个命令行终端(跑 `claude`、`codex`、`pi`、编译……)。两个按钮里实心的那个是最近一次点的,输满控制码时就按它来连。快捷键栏、手势、复制见[远程终端](usage.zh-CN.md#远程终端) 远程画面全屏显示,只有一个**可以拖动的小圆钮**(松手后贴到左 / 右边),点开是菜单(设置里打开“双击浮标开关键盘”后,双击它直接打开 / 收起键盘)。菜单顶部显示对方名称和编码格式、分辨率、帧率、延迟、码率、走的路;下面是最常用的四个:键盘、声音、切到竖屏 / 横屏、断开;再下面是六个分类,和首页“设置”里的分类一样: diff --git a/docs/architecture.md b/docs/architecture.md index 2f34a729..262a56bd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -106,6 +106,7 @@ For running command-line programs without the screen (protocol in `crates/airhan - **Reconnecting**: when a session drops (rather than ending normally) the host keeps the terminal for 30 minutes (`airhand_link::host::terminal::GRACE`), reading on and keeping the latest 1 MiB. After reconnecting the controller opens it again with the token it got and how far it received, and the host carries on from there; the token is bound to the controller's public key. A normal disconnect, the local user disconnecting all controllers, or turning off "Allow remote terminal" ends it right away - **Pseudo terminals**: `openpty` plus a login shell (`setsid`, `TIOCSCTTY`) on macOS / Linux, ConPTY on Windows. The host in the Windows service is SYSTEM, but ConPTY has to run as the same user as the programs in it: it starts the helper `airhand.exe --terminal` as the user signed in on the console session (`WTSQueryUserToken`, `CreateEnvironmentBlock`), lets it inherit only two pipes (`PROC_THREAD_ATTRIBUTE_HANDLE_LIST`), and the terminal lives in the helper, talking over its standard input and output (`client/src-tauri/src/host/terminal/helper.rs`) - The controller service decodes the output into text for the UI (a UTF-8 character split across two messages waits for the rest) along with how many bytes it was, which the UI acknowledges. The console's terminal (`client/src/lib/terminal.ts`) is loaded on demand along with xterm.js +- **On phones** (Android `controller/TerminalSession.kt`, iOS `Terminal/TerminalSession.swift`): connecting, reconnecting, opening, resuming and acknowledging work like the console, with the same commands (`terminalOpen` and so on, through `airhand-mobile`'s `Ctl::call`). The display is the same xterm.js: `client/mobile-terminal/` is a plain page (classic scripts, since Android's WebView can't load module scripts from `file:///android_asset`), copied into the app at build time together with xterm.js from `client/node_modules` (Android's `terminalAssets` task, iOS `scripts/terminal-page.sh`) and opened in a WebView / WKWebView; page and native code call each other with JSON messages (see the top of `terminal.js`). The page belongs to the session, not the screen: leave the terminal and come back and the content is still there; if the system kills the page's process, a new page takes over, everything unacknowledged is acknowledged and the program is made to redraw. The keyboard is native (a hidden input field that handles input-method composition like remote control does); typed text and key-bar keys go to the page, which turns them into bytes for the terminal's current mode (application cursor keys) in `keys.js`. The soft keyboard **doesn't resize** the terminal: it covers the bottom and the page shifts the cursor's line above it. Resizing on every keyboard toggle would make programs like claude redraw the whole screen each time, and Windows' ConPTY could lose track of the cursor relative to xterm after a resumed terminal is resized. Gestures are handled in the page: one finger scrolls back (arrow keys in full-screen programs, wheel events when the program asked for the mouse), a tap brings up the keyboard, a long press copies text, a pinch changes the text size ### Protocol evolution diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index daf2de2c..160dbd3c 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -106,6 +106,7 @@ flowchart LR - **断线重连**:会话断了(不是正常断开)被控端把终端留 30 分钟(`airhand_link::host::terminal::GRACE`),这期间一直读,只留最近的 1 MiB。控制端重连之后带着开好时给的凭证和收到了哪里再开,从那里接着发;凭证绑着控制端的公钥,别人拿不走。正常断开、本机用户断开所有控制端、关掉“允许远程终端”时马上结束 - **伪终端**:macOS / Linux 是 `openpty` + 登录 shell(`setsid`、`TIOCSCTTY`);Windows 是 ConPTY。服务里的被控端是 SYSTEM,ConPTY 的宿主和里面的程序又得是同一个用户:它以控制台会话里登录的用户的身份(`WTSQueryUserToken`、`CreateEnvironmentBlock`)运行助手 `airhand.exe --terminal`,只让它继承两个管道(`PROC_THREAD_ATTRIBUTE_HANDLE_LIST`),终端开在助手里,经它的标准输入输出收发(`client/src-tauri/src/host/terminal/helper.rs`) - 控制端服务把输出解成文字交给界面(一个 UTF-8 字符被拆在两条里时前半截留到下一条),同时告诉界面这些文字是几个字节,界面按字节确认。控制台的终端(`client/src/lib/terminal.ts`)和 xterm.js 一起按需加载 +- **手机上**(Android 的 `controller/TerminalSession.kt`、iOS 的 `Terminal/TerminalSession.swift`):连接、重连、开终端、接回、确认和控制台一样,命令就是控制台的那几个(`terminalOpen` 等,经 `airhand-mobile` 的 `Ctl::call`)。显示用同一个 xterm.js:`client/mobile-terminal/` 是一个普通页面(不是模块,Android 的 WebView 从 `file:///android_asset` 打开模块脚本加载不了),构建时和 `client/node_modules` 里的 xterm.js 一起拷进 App(Android 的 `terminalAssets` 任务、iOS 的 `scripts/terminal-page.sh`),用 WebView / WKWebView 打开,和原生之间用 JSON 消息互相调用(见 `terminal.js` 开头)。页面属于会话、不属于界面:离开终端界面再回来内容还在;页面的进程被系统收回了就换一个新的,把没确认的都确认掉,再让程序重画一遍。键盘在原生那边(看不见的输入框,和远程画面一样处理输入法组字),打的字、快捷键栏上的键交给页面,按终端现在的模式(应用光标键)换成字节(`keys.js`)。弹出软键盘时终端**不改大小**:键盘盖在终端上,页面把光标所在的行挪到键盘上面。每开关一次键盘就改一次大小的话,claude 这类程序每次都整屏重画,Windows 的 ConPTY 在接回终端之后改大小还会和 xterm 对不上光标的位置。手势在页面里处理:一个手指滑是往回看(全屏的程序里是上下键,程序要鼠标时是滚轮事件),点一下弹出键盘,长按复制文字,两个手指捏改字号 ### 协议的演进 diff --git a/docs/building.md b/docs/building.md index 73e0e8fa..1b4e5528 100644 --- a/docs/building.md +++ b/docs/building.md @@ -98,7 +98,13 @@ rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-and cargo install cargo-ndk ``` -Then build in `android/` (Gradle first builds the Rust core in `android/native` with cargo-ndk). As on the desktop, the server address and fingerprint are compiled-in defaults that can be changed later in the app's Settings. +The remote terminal's page uses the desktop console's xterm.js, so install the client's dependencies once (`client/node_modules`; `--omit=dev` is enough for this): + +```bash +cd client && npm ci --omit=dev --ignore-scripts && cd .. +``` + +Then build in `android/` (Gradle first builds the Rust core in `android/native` with cargo-ndk, and copies `client/mobile-terminal` together with xterm.js into the app's assets). As on the desktop, the server address and fingerprint are compiled-in defaults that can be changed later in the app's Settings. Windows (PowerShell): diff --git a/docs/building.zh-CN.md b/docs/building.zh-CN.md index e0a94257..5fd0a8d9 100644 --- a/docs/building.zh-CN.md +++ b/docs/building.zh-CN.md @@ -98,7 +98,13 @@ rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-and cargo install cargo-ndk ``` -然后在 `android/` 里构建(Gradle 会先用 cargo-ndk 编译 `android/native` 里的 Rust 核心)。服务器地址和指纹和桌面版一样是编译进去的默认值,装好后可以在应用的“设置”里改。 +远程终端的页面用桌面控制台的 xterm.js,所以先装一次客户端的依赖(`client/node_modules`,这里只要 `--omit=dev` 的就够了): + +```bash +cd client && npm ci --omit=dev --ignore-scripts && cd .. +``` + +然后在 `android/` 里构建(Gradle 会先用 cargo-ndk 编译 `android/native` 里的 Rust 核心,再把 `client/mobile-terminal` 和 xterm.js 一起拷进应用的 assets)。服务器地址和指纹和桌面版一样是编译进去的默认值,装好后可以在应用的“设置”里改。 Windows(PowerShell): diff --git a/docs/ios.md b/docs/ios.md index 3bc6c3f9..3da26339 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -18,6 +18,7 @@ The UI follows the system language (Chinese / English), dark theme. - **Pairing code**: the first connection to a device asks for the 6-digit pairing code it shows; afterwards it remembers this iPhone / iPad. If its identity changed (reinstalled, or impersonated) you pair again - **My devices**: devices you connected to are saved — one tap to connect. Offline devices show “Offline · connects when it's back” and open automatically when they come online. Long-press to rename, copy the code, or delete (with undo) - **Links**: `airhand://connect/123456?pairing=654321` connects with one tap (`pairing` is optional) +- **Terminal**: next to **Connect** there's **Terminal**, and a terminal icon on each device in My devices: it opens just a command-line terminal on the computer, without its screen (for `claude`, `codex`, `pi`, builds…). The filled one of the two buttons is the one you tapped last, and it's what a completed code opens. See [Remote terminal](usage.md#remote-terminal) for the key bar, gestures and copying - The remote screen is full-screen with a single **draggable round button** (snaps to the left / right edge). It opens the menu: the remote's name, codec, frame rate, latency, bitrate, direct or relayed path and safety code at the top; then keyboard, sound, microphone, input mode, lock mouse, fit screen, rotate (iPhone), send files, gestures, home, disconnect; and pages for shortcuts, quality (presets, codec, A/V sync), clipboard, displays (multi-monitor), privacy mode (when the remote is Windows or a Mac) and game controls - On iPhone the screen follows the remote's orientation (landscape for computers), and the menu can rotate it; iPad rotates freely @@ -81,9 +82,10 @@ Settings, saved devices, the end-to-end identity, control code, pairing state an ## Building -On a Mac with Xcode 27+ (which needs Apple silicon and macOS 26.6 or later; the app still runs on iOS 17+), Rust with `rustup target add aarch64-apple-ios aarch64-apple-ios-sim`, and [XcodeGen](https://github.com/yonaskolb/XcodeGen): +On a Mac with Xcode 27+ (which needs Apple silicon and macOS 26.6 or later; the app still runs on iOS 17+), Rust with `rustup target add aarch64-apple-ios aarch64-apple-ios-sim`, [XcodeGen](https://github.com/yonaskolb/XcodeGen), and Node.js: the remote terminal's page uses the desktop console's xterm.js from `client/node_modules`, so run `npm ci --omit=dev --ignore-scripts` in `client/` once: ```bash +(cd client && npm ci --omit=dev --ignore-scripts) cd ios # IPA without a real signature (ad-hoc signed, entitlements included): build/Airhand.ipa AIRHAND_SERVER=relay.example.com:4433 AIRHAND_SERVER_FP= scripts/build-ipa.sh @@ -91,7 +93,7 @@ AIRHAND_SERVER=relay.example.com:4433 AIRHAND_SERVER_FP= scripts/bu TEAM_ID= EXPORT_METHOD=development AIRHAND_SERVER=... AIRHAND_SERVER_FP=... scripts/build-ipa.sh ``` -`EXPORT_METHOD` can also be `ad-hoc`, `app-store-connect` (TestFlight / App Store) or `enterprise`. For development, run `xcodegen generate` and open `ios/Airhand.xcodeproj`; a build phase compiles the Rust core (`ios/native`) for the current SDK with `scripts/build-rust.sh`. +`EXPORT_METHOD` can also be `ad-hoc`, `app-store-connect` (TestFlight / App Store) or `enterprise`. For development, run `xcodegen generate` and open `ios/Airhand.xcodeproj`; a build phase compiles the Rust core (`ios/native`) for the current SDK with `scripts/build-rust.sh`, and another copies the terminal page (`client/mobile-terminal` plus xterm.js) into the app with `scripts/terminal-page.sh`. iOS only runs signed apps: use your developer account, Xcode with a free Apple ID (re-install every 7 days; if the App Group capability isn't available, remote control still works but sharing doesn't), or re-sign the unsigned IPA with tools like Sideloadly / AltStore (the app and its extension must share one App Group). diff --git a/docs/ios.zh-CN.md b/docs/ios.zh-CN.md index 6421d82c..c11606d4 100644 --- a/docs/ios.zh-CN.md +++ b/docs/ios.zh-CN.md @@ -18,6 +18,7 @@ - **配对码**:第一次连接一台设备时要输入对方显示的 6 位配对码(弹出输入框),之后对方记住这台 iPhone / iPad。对方的身份变了(重装过,或者有人冒充)时也要重新配对 - **我的设备**:连接成功的设备自动保存,点一下就连;对方不在线时卡片上显示“对方不在线 · 上线后自动连接”,对方一上线就自动进入远程画面。长按可以重命名、复制控制码、删除(删除后可以撤销) - **链接**:`airhand://connect/123456?pairing=654321` 点一下就连(`pairing` 可以不带) +- **终端**:**连接**旁边有**终端**,我的设备里每台设备上也有终端图标:不传画面,只在对方电脑上开一个命令行终端(跑 `claude`、`codex`、`pi`、编译……)。两个按钮里实心的那个是最近一次点的,输满控制码时就按它来连。快捷键栏、手势、复制见[远程终端](usage.zh-CN.md#远程终端) - 远程画面全屏显示,只有一个**可以拖动的小圆钮**(松手后贴到左 / 右边),点开是菜单:顶部是对方名称、编码格式、帧率、延迟、码率、直连还是中转、安全码;下面是键盘、声音、麦克风、操作方式、锁定鼠标、适应屏幕、旋转画面(iPhone)、发送文件、手势说明、回到首页、断开,以及快捷键、画质(预设、编码格式、音画同步)、剪贴板、显示器(多屏时)、防窥模式(对方是 Windows、Mac 时)、游戏按键这几页 - iPhone 上画面跟着对方横 / 竖(电脑一般是横屏),菜单里可以转;iPad 随意转 @@ -99,8 +100,10 @@ iOS 不允许 App 自己安装新版本,发布的 IPA 也没有正式签名: - Xcode 27 或更新(带 iOS SDK;只能装在 Apple 芯片、macOS 26.6 或更新的 Mac 上;装好的应用仍然支持 iOS 17 及以上) - Rust([rustup](https://rustup.rs))和两个目标:`rustup target add aarch64-apple-ios aarch64-apple-ios-sim` - [XcodeGen](https://github.com/yonaskolb/XcodeGen)(`brew install xcodegen`,或者下载它的发布包):`ios/project.yml` 生成 Xcode 工程 +- Node.js:远程终端的页面用桌面控制台的 xterm.js(`client/node_modules`),先在 `client/` 里 `npm ci --omit=dev --ignore-scripts` 一次 ```bash +(cd client && npm ci --omit=dev --ignore-scripts) cd ios # 没有正式签名的 IPA(只做了 ad-hoc 签名,带着 App Group 等权限):build/Airhand.ipa AIRHAND_SERVER=relay.example.com:4433 AIRHAND_SERVER_FP=<指纹> scripts/build-ipa.sh @@ -110,7 +113,7 @@ TEAM_ID=<团队 ID> EXPORT_METHOD=development AIRHAND_SERVER=... AIRHAND_SERVER_ # EXPORT_METHOD 还可以是 ad-hoc(登记过的设备)、app-store-connect(TestFlight / App Store)、enterprise ``` -在 Xcode 里开发:`xcodegen generate` 之后打开 `ios/Airhand.xcodeproj`。编译时构建阶段会调用 `scripts/build-rust.sh` 按当前的 SDK 编译 Rust 核心(`ios/native`,静态库在 `ios/build/rust/<平台>/`)。 +在 Xcode 里开发:`xcodegen generate` 之后打开 `ios/Airhand.xcodeproj`。编译时构建阶段会调用 `scripts/build-rust.sh` 按当前的 SDK 编译 Rust 核心(`ios/native`,静态库在 `ios/build/rust/<平台>/`),再用 `scripts/terminal-page.sh` 把终端的页面(`client/mobile-terminal` 加上 xterm.js)拷进 App。 ### 安装 diff --git a/docs/usage.md b/docs/usage.md index 770f0542..41400e3c 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -378,9 +378,16 @@ When you only want to run command-line programs on the other computer (`claude`, - Authentication is the same as for remote control: only paired controllers can open one, the first time with the remote pairing code. The person at the remote computer can uncheck **Allow remote terminal** in the tray menu: terminal connections are then refused and open terminals end right away. In the tray's list of who is controlling the computer, controllers with a terminal are marked "(terminal)" - **Copy and paste**: select text and press Ctrl+C (⌘C on macOS) to copy; without a selection Ctrl+C interrupts as usual. Ctrl+V (⌘V) or right-click pastes (right-click copies when text is selected). The toolbar changes the text size and has full screen - **Survives dropped connections**: Airhand reconnects by itself, and the remote terminal is kept meanwhile (up to 30 minutes) with its programs still running; after reconnecting you get the same terminal back, with the output from while you were away (the latest 1 MiB if there was more). Closing the tab, or the remote user disconnecting all controllers, ends the terminal and its programs right away -- You can open several terminals on the same computer (one per tab). Phones don't have a terminal +- You can open several terminals on the same computer (one per tab). A phone can't be the remote side of a terminal (it has no shell to offer), but it can open one, see below - With a lot of output (say, `cat` on a big file) the remote side only sends as much as the console has shown, so nothing piles up and Ctrl+C takes effect right away +**From a phone (Android / iOS)**: on the Remote tab, type the control code and tap **Terminal** (instead of **Connect**), or tap the terminal icon next to a computer in My devices. Whichever of the two you tapped last is the filled one, and it's what a completed control code opens. It's the same terminal as on the desktop (xterm.js), full screen: + +- Tap the terminal to bring up the keyboard; Chinese and other input methods work as usual (the text being composed shows above the key bar). The key bar has Esc, Tab, ⇧Tab, Ctrl, Alt, the arrows, ^C, Home / End, PgUp / PgDn, a few symbols and F1–F12; Ctrl and Alt apply to the next key, tap twice to lock (Ctrl then `c` on the keyboard is Ctrl+C). A hardware keyboard works directly +- The keyboard doesn't resize the terminal: it covers the bottom and the terminal shifts up so the line with the cursor stays visible above it. Programs like claude or codex don't redraw every time the keyboard comes and goes +- Swipe to scroll back (in full-screen programs such as vim or less a swipe becomes the arrow keys, or the mouse wheel if the program asked for the mouse), pinch to change the text size (remembered), long-press (or **Copy text** in the menu) for a page with the recent output where you can select part of it or copy it all. Paste is on the key bar and in the menu +- Back returns to the home screen with the terminal still open (a card there takes you back). **Close terminal** in the menu ends it and the programs in it. One terminal at a time; it doesn't affect a remote control session that's open at the same time + ## 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 8625b163..e5faa0ed 100644 --- a/docs/usage.zh-CN.md +++ b/docs/usage.zh-CN.md @@ -378,9 +378,16 @@ rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/airhand" # 删除当前用户的配 - 认证和远程桌面一样:配对过的控制端才能开,第一次要输对方的配对码。对方电脑前的人可以在托盘菜单里取消**允许远程终端**:之后终端连接都被拒绝,开着的终端马上结束;托盘的“正在控制本机”列表里,开终端的控制端后面写着“(终端)” - **复制粘贴**:选中文字后按 Ctrl+C(macOS 是 ⌘C)复制,没有选中时 Ctrl+C 照常中断程序;Ctrl+V(⌘V)或者右键粘贴(选中了文字时右键是复制)。工具栏里可以调字号,按钮还有全屏 - **断线不丢**:网络断了照常自动重连,对方的终端在这期间留着(最多 30 分钟),里面的程序照常运行;重连之后接回原来的终端,断开期间的输出补上(太多的话只留最近的 1 MiB)。关掉标签、对方断开所有控制端时,终端连同里面的程序马上结束 -- 同一台电脑可以开好几个终端(每个标签一个)。被控端是手机时没有终端 +- 同一台电脑可以开好几个终端(每个标签一个)。手机做不了终端的被控端(它没有 shell 可以给你用),但可以用手机开终端,见下面 - 输出很多(例如 `cat` 一个大文件)时控制台处理多少,对方才发多少,不会越积越多,Ctrl+C 马上起作用 +**用手机开(Android / iOS)**:在“远程”页输入控制码后点**终端**(不点**连接**),或者点我的设备里那台电脑右边的终端图标。这两个按钮里最近一次点的那个是实心的,输满控制码时就按它来连。和桌面上是同一个终端(xterm.js),全屏显示: + +- 点一下终端弹出键盘,中文等输入法照常能用(组字中的文字显示在快捷键栏上方)。快捷键栏上有 Esc、Tab、⇧Tab、Ctrl、Alt、方向键、^C、Home / End、PgUp / PgDn、几个符号和 F1–F12;Ctrl、Alt 对下一个键有效,点两下锁定(点 Ctrl 再在键盘上打 `c` 就是 Ctrl+C)。外接键盘直接能用 +- 弹出键盘时终端不改大小:键盘盖住底下,终端往上挪,让光标所在的那一行露在键盘上面。claude、codex 这类程序不会因为键盘开开关关一直重画 +- 上下滑动看前面的输出(vim、less 这类全屏程序里滑动是上下键,程序要鼠标时是滚轮),双指捏合改字号(会记住),长按(或者菜单里的**复制文字**)打开最近的输出,可以选中一段复制,也可以全部复制。粘贴在快捷键栏和菜单里 +- 返回键回到首页,终端保持打开(首页上的卡片点一下回来);菜单里的**关闭终端**才结束它和里面的程序。同一时间一个终端,和同时开着的远程画面互不影响 + ## 界面语言 控制台和托盘菜单支持**简体中文**和**英文**。默认跟随系统显示语言:系统是中文就用中文,否则用英文。可以在托盘菜单“语言 / Language”或控制台菜单(左上角的图标)里的“中文 / EN”随时切换。选的语言记在 `config.toml` 里(`language`),以后一直用它;删掉这一项就重新跟随系统语言。 diff --git a/ios/Airhand/App.swift b/ios/Airhand/App.swift index 8f0ba598..bef19c57 100644 --- a/ios/Airhand/App.swift +++ b/ios/Airhand/App.swift @@ -22,8 +22,9 @@ struct AirhandApp: App { // 自动检查更新(打开了的话,最多 6 小时一次):找到了提示一次,点“查看”打开发布页面 app.updater.autoCheck() } - // 切到别的应用一会儿(复制个东西)再回来,会话不断:系统给的后台时间里连接保持着 - if p == .background, app.session != nil { + // 切到别的应用一会儿(复制个东西)再回来,会话不断:系统给的后台时间里连接保持着(终端也是; + // 被系统挂起断了的话,对方把终端留着,回来时重连接回原来的终端) + if p == .background, app.session != nil || app.terminal != nil { BackgroundTask.begin() } else if p == .active { BackgroundTask.end() diff --git a/ios/Airhand/Core/AppModel.swift b/ios/Airhand/Core/AppModel.swift index 7e74d734..46e258b8 100644 --- a/ios/Airhand/Core/AppModel.swift +++ b/ios/Airhand/Core/AppModel.swift @@ -29,6 +29,14 @@ final class AppModel { DispatchQueue.main.async { [self] in SessionPresenter.sync(self) } } } + /// 当前的远程终端(同一时间一个,和远程画面的会话互不影响,见 Terminal/) + var terminal: TerminalSession? + /// 远程终端全屏显示着(和 showingSession 一样在这里推出 / 收回) + var showingTerminal = false { + didSet { DispatchQueue.main.async { [self] in TerminalPresenter.sync(self) } } + } + /// 首页正在开终端的控制码(按钮上转圈) + var connectingTerminalCode: String? /// 首页正在连接的控制码(按钮上转圈),以及连接失败的原因 var connectingCode: String? var connectError: String? @@ -44,7 +52,9 @@ final class AppModel { struct PairingRequest: Identifiable { var code: String var problem: Problem - var id: String { code + problem.kind } + /// 是在开终端(输入配对码之后接着开终端) + var terminal = false + var id: String { code + problem.kind + (terminal ? "/terminal" : "") } } struct Toast: Equatable, Identifiable { @@ -160,6 +170,72 @@ final class AppModel { connectingCode = nil } + // ───────────────────────────── 远程终端 ───────────────────────────── + + /// 第一次连上时自动推出过的终端(之后重连不再自己弹出来:用户可能已经回到了首页) + @ObservationIgnored private weak var shownTerminal: TerminalSession? + + /// 在一台电脑上开远程终端(不传画面)。连接过程留在首页,连上了才进入终端。已经开着这台的就回到终端; + /// 开着别的会先关掉(首页上先问过用户) + func openTerminal(code: String, pairing: String? = nil) { + if let t = terminal { + if t.code == code, pairing == nil, t.phase.isActive { + if t.phase == .live { showingTerminal = true } + return + } + t.close() + terminal = nil + } + let s = TerminalSession(app: self, code: code, pairing: pairing) + terminal = s + connectingTerminalCode = code + connectError = nil + s.onPhase = { [weak self, weak s] phase in + guard let self, let s, self.terminal === s else { return } + self.onTerminalPhase(s, phase) + } + s.start() + } + + private func onTerminalPhase(_ s: TerminalSession, _ phase: RemoteSession.Phase) { + switch phase { + case .live: + connectingTerminalCode = nil + if shownTerminal !== s { + shownTerminal = s + showingTerminal = true + } + case .waitingHost: + connectingTerminalCode = nil + case .failed(let p): + connectingTerminalCode = nil + terminal = nil + showingTerminal = false + if p.needsPairing { + pairingFor = PairingRequest(code: s.code, problem: p, terminal: true) + } else { + connectError = Messages.problem(p) + } + case .ended(let p): + if !showingTerminal { + terminal = nil + connectError = Messages.problem(p) + } + case .closed: + if terminal === s { terminal = nil } + connectingTerminalCode = nil + default: break + } + } + + /// 关掉终端(里面的程序随之结束)、取消等待 + func closeTerminal() { + terminal?.close() + terminal = nil + showingTerminal = false + connectingTerminalCode = nil + } + /// 链接:`airhand://connect/123456?pairing=654321`(分享控制码时可以发这样的链接,点一下就连) func open(_ url: URL) { guard url.scheme == "airhand", url.host == "connect" || url.host == "c" else { return } diff --git a/ios/Airhand/Core/Protocol.swift b/ios/Airhand/Core/Protocol.swift index 6e69b60c..177547a7 100644 --- a/ios/Airhand/Core/Protocol.swift +++ b/ios/Airhand/Core/Protocol.swift @@ -74,11 +74,14 @@ enum Media { enum Commands { private static func cmd(_ name: String, _ sid: UInt32) -> JSON { ["cmd": name, "sid": sid] } - /// `privacy`:要不要防窥模式(重连时带上现在的开关,对方一开始就保持着,它的屏幕不会在重连的间隙露出来) + /// `privacy`:要不要防窥模式(重连时带上现在的开关,对方一开始就保持着,它的屏幕不会在重连的间隙露出来); + /// `terminal`:终端会话(不要画面和声音,只开终端,见 TerminalSession.swift) static func connect(code: String, resume: String?, settings: Quality, hostKey: String?, pairing: String?, audio: Bool, - privacy: Bool = false) -> JSON { - ["cmd": "connect", "code": code, "resume": Resume.toJson(resume), "hostKey": hostKey ?? NSNull(), - "pairing": pairing ?? NSNull(), "settings": settings.json, "audio": audio, "privacy": privacy] + privacy: Bool = false, terminal: Bool = false) -> JSON { + var c: JSON = ["cmd": "connect", "code": code, "resume": Resume.toJson(resume), "hostKey": hostKey ?? NSNull(), + "pairing": pairing ?? NSNull(), "settings": settings.json, "audio": audio, "privacy": privacy] + if terminal { c["terminal"] = true } + return c } static func input(_ sid: UInt32, _ events: [JSON]) -> JSON { var c = cmd("input", sid); c["events"] = events; return c } @@ -91,6 +94,32 @@ enum Commands { static func privacy(_ sid: UInt32, _ on: Bool) -> JSON { var c = cmd("privacy", sid); c["on"] = on; return c } static func clipboard(_ sid: UInt32, _ text: String) -> JSON { var c = cmd("clipboard", sid); c["text"] = text; return c } static func disconnect(_ sid: UInt32) -> JSON { cmd("disconnect", sid) } + + // ── 远程终端(见 TerminalSession.swift 和 Rust 的 airhand_proto::terminal)── + + /// 开第 `term` 个终端。`resume`:接回断线前的那个(对方给的凭证,收到了哪里) + static func terminalOpen(_ sid: UInt32, _ term: Int, cols: Int, rows: Int, resume: (token: String, offset: Int64)?) -> JSON { + var c = cmd("terminalOpen", sid) + c["term"] = term + c["size"] = ["cols": cols, "rows": rows] + c["resume"] = resume.map { ["token": $0.token, "offset": $0.offset] as JSON } ?? NSNull() + return c + } + + static func terminalInput(_ sid: UInt32, _ term: Int, _ data: String) -> JSON { + var c = cmd("terminalInput", sid); c["term"] = term; c["data"] = data; return c + } + + static func terminalResize(_ sid: UInt32, _ term: Int, cols: Int, rows: Int) -> JSON { + var c = cmd("terminalResize", sid); c["term"] = term; c["size"] = ["cols": cols, "rows": rows]; return c + } + + /// 界面显示了到 `offset` 为止的输出(累积的位置) + static func terminalAck(_ sid: UInt32, _ term: Int, _ offset: Int64) -> JSON { + var c = cmd("terminalAck", sid); c["term"] = term; c["offset"] = offset; return c + } + + static func terminalClose(_ sid: UInt32, _ term: Int) -> JSON { var c = cmd("terminalClose", sid); c["term"] = term; return c } } /// 重连凭证:Rust 那边是 16 个字节(JSON 数组),这里存成十六进制字符串 diff --git a/ios/Airhand/Terminal/TerminalController.swift b/ios/Airhand/Terminal/TerminalController.swift new file mode 100644 index 00000000..1ac2e0b9 --- /dev/null +++ b/ios/Airhand/Terminal/TerminalController.swift @@ -0,0 +1,432 @@ +import Observation +import SwiftUI +import UIKit + +/// 远程终端(全屏):上面一条标题栏(连的是哪台、延迟、菜单),中间是终端(TerminalWebView),下面是快捷键栏 +/// (Esc、Tab、Ctrl、Alt、方向键……)。弹出软键盘时终端不改大小(不然每开关一次键盘对方就重排一次):快捷键栏挪到 +/// 键盘上面,页面把光标所在的行挪到它上面(见 terminal.js)。 +/// +/// 会话本身在 TerminalSession 里(属于整个应用),这个界面只是显示它:左上角的返回回到首页、终端保持打开 +/// (首页上点一下回来),菜单里“关闭终端”才结束它(里面的程序随之结束)。和 Android 的 TerminalActivity 一样 +final class TerminalController: UIViewController { + let app: AppModel + let session: TerminalSession + private let keyField = KeyField() + private let keys = TerminalKeyState() + private let ui = TerminalUIState() + private var topHost: UIHostingController! + private var barHost: UIHostingController! + private var overlayHost: UIHostingController! + private var toastHost: UIHostingController! + private let composingLabel = UILabel() + /// 现在放在界面里的页面(会话换了页面时换掉) + private weak var shownWeb: TerminalWebView? + private var keyboardHeight: CGFloat = 0 + private var lastBell: CFTimeInterval = 0 + + static let topHeight: CGFloat = 48 + static let barHeight: CGFloat = 50 + + init(app: AppModel, session: TerminalSession) { + self.app = app + self.session = session + super.init(nibName: nil, bundle: nil) + modalPresentationStyle = .fullScreen + } + + required init?(coder: NSCoder) { fatalError() } + + override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent } + override var canBecomeFirstResponder: Bool { true } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = TerminalWebView.background + keys.session = session + + keyField.frame = CGRect(x: -100, y: -100, width: 10, height: 10) + keyField.onText = { [weak self] t in self?.keys.text(t) } + keyField.onBackspace = { [weak self] in self?.keys.key("Backspace") } + keyField.onEnter = { [weak self] in self?.keys.key("Enter") } + keyField.onComposing = { [weak self] s in self?.setComposing(s) } + keyField.onPresses = { [weak self] p, down in self?.hardwareKeys(p, down, typing: true) ?? false } + view.addSubview(keyField) + + overlayHost = UIHostingController(rootView: TerminalOverlay(session: session, close: { [weak self] in self?.app.closeTerminal() })) + overlayHost.view.backgroundColor = .clear + addChild(overlayHost) + view.addSubview(overlayHost.view) + overlayHost.didMove(toParent: self) + + topHost = UIHostingController(rootView: TerminalTopBar(session: session, actions: TerminalTopBar.Actions( + back: { [weak self] in self?.app.showingTerminal = false }, + copy: { [weak self] in self?.openCopy() }, + paste: { [weak self] in self?.paste() }, + bottom: { [weak self] in self?.session.scrollToBottom() }, + help: { [weak self] in self?.showHelp() }, + close: { [weak self] in self?.confirmClose() } + ))) + topHost.view.backgroundColor = .clear + addChild(topHost) + view.addSubview(topHost.view) + topHost.didMove(toParent: self) + + barHost = UIHostingController(rootView: TerminalKeyBar( + keys: keys, ui: ui, + paste: { [weak self] in self?.paste() }, + toggleKeyboard: { [weak self] in self?.setKeyboard(!(self?.keyField.isFirstResponder ?? false)) } + )) + barHost.view.backgroundColor = .clear + addChild(barHost) + view.addSubview(barHost.view) + barHost.didMove(toParent: self) + + toastHost = UIHostingController(rootView: TerminalToast(app: app)) + toastHost.view.backgroundColor = .clear + toastHost.sizingOptions = [.intrinsicContentSize] + addChild(toastHost) + view.addSubview(toastHost.view) + toastHost.didMove(toParent: self) + + composingLabel.font = .systemFont(ofSize: 18) + composingLabel.textColor = .white + composingLabel.textAlignment = .center + composingLabel.backgroundColor = UIColor.black.withAlphaComponent(0.85) + composingLabel.layer.cornerRadius = 10 + composingLabel.clipsToBounds = true + composingLabel.isHidden = true + view.addSubview(composingLabel) + + session.onGesture = { [weak self] g in self?.gesture(g) } + NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrame(_:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrame(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) + observe { [weak self] in self?.sessionChanged() } + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + if !keyField.isFirstResponder { becomeFirstResponder() } + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + keyField.resignFirstResponder() + } + + /// 观察 TerminalSession 的变化(UIKit 里用 Observation) + private func observe(_ apply: @escaping () -> Void) { + withObservationTracking(apply) { [weak self] in + DispatchQueue.main.async { if self != nil { self?.observe(apply) } } + } + } + + private func sessionChanged() { + let phase = session.phase + let state = session.termState + let web = session.web + if web !== shownWeb { + shownWeb?.removeFromSuperview() + view.insertSubview(web, at: 0) + shownWeb = web + view.setNeedsLayout() + } + // 正常显示着终端时不盖东西(盖着的那一层会挡住手指) + overlayHost.view.isHidden = phase == .live && state == .open + // 提示来了 / 没了:按它的大小重新摆(没有提示时是 0 高,不挡手指) + _ = app.toast + view.setNeedsLayout() + // 连接断了、程序退出了、开不了:收起键盘(不然挡着卡片上的按钮) + if phase != .live || state == .exited || state == .failed { setKeyboard(false) } + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + let b = view.bounds + let safe = view.safeAreaInsets + let width = b.width - safe.left - safe.right + topHost.view.frame = CGRect(x: safe.left, y: safe.top, width: width, height: Self.topHeight) + // 终端的大小不跟着键盘变:从标题栏下面到(没有键盘时的)快捷键栏上面 + let bottom = b.height - safe.bottom + let termTop = safe.top + Self.topHeight + let term = CGRect(x: safe.left, y: termTop, width: width, height: max(0, bottom - Self.barHeight - termTop)) + shownWeb?.frame = term + overlayHost.view.frame = term + let toast = toastHost.view.intrinsicContentSize + let toastWidth = min(width - 32, max(toast.width, 0)) + toastHost.view.frame = CGRect(x: b.midX - toastWidth / 2, y: termTop + 8, width: toastWidth, height: max(toast.height, 0)) + let barY = keyboardHeight > 0 ? b.height - keyboardHeight - Self.barHeight : bottom - Self.barHeight + barHost.view.frame = CGRect(x: safe.left, y: barY, width: width, height: Self.barHeight) + // 快捷键栏和键盘盖住了终端底下多高:页面把光标所在的行挪到它上面 + session.setInset(Int(max(0, term.maxY - barY).rounded())) + if !composingLabel.isHidden { + let size = composingLabel.sizeThatFits(CGSize(width: width - 32, height: 40)) + let w = min(width - 32, size.width + 28) + composingLabel.frame = CGRect(x: b.midX - w / 2, y: barY - 48, width: w, height: 40) + } + } + + // ───────────────────────────── 键盘 ───────────────────────────── + + private var active: Bool { session.phase == .live && (session.termState == .open || session.termState == .opening) } + + func setKeyboard(_ on: Bool) { + if on { + guard active else { return } + keyField.becomeFirstResponder() + } else if keyField.isFirstResponder { + keyField.resignFirstResponder() + becomeFirstResponder() + } + } + + @objc private func keyboardFrame(_ n: Notification) { + var h: CGFloat = 0 + if n.name != UIResponder.keyboardWillHideNotification, let f = n.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { + let local = view.convert(f, from: nil) + h = max(0, view.bounds.maxY - local.minY) + } + ui.keyboard = h > 0 && keyField.isFirstResponder + if h == keyboardHeight { return } + keyboardHeight = h + UIView.animate(withDuration: 0.25) { + self.view.setNeedsLayout() + self.view.layoutIfNeeded() + } + } + + /// 输入法正在组字(拼音等)的内容,显示在快捷键栏上方 + private func setComposing(_ s: String) { + composingLabel.text = s + composingLabel.isHidden = s.isEmpty + view.setNeedsLayout() + } + + override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { + if !hardwareKeys(presses, true, typing: false) { super.pressesBegan(presses, with: event) } + } + + override func pressesEnded(_ presses: Set, with event: UIPressesEvent?) { + if !hardwareKeys(presses, false, typing: false) { super.pressesEnded(presses, with: event) } + } + + /// 外接键盘发给终端的键。`typing`:输入框拿着键盘(打的字交给它,输入法要组字),只拦特殊键和 Ctrl / Alt 的组合; + /// 不然(软键盘收起来了)所有的键都在这里发。⌘ 的组合键留给系统(⌘V 粘贴、⌘Tab……) + private func hardwareKeys(_ presses: Set, _ down: Bool, typing: Bool) -> Bool { + guard active else { return false } + if typing && keyField.markedTextRange != nil { return false } + var handled = false + for p in presses { + guard let k = p.key else { continue } + let f = k.modifierFlags + if f.contains(.command) { continue } + let ctrl = f.contains(.control) + let alt = f.contains(.alternate) + if let name = Self.namedKey(k.keyCode.rawValue, typing: typing) { + handled = true + if down { keys.key(name, shift: f.contains(.shift), ctrl: ctrl, alt: alt) } + } else if ctrl || alt || !typing { + let s = ctrl || alt ? k.charactersIgnoringModifiers : k.characters + guard !s.isEmpty else { continue } + handled = true + if down { keys.text(s, ctrl: ctrl, alt: alt) } + } + } + return handled + } + + /// 按名字发的键(HID 键码 → KeyboardEvent.key,见 keys.js)。输入框拿着键盘时回车、退格交给它(输入法可能要用) + private static func namedKey(_ hid: Int, typing: Bool) -> String? { + guard let code = KeyMap.code(hid: hid) else { return nil } + switch code { + case "Enter", "NumpadEnter": return typing ? nil : "Enter" + case "Backspace": return typing ? nil : "Backspace" + case "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Escape", "Tab", "Home", "End", "PageUp", "PageDown", + "Delete", "Insert": + return code + default: + return code.count <= 3 && code.hasPrefix("F") ? code : nil + } + } + + // ───────────────────────────── 手势、菜单 ───────────────────────────── + + /// 页面上的手势:点一下弹出键盘,长按复制文字,响铃时震一下(最多一秒一次) + private func gesture(_ g: TerminalSession.Gesture) { + switch g { + case .tap: + setKeyboard(true) + case .longPress: + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + openCopy() + case .bell: + let now = CACurrentMediaTime() + if now - lastBell > 1 { + lastBell = now + UIImpactFeedbackGenerator(style: .light).impactOccurred() + } + } + } + + private func paste() { + guard let text = UIPasteboard.general.string, !text.isEmpty else { + app.show(L.t("clipboard_empty")) + return + } + session.paste(text) + } + + private func openCopy() { + session.copyText { [weak self] text in + guard let self, self.presentedViewController == nil else { return } + let nav = UINavigationController(rootViewController: TerminalCopyController(text: text) { [weak self] in + self?.app.show(L.t("copied")) + }) + nav.overrideUserInterfaceStyle = .dark + if let sheet = nav.sheetPresentationController { + sheet.detents = [.medium(), .large()] + sheet.prefersGrabberVisible = true + } + self.setKeyboard(false) + self.present(nav, animated: true) + } + } + + private func showHelp() { + let a = UIAlertController(title: L.t("terminal"), message: L.t("terminal_help"), preferredStyle: .alert) + a.addAction(UIAlertAction(title: L.t("close"), style: .cancel)) + present(a, animated: true) + } + + private func confirmClose() { + let a = UIAlertController(title: L.t("terminal_close_title"), message: L.t("terminal_close_text", session.hostName), preferredStyle: .alert) + a.addAction(UIAlertAction(title: L.t("cancel"), style: .cancel)) + a.addAction(UIAlertAction(title: L.t("terminal_close"), style: .destructive) { [weak self] _ in self?.app.closeTerminal() }) + present(a, animated: true) + } +} + +/// 终端界面的状态(SwiftUI 部分观察) +@Observable +final class TerminalUIState { + /// 软键盘开着 + var keyboard = false +} + +/// 远程终端的键盘:软键盘打的字、快捷键栏的特殊键、外接键盘,都交给 TerminalSession(页面里换成终端的字节)。 +/// Ctrl / Alt 在快捷键栏上是“粘滞”的(和远程画面的快捷键栏一样):点一下只对下一个键有效,再点一下锁定,再点取消。 +/// 比如点 Ctrl 再在软键盘上打 c,发出去的就是 Ctrl+C(0x03) +@Observable +final class TerminalKeyState { + var ctrl: KeyboardState.Sticky = .off + var alt: KeyboardState.Sticky = .off + @ObservationIgnored weak var session: TerminalSession? + + func toggleCtrl() { ctrl = Self.next(ctrl) } + func toggleAlt() { alt = Self.next(alt) } + + private static func next(_ s: KeyboardState.Sticky) -> KeyboardState.Sticky { + switch s { + case .off: return .once + case .once: return .locked + case .locked: return .off + } + } + + private func consumeOnce() { + if ctrl == .once { ctrl = .off } + if alt == .once { alt = .off } + } + + /// 按一个特殊键(KeyboardEvent.key:Escape、ArrowUp……),带上快捷键栏上点了的修饰键 + func key(_ name: String, shift: Bool = false, ctrl withCtrl: Bool = false, alt withAlt: Bool = false) { + session?.key(name, ctrl: withCtrl || ctrl != .off, alt: withAlt || alt != .off, shift: shift) + consumeOnce() + } + + /// 打的字 + func text(_ s: String, ctrl withCtrl: Bool = false, alt withAlt: Bool = false) { + guard !s.isEmpty else { return } + session?.text(s, ctrl: withCtrl || ctrl != .off, alt: withAlt || alt != .off) + consumeOnce() + } +} + +/// 复制文字:终端里最近的输出,选中一段复制,或者全部复制 +final class TerminalCopyController: UIViewController { + private let text: String + private let copied: () -> Void + private let textView = UITextView() + private var scrolled = false + + init(text: String, copied: @escaping () -> Void) { + self.text = text + self.copied = copied + super.init(nibName: nil, bundle: nil) + } + + required init?(coder: NSCoder) { fatalError() } + + override func viewDidLoad() { + super.viewDidLoad() + title = L.t("terminal_copy") + view.backgroundColor = TerminalWebView.background + textView.isEditable = false + textView.isSelectable = true + textView.backgroundColor = TerminalWebView.background + textView.textColor = text.isEmpty ? .gray : UIColor(red: 0.89, green: 0.9, blue: 0.94, alpha: 1) + textView.font = .monospacedSystemFont(ofSize: 12, weight: .regular) + textView.textContainerInset = UIEdgeInsets(top: 12, left: 10, bottom: 12, right: 10) + textView.text = text.isEmpty ? L.t("terminal_copy_empty") : text + textView.frame = view.bounds + textView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + view.addSubview(textView) + navigationItem.prompt = text.isEmpty ? nil : L.t("terminal_copy_hint") + navigationItem.leftBarButtonItem = UIBarButtonItem(systemItem: .close, primaryAction: UIAction { [weak self] _ in + self?.dismiss(animated: true) + }) + if !text.isEmpty { + navigationItem.rightBarButtonItem = UIBarButtonItem(title: L.t("terminal_copy_all"), primaryAction: UIAction { [weak self] _ in + guard let self else { return } + UIPasteboard.general.string = self.text + self.copied() + self.dismiss(animated: true) + }) + } + } + + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + // 一打开就在最后(最新的输出) + guard !scrolled, !text.isEmpty, textView.bounds.height > 0 else { return } + scrolled = true + let y = max(0, textView.contentSize.height - textView.bounds.height + textView.adjustedContentInset.bottom) + textView.setContentOffset(CGPoint(x: 0, y: y), animated: false) + } +} + +/// 把远程终端(UIKit)全屏推出来、收回去(AppModel.showingTerminal 改了就调用),和远程画面的 SessionPresenter 一样 +enum TerminalPresenter { + static func sync(_ app: AppModel) { + guard let root = UIApplication.shared.connectedScenes.compactMap({ ($0 as? UIWindowScene)?.keyWindow }).first?.rootViewController else { return } + let current = find(root) + if app.showingTerminal, let s = app.terminal { + if current?.session === s { return } + if let current { current.dismiss(animated: false) } + let vc = TerminalController(app: app, session: s) + var host = root + while let p = host.presentedViewController, !(p is TerminalController) { host = p } + host.present(vc, animated: true) + } else if let current, !current.isBeingDismissed { + current.presentingViewController?.dismiss(animated: true) + } + } + + private static func find(_ root: UIViewController) -> TerminalController? { + var v: UIViewController? = root + while let c = v { + if let t = c as? TerminalController { return t } + v = c.presentedViewController + } + return nil + } +} diff --git a/ios/Airhand/Terminal/TerminalSession.swift b/ios/Airhand/Terminal/TerminalSession.swift new file mode 100644 index 00000000..da64b7a0 --- /dev/null +++ b/ios/Airhand/Terminal/TerminalSession.swift @@ -0,0 +1,569 @@ +import Foundation +import Observation +import UIKit + +/// 远程终端(终端会话,见 Rust 的 `airhand_proto::terminal`):不传画面,在对方电脑上开一个终端,用 xterm.js 显示 +/// (TerminalWebView)。和桌面控制台的 `client/src/lib/terminal.ts`、Android 的 TerminalSession.kt 是同一套做法。 +/// +/// * 连接、断线重连、等对方上线和 RemoteSession 一样(重连凭证、配对码),只是连接选项里带着 `terminal`: +/// 对方不采集画面。第一次就没连上(控制码不对、要配对码、对方没开远程终端……)是 `.failed`,回到首页说明原因; +/// * 会话断了(网络断了)对方把终端留着(最多 30 分钟)、里面的程序照常运行;重连之后带着对方给的凭证(token)和 +/// 收到了哪里再开,就接回原来的终端,断开期间的输出补上; +/// * 流量控制:页面里的 xterm 处理完一段输出才确认(terminalAck)。对方发出去、没确认的输出有上限, +/// `cat` 大文件时输出不会在中间越积越多,Ctrl+C 也马上起作用。 +/// +/// 连接在自己的线程上;终端的状态(开着第几个、收到了哪里……)都在主线程上改,和页面的消息一个顺序。 +/// 同一时间一个终端会话(和远程画面的会话互不影响),属于整个应用:离开终端界面再回来还是它。 +@Observable +final class TerminalSession { + /// 终端现在怎么样(会话连着的时候):正在开 / 接回、开着、里面的程序退出了、开不了 + enum TermState { case opening, open, exited, failed } + + /// 开不了的原因(Rust 的 `TermError`:unavailable / noUser / tooMany / expired / spawnFailed)和技术信息 + struct TermError: Equatable { + var error: String + var detail: String? + } + + /// 页面上的手势,界面来处理 + enum Gesture { case tap, longPress, bell } + + let code: String + private(set) var phase: RemoteSession.Phase = .connecting + private(set) var hostName: String + private(set) var hostOs: String + /// 对方报告的平台(Hello 之后才有) + private(set) var platform: OsKind = .unknown + /// 往返时延(输入、输出都走控制通道) + private(set) var rttMs: Double? + /// 安全码(连上之后才有):对方屏幕上显示的是同一个 + private(set) var safety: String? + private(set) var termState: TermState = .opening + /// 里面的程序的退出码(`.exited`,不知道时为 nil) + private(set) var exitCode: Int? + private(set) var termError: TermError? + private(set) var fontSize: Int + /// 显示终端的页面:会话一开始就建好,界面只是把它放进来。页面的进程没了时换一个新的(`pageGone`),界面跟着换 + private(set) var web: TerminalWebView + + @ObservationIgnored var onPhase: ((RemoteSession.Phase) -> Void)? + @ObservationIgnored var onGesture: ((Gesture) -> Void)? + + /// 对方的平台:连上之后以对方报告的为准,之前按系统名称猜 + var os: OsKind { platform != .unknown ? platform : OsKind.of(hostOs) } + + @ObservationIgnored private weak var app: AppModel? + @ObservationIgnored private let client: ControllerClient + @ObservationIgnored private let saved: SavedDevice? + @ObservationIgnored private var resume: String? + @ObservationIgnored private var hostKey: String? + @ObservationIgnored private var pairing: String? + @ObservationIgnored private let wake = NSCondition() + @ObservationIgnored private var woken = false + @ObservationIgnored private var closed = false + @ObservationIgnored private var connectedOnce = false + @ObservationIgnored private var handle: Int64 = 0 + @ObservationIgnored private var sid: Int64 = -1 + @ObservationIgnored private var handlerIds: [UUID] = [] + + // ── 终端的状态(主线程)── + + /// 这个会话里的终端的编号(每开一次、接回一次加一) + @ObservationIgnored private var termId = 0 + /// 接回终端用的凭证(对方开好时给的) + @ObservationIgnored private var token: String? + /// 交给页面的输出到了哪里(下一个字节的位置):接回终端时从这里接着要 + @ObservationIgnored private var received: Int64 = 0 + /// 页面量出来的终端大小(字符数),还没量时是 0 + @ObservationIgnored private var cols = 0 + @ObservationIgnored private var rows = 0 + @ObservationIgnored private var openTimeout: DispatchWorkItem? + /// 软键盘挡住了页面底下多高(点) + @ObservationIgnored private var inset = 0 + /// 新的页面量出大小之后让程序重画(`pageGone`) + @ObservationIgnored private var redraw = false + + /// 终端会话用不上画质,Rust 那边要一个:按默认的 + private static let settings = Quality(fps: 30, kbps: 4000, maxShort: 1080, adaptive: true, codec: .h264) + /// 一次最多粘贴这么多(和桌面一样) + static let maxPaste = 512 * 1024 + /// 一条输入最多这么多个字(长的粘贴分几条发) + private static let inputChunk = 16 * 1024 + /// "复制文字"最多拿最近这么多行 + private static let copyLines = 2000 + static let fontRange = 8...28 + + init(app: AppModel, code: String, pairing: String?) { + self.app = app + self.client = app.controller + self.code = code + self.pairing = pairing + saved = app.devices.get(code) + resume = saved?.resume.isEmpty == false ? saved?.resume : nil + hostKey = saved?.hostKey + hostName = saved?.title ?? Code.format(code) + hostOs = saved?.hostOs ?? "" + let font = min(max(app.settings.terminalFont, Self.fontRange.lowerBound), Self.fontRange.upperBound) + fontSize = font + web = TerminalWebView(fontSize: font) + wire(web) + } + + private func wire(_ w: TerminalWebView) { + w.onMessage = { [weak self] m in self?.pageMessage(m) } + w.onGone = { [weak self] in self?.pageGone() } + } + + func start() { + handlerIds.append(client.onHostOnline { [weak self] c in if c == self?.code { self?.signal() } }) + var was: ServerState? + handlerIds.append(client.onServer { [weak self] s in + if s.isConnected, was?.isConnected != true { self?.signal() } + was = s + }) + let t = Thread { [weak self] in self?.run() } + t.name = "airhand-terminal" + t.qualityOfService = .userInteractive + t.start() + } + + // ───────────────────────────── 连接 ───────────────────────────── + + private func signal() { + wake.lock() + woken = true + wake.broadcast() + wake.unlock() + } + + private func sleep(_ seconds: Double) { + wake.lock() + if !woken && !closed { _ = wake.wait(until: Date().addingTimeInterval(seconds)) } + woken = false + wake.unlock() + } + + /// 在主线程上改终端的状态(会话关了就不改了) + private func ui(_ f: @escaping () -> Void) { + DispatchQueue.main.async { if !self.closed { f() } } + } + + private func setPhase(_ p: RemoteSession.Phase) { + DispatchQueue.main.async { + guard self.phase != .closed || p == .closed else { return } + self.phase = p + self.onPhase?(p) + } + } + + private func run() { + client.acquire() + defer { + client.release() + if closed { setPhase(.closed) } + } + var attempts = 0 + while !closed { + if let p = waitServer(connectedOnce ? .infinity : 12) { + setPhase(.failed(p)) + break + } + if closed { break } + let h = client.handle + // 终端会话用不上画质和声音(对方不采集画面) + let cmd = Commands.connect(code: code, resume: resume, settings: Self.settings, hostKey: hostKey, pairing: pairing, + audio: false, terminal: true) + let r = Json.parse(Native.ctlCall(h, Json.string(cmd))) ?? ["err": ["kind": "failed", "detail": "bad reply"]] + if closed { + if let ok = r.obj("ok"), let s = ok.int("sid") { _ = Native.ctlCall(h, Json.string(Commands.disconnect(UInt32(s)))) } + break + } + if let ok = r.obj("ok"), let s = ok.int("sid") { + attempts = 0 + onConnected(h, ok, UInt32(s)) + guard let end = pump(h, UInt32(s)) else { break } + sid = -1 + DispatchQueue.main.async { self.rttMs = nil } + if closed { break } + if !end.retry { + // 对方断开了我们、换了控制码:终端也结束了,凭证不再有用 + if end.problem.kind == "kicked" || end.problem.kind == "codeChanged" { + resume = nil + ui { self.token = nil } + } + setPhase(.ended(end.problem)) + break + } + setPhase(.reconnecting(end.problem)) + sleep(0.8) + continue + } + let p = Problem.parse(r.obj("err")) + attempts += 1 + switch p.kind { + // 和远程画面一样:带着凭证而对方不在线时等它上线 + case "hostOffline": + setPhase(.waitingHost(p)) + sleep(60) + // 重连凭证作废了:还没连上过就丢掉凭证、用控制码直接连;连上过就不再自动重连 + case "kicked": + let retryPlain = resume != nil && !connectedOnce + resume = nil + if retryPlain { continue } + setPhase(connectedOnce ? .ended(p) : .failed(p)) + return + case "notConnected", "serverTimeout", "serverLost": + if !connectedOnce && attempts >= 3 { + setPhase(.failed(p)) + return + } + if connectedOnce { setPhase(.reconnecting(p)) } + sleep(1.6) + default: + setPhase(connectedOnce ? .ended(p) : .failed(p)) + return + } + } + } + + /// 等到连上服务器。返回 nil 表示连上了;第一次连接时等不到就返回原因(和 RemoteSession 一样) + private func waitServer(_ limit: Double) -> Problem? { + let start = Date() + while !closed { + switch client.state { + case .connected: + if client.handle != 0 { return nil } + case .disconnected(let reason): + if !connectedOnce && ["incompatible", "certMismatch", "failed"].contains(reason.kind) { return reason } + if Date().timeIntervalSince(start) > limit { return reason } + case .connecting: + if Date().timeIntervalSince(start) > limit { return Problem(kind: "serverTimeout") } + } + Thread.sleep(forTimeInterval: 0.1) + } + return nil + } + + /// 连上了(第一次和每次重连):记进"我的设备",开终端(断线前开着的就接回来) + private func onConnected(_ h: Int64, _ ok: JSON, _ s: UInt32) { + handle = h + sid = Int64(s) + resume = Resume.fromJson(ok.arr("resume")) ?? resume + if let k = ok.str("hostKey"), !k.isEmpty { hostKey = k } + pairing = nil + connectedOnce = true + let safety = ok.str("safety") + let name = ok.str("hostName") ?? "" + let os = ok.str("hostOs") ?? "" + let r = resume ?? "" + let key = hostKey + ui { + self.safety = safety?.isEmpty == false ? safety : nil + if !name.isEmpty, self.saved?.alias.isEmpty != false { self.hostName = name } + if !os.isEmpty { self.hostOs = os } + // 和桌面一样:只记下这台电脑和重连凭证 + self.app?.devices.connected(code: self.code, name: name, os: os, resume: r, hostKey: key) + self.openTerminal() + } + setPhase(.live) + Log.info("terminal session connected to \(code) (\(name), \(os))") + } + + /// 读会话数据直到会话结束。返回 (原因, 是否重连);用户关闭时返回 nil + private func pump(_ h: Int64, _ s: UInt32) -> (problem: Problem, retry: Bool)? { + while !closed { + if client.handle != h { return (Problem(kind: "serverLost", detail: "connection restarted"), true) } + switch Native.ctlPollSession(h, s, 250) { + case .timeout: continue + case .gone: return (Problem(kind: "sessionEnded"), true) + case .data(let b): + // 终端会话只有事件(JSON),没有画面、声音 + guard b.first == UInt8(ascii: "{"), let e = Json.parse(b) else { continue } + if e.str("type") == "closed" { + _ = Native.ctlCall(h, Json.string(Commands.disconnect(s))) + return (Problem.parse(e.obj("reason")), (e["retry"] as? Bool) ?? true) + } + handleEvent(e) + } + } + return nil + } + + private func handleEvent(_ e: JSON) { + switch e.str("type") { + case "hello": + let p = OsKind.fromWire(e.str("platform")) + let name = e.str("hostname") ?? "" + ui { + self.platform = p + // 对方是 Windows:输出来自 ConPTY(换行、改大小时的重排由它做) + self.web.call("windows", p == .windows) + if !name.isEmpty, self.saved?.alias.isEmpty != false { self.hostName = name } + } + case "stats": + let rtt = e.dbl("rttMs") + ui { self.rttMs = rtt } + case "terminalOpened": + let term = e.int("term") ?? 0 + let tok = e.str("token") ?? "" + let offset = (e["offset"] as? NSNumber)?.int64Value ?? 0 + let resumed = e.bool("resumed") + ui { self.onOpened(term, tok, offset, resumed) } + case "terminalOutput": + let term = e.int("term") ?? 0 + let data = e.str("data") ?? "" + let bytes = (e["bytes"] as? NSNumber)?.int64Value ?? 0 + ui { self.onOutput(term, data, bytes) } + case "terminalExited": + let term = e.int("term") ?? 0 + let code = e.int("code") + ui { self.onExited(term, code) } + case "terminalFailed": + let term = e.int("term") ?? 0 + let error = e.str("error").flatMap { $0.isEmpty ? nil : $0 } ?? "unavailable" + let err = TermError(error: error, detail: e.str("detail")) + ui { self.onFailed(term, err) } + default: break + } + } + + // ───────────────────────────── 终端(主线程)───────────────────────────── + + /// 会话连上了:开终端,断线前开着的就接回来。程序退出了、开不了的不再开(用户点"重新打开"才开新的) + private func openTerminal() { + guard sid >= 0, termState != .exited, termState != .failed else { return } + termState = .opening + termId += 1 + let id = termId + let (c, r) = size() + let back: (token: String, offset: Int64)? = token.map { (token: $0, offset: received) } + command { Commands.terminalOpen($0, id, cols: c, rows: r, resume: back) } + openTimeout?.cancel() + let w = DispatchWorkItem { [weak self] in + guard let self, self.termId == id, self.termState == .opening, self.sid >= 0 else { return } + // 对方的 Airhand 多半太旧,不认识终端的消息 + self.termError = TermError(error: "unavailable", detail: "no answer (the remote Airhand may be too old for terminals)") + self.termState = .failed + } + openTimeout = w + DispatchQueue.main.asyncAfter(deadline: .now() + 15, execute: w) + } + + /// 终端的大小:页面量出来的;还没量(终端界面还没打开)时按屏幕的大小估一个,打开之后再改 + private func size() -> (Int, Int) { + if cols > 0, rows > 0 { return (cols, rows) } + let b = UIScreen.main.bounds + let font = Double(fontSize) + // 等宽字大约 0.6 个字号宽,一行大约 1.3 个字号高;上下还有状态栏、标题栏、快捷键栏 + let c = Int((Double(b.width) - 8) / (font * 0.6)) + let r = Int((Double(b.height) - 190) / (font * 1.3)) + return (min(max(c, 20), 500), min(max(r, 5), 300)) + } + + private func onOpened(_ term: Int, _ tok: String, _ offset: Int64, _ resumed: Bool) { + guard term == termId else { return } + if resumed && offset > received { + // 断开太久,中间有一段输出对方没留住 + web.call("note", L.t("terminal_gap")) + } else if !resumed && token != nil { + // 原来的终端已经不在了,这是新开的 + web.call("note", L.t("terminal_new_shell")) + } + openTimeout?.cancel() + token = tok + received = offset + web.call("begin", termId, offset) + termState = .open + // 对方开的时候按的是那时的大小:期间可能变了 + sendResize() + } + + private func onOutput(_ term: Int, _ data: String, _ bytes: Int64) { + guard term == termId else { return } + received += bytes + web.call("write", data, received, termId) + } + + private func onExited(_ term: Int, _ code: Int?) { + guard term == termId else { return } + exitCode = code + termState = .exited + token = nil + } + + private func onFailed(_ term: Int, _ err: TermError) { + guard term == termId else { return } + openTimeout?.cancel() + if err.error == "expired", token != nil { + // 要接回的终端不在了(断开太久、对方重启过):开一个新的 + token = nil + web.call("note", L.t("terminal_expired")) + openTerminal() + return + } + termError = err + termState = .failed + } + + /// 程序退出了 / 开不了之后,开一个新的终端 + func restart() { + token = nil + exitCode = nil + termError = nil + termState = .opening + web.call("reset") + openTerminal() + } + + private func sendResize() { + guard sid >= 0, termState == .open, cols > 0, rows > 0 else { return } + let (id, c, r) = (termId, cols, rows) + command { Commands.terminalResize($0, id, cols: c, rows: r) } + } + + // ── 页面发来的(主线程)── + + private func pageMessage(_ m: JSON) { + switch m.str("t") { + case "ready": + if m.bool("measured") { onSize(m.int("cols") ?? 0, m.int("rows") ?? 0) } + case "data": + if let d = m.str("d"), !d.isEmpty { onData(d) } + case "size": + onSize(m.int("cols") ?? 0, m.int("rows") ?? 0) + case "ack": + let term = m.int("term") ?? 0 + let offset = (m["offset"] as? NSNumber)?.int64Value ?? 0 + guard term == termId, sid >= 0, termState == .open else { return } + command { Commands.terminalAck($0, term, offset) } + case "tap": onGesture?(.tap) + case "longPress": onGesture?(.longPress) + case "bell": onGesture?(.bell) + case "font": + if let s = m.int("size") { fontChanged(s) } + default: break + } + } + + private func onData(_ d: String) { + guard sid >= 0, termState == .open else { return } + let id = termId + var rest = Substring(d) + while !rest.isEmpty { + let part = String(rest.prefix(Self.inputChunk)) + rest = rest.dropFirst(part.count) + command { Commands.terminalInput($0, id, part) } + } + } + + private func onSize(_ c: Int, _ r: Int) { + guard c > 0, r > 0 else { return } + cols = c + rows = r + if redraw, r > 1, sid >= 0, termState == .open { + // 大小变一下(再变回来):程序收到 SIGWINCH 会重画整个屏幕 + redraw = false + let id = termId + command { Commands.terminalResize($0, id, cols: c, rows: r - 1) } + } + sendResize() + } + + private func fontChanged(_ size: Int) { + let s = min(max(size, Self.fontRange.lowerBound), Self.fontRange.upperBound) + fontSize = s + if app?.settings.terminalFont != s { app?.settings.terminalFont = s } + } + + /// 页面的进程没了(系统在后台收回了内存、崩溃了):换一个新的页面,终端照常。之前显示的没了,交给旧页面、 + /// 还没确认的输出也没了:都确认掉(不然对方的窗口满了就不再发),再让终端里的程序重画一遍 + private func pageGone() { + guard !closed else { return } + Log.warn("the terminal page is gone, starting a new one") + let old = web + let w = TerminalWebView(fontSize: fontSize) + wire(w) + web = w + old.release() + w.call("windows", platform == .windows) + w.call("inset", inset) + w.call("note", L.t("terminal_redrawn")) + w.call("begin", termId, received) + if sid >= 0, termState == .open { + let (id, at) = (termId, received) + command { Commands.terminalAck($0, id, at) } + redraw = true + } + } + + // ───────────────────────────── 输入(界面调用,主线程)───────────────────────────── + + /// 快捷键栏 / 外接键盘的特殊键(W3C 的 KeyboardEvent.key,见 client/mobile-terminal/keys.js) + func key(_ name: String, ctrl: Bool = false, alt: Bool = false, shift: Bool = false) { + web.call("key", name, ["ctrl": ctrl, "alt": alt, "shift": shift]) + } + + /// 软键盘 / 外接键盘打的字 + func text(_ s: String, ctrl: Bool = false, alt: Bool = false) { + guard !s.isEmpty else { return } + web.call("text", s, ["ctrl": ctrl, "alt": alt, "shift": false]) + } + + /// 粘贴(太长的截掉:本机和对方之间的队列放不下) + func paste(_ s: String) { + guard !s.isEmpty else { return } + web.call("paste", String(s.prefix(Self.maxPaste))) + } + + func setFont(_ size: Int) { + let s = min(max(size, Self.fontRange.lowerBound), Self.fontRange.upperBound) + web.call("font", s) + fontChanged(s) + } + + /// 软键盘挡住的高度(点,就是页面的 CSS 像素):终端不改大小,页面把光标所在的行挪到键盘上面 + func setInset(_ points: Int) { + guard points != inset else { return } + inset = points + web.call("inset", points) + } + + /// 回到最新的输出 + func scrollToBottom() { web.call("bottom") } + + /// 最近的输出的文字("复制文字") + func copyText(_ done: @escaping (String) -> Void) { web.copyText(Self.copyLines, done) } + + // ───────────────────────────── 其他 ───────────────────────────── + + /// 给当前会话发命令(`make` 拿到会话的 sid)。没连上时丢掉 + private func command(_ make: (UInt32) -> JSON) { + let h = handle + let s = sid + guard h != 0, s >= 0, !closed else { return } + let cmd = make(UInt32(s)) + let r = Native.ctlCall(h, Json.string(cmd)) + if r.contains("\"err\"") { Log.warn("\(cmd.str("cmd") ?? "?") failed: \(r)") } + } + + /// 立即重试(等对方上线时用户点了"重试") + func retryNow() { signal() } + + /// 结束:关掉终端(里面的程序随之结束),再断开。主线程上调用 + func close() { + if closed { return } + let (h, s, id) = (handle, sid, termId) + closed = true + signal() + handlerIds.forEach { client.removeHandler($0) } + openTimeout?.cancel() + if h != 0, s >= 0 { + DispatchQueue.global().async { + _ = Native.ctlCall(h, Json.string(Commands.terminalClose(UInt32(s), id))) + _ = Native.ctlCall(h, Json.string(Commands.disconnect(UInt32(s)))) + } + } + web.release() + if case .failed = phase {} else { phase = .closed } + } +} diff --git a/ios/Airhand/Terminal/TerminalViews.swift b/ios/Airhand/Terminal/TerminalViews.swift new file mode 100644 index 00000000..4b87b8d2 --- /dev/null +++ b/ios/Airhand/Terminal/TerminalViews.swift @@ -0,0 +1,277 @@ +import SwiftUI +import UIKit + +private let barColor = Color(red: 21 / 255, green: 25 / 255, blue: 37 / 255) + +/// 终端上面的标题栏:返回(终端保持打开)、连的是哪台、延迟、菜单 +struct TerminalTopBar: View { + struct Actions { + var back: () -> Void + var copy: () -> Void + var paste: () -> Void + var bottom: () -> Void + var help: () -> Void + var close: () -> Void + } + + let session: TerminalSession + let actions: Actions + + private var dot: Color { + switch session.phase { + case .live: return Theme.good + case .connecting, .reconnecting, .waitingHost: return Theme.warn + default: return Theme.bad + } + } + + private var rtt: (String, Color) { + guard let ms = session.rttMs.map({ Int($0.rounded()) }) else { return ("— ms", Theme.faint) } + return ("\(ms) ms", ms < 60 ? Theme.good : (ms < 150 ? Theme.warn : Theme.bad)) + } + + var body: some View { + HStack(spacing: 8) { + Button(action: actions.back) { + Image(systemName: "chevron.backward").font(.system(size: 18, weight: .semibold)).foregroundStyle(.white) + .frame(width: 44, height: 44).contentShape(Rectangle()) + } + .accessibilityLabel(L.t("terminal_minimize")) + Circle().fill(dot).frame(width: 8, height: 8) + Image(systemName: "terminal").font(.system(size: 14)).foregroundStyle(.white.opacity(0.7)) + Text(session.hostName).font(.headline).foregroundStyle(.white).lineLimit(1) + if session.phase == .live { + Text(rtt.0).font(.caption.monospacedDigit()).foregroundStyle(rtt.1) + } + Spacer(minLength: 8) + Menu { + Button(action: actions.copy) { Label(L.t("terminal_copy"), systemImage: "doc.on.doc") } + Button(action: actions.paste) { Label(L.t("terminal_paste"), systemImage: "doc.on.clipboard") } + Button(action: actions.bottom) { Label(L.t("terminal_bottom"), systemImage: "arrow.down.to.line") } + Section(L.t("terminal_font_size", session.fontSize)) { + Button { session.setFont(session.fontSize + 1) } label: { + Label(L.t("terminal_font_larger"), systemImage: "textformat.size.larger") + } + .disabled(session.fontSize >= TerminalSession.fontRange.upperBound) + Button { session.setFont(session.fontSize - 1) } label: { + Label(L.t("terminal_font_smaller"), systemImage: "textformat.size.smaller") + } + .disabled(session.fontSize <= TerminalSession.fontRange.lowerBound) + } + Button(action: actions.help) { Label(L.t("menu_help"), systemImage: "questionmark.circle") } + Button(role: .destructive, action: actions.close) { Label(L.t("terminal_close"), systemImage: "power") } + } label: { + Image(systemName: "ellipsis.circle").font(.system(size: 20)).foregroundStyle(.white) + .frame(width: 44, height: 44).contentShape(Rectangle()) + } + .accessibilityLabel(L.t("menu_more")) + } + .padding(.horizontal, 4) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(barColor) + .preferredColorScheme(.dark) + } +} + +/// 快捷键栏:终端里常用、软键盘上没有的键(Ctrl / Alt 点一下对下一个键有效,再点锁定);最右边是粘贴和键盘的开关 +struct TerminalKeyBar: View { + let keys: TerminalKeyState + let ui: TerminalUIState + let paste: () -> Void + let toggleKeyboard: () -> Void + + var body: some View { + HStack(spacing: 0) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + key("Esc") { keys.key("Escape") } + key("Tab") { keys.key("Tab") } + // Shift + Tab:反向(claude code 用它切换模式) + key("⇧Tab") { keys.key("Tab", shift: true) } + sticky("Ctrl", keys.ctrl) { keys.toggleCtrl() } + sticky("Alt", keys.alt) { keys.toggleAlt() } + key("←") { keys.key("ArrowLeft") } + key("↑") { keys.key("ArrowUp") } + key("↓") { keys.key("ArrowDown") } + key("→") { keys.key("ArrowRight") } + key("↵") { keys.key("Enter") } + key("^C") { keys.text("c", ctrl: true) } + key("Home") { keys.key("Home") } + key("End") { keys.key("End") } + key("PgUp") { keys.key("PageUp") } + key("PgDn") { keys.key("PageDown") } + ForEach(["~", "|", "/", "-", "`"], id: \.self) { c in + key(c) { keys.text(c) } + } + ForEach(1...12, id: \.self) { i in + key("F\(i)") { keys.key("F\(i)") } + } + } + .padding(.horizontal, 8) + } + Button(action: paste) { + Image(systemName: "doc.on.clipboard").font(.system(size: 17, weight: .semibold)) + .foregroundStyle(.white).frame(width: 44, height: 40) + } + .accessibilityLabel(L.t("terminal_paste")) + Button(action: toggleKeyboard) { + Image(systemName: ui.keyboard ? "keyboard.chevron.compact.down" : "keyboard").font(.system(size: 17, weight: .semibold)) + .foregroundStyle(.white).frame(width: 46, height: 40) + } + .accessibilityLabel(L.t(ui.keyboard ? "hide_keyboard" : "menu_keyboard")) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(barColor) + .preferredColorScheme(.dark) + } + + private func key(_ label: String, _ f: @escaping () -> Void) -> some View { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred(intensity: 0.6) + f() + } label: { + Text(label).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white) + .frame(minWidth: 42, minHeight: 36).padding(.horizontal, 6) + .background(RoundedRectangle(cornerRadius: 9, style: .continuous).fill(Color.white.opacity(0.12))) + } + .buttonStyle(.plain) + } + + private func sticky(_ label: String, _ state: KeyboardState.Sticky, _ f: @escaping () -> Void) -> some View { + Button { + UIImpactFeedbackGenerator(style: .light).impactOccurred() + f() + } label: { + Text(label).font(.system(size: 15, weight: .semibold)).foregroundStyle(.white) + .frame(minWidth: 46, minHeight: 36).padding(.horizontal, 6) + .background( + RoundedRectangle(cornerRadius: 9, style: .continuous) + .fill(state == .off ? Color.white.opacity(0.12) : (state == .locked ? Theme.c2 : Theme.c2.opacity(0.55))) + ) + .overlay(alignment: .bottom) { + if state == .locked { Capsule().fill(.white).frame(width: 14, height: 2).padding(.bottom, 3) } + } + } + .buttonStyle(.plain) + } +} + +/// 终端上面的短提示(已复制、剪贴板是空的……):终端全屏盖着首页,首页的提示看不到 +struct TerminalToast: View { + let app: AppModel + + var body: some View { + VStack { + if let t = app.toast { + Text(t.text).font(.footnote.weight(.medium)).foregroundStyle(.white) + .padding(.horizontal, 14).padding(.vertical, 9) + .background(.ultraThinMaterial, in: Capsule()) + .transition(.opacity) + .task(id: t.id) { + try? await Task.sleep(for: .seconds(2.4)) + if app.toast?.id == t.id { withAnimation { app.toast = nil } } + } + } + } + .animation(.easeInOut(duration: 0.2), value: app.toast) + .preferredColorScheme(.dark) + } +} + +/// 盖在终端上的那一层:正在打开、程序退出了 / 开不了,连接中、断线重连、对方离线、已结束(和远程画面的 SessionOverlay 一样) +struct TerminalOverlay: View { + let session: TerminalSession + let close: () -> Void + + var body: some View { + ZStack { + switch session.phase { + case .live: + switch session.termState { + case .opening: + VStack { + HStack(spacing: 10) { + ProgressView().tint(.white) + Text(L.t("terminal_opening")).font(.subheadline).foregroundStyle(.white) + } + .padding(.horizontal, 14).padding(.vertical, 9) + .background(Color.black.opacity(0.75), in: Capsule()) + .padding(.top, 12) + Spacer() + } + case .exited, .failed: + Color.black.opacity(0.6).ignoresSafeArea() + done + case .open: + Color.clear + } + case .closed: + Color.clear + default: + Color.black.opacity(0.8).ignoresSafeArea() + status + } + } + .preferredColorScheme(.dark) + } + + /// 程序退出了 / 开不了终端:重新打开一个,或者关掉 + private var done: some View { + VStack(spacing: 16) { + let failed = session.termState == .failed + Image(systemName: failed ? "exclamationmark.triangle" : "terminal").font(.system(size: 40)) + .foregroundStyle(failed ? Theme.warn : .white) + Text(failed ? L.t("terminal_failed") + : (session.exitCode.map { L.t("terminal_exited_code", $0) } ?? L.t("terminal_exited"))) + .font(.headline).foregroundStyle(.white).multilineTextAlignment(.center) + if failed, let e = session.termError { + Text(Messages.termError(e.error, detail: e.detail)).font(.subheadline).foregroundStyle(Theme.sub) + .multilineTextAlignment(.center) + } + Button(L.t("terminal_restart")) { session.restart() }.buttonStyle(PrimaryButtonStyle(enabled: true)) + Button(L.t("terminal_close"), action: close).buttonStyle(SecondaryButtonStyle()) + } + .padding(24) + .frame(maxWidth: 380) + .background(Theme.card, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + .padding(24) + } + + @ViewBuilder private var status: some View { + VStack(spacing: 18) { + switch session.phase { + case .connecting: + spinner(L.t("session_connecting", session.hostName)) + Button(L.t("terminal_close"), action: close).buttonStyle(SecondaryButtonStyle()) + case .reconnecting(let p): + spinner(L.t("session_reconnecting")) + Text(Messages.problem(p)).font(.footnote).foregroundStyle(Theme.sub).multilineTextAlignment(.center) + Button(L.t("terminal_close"), action: close).buttonStyle(SecondaryButtonStyle()) + case .waitingHost: + Image(systemName: "icloud.slash").font(.system(size: 44)).foregroundStyle(Theme.sub) + Text(L.t("session_waiting_host", session.hostName)).font(.title3.weight(.semibold)).foregroundStyle(.white) + Text(L.t("session_waiting_host_detail")).font(.subheadline).foregroundStyle(Theme.sub).multilineTextAlignment(.center) + HStack(spacing: 12) { + Button(L.t("retry")) { session.retryNow() }.buttonStyle(SecondaryButtonStyle()) + Button(L.t("terminal_close"), action: close).buttonStyle(SecondaryButtonStyle()) + } + case .ended(let p), .failed(let p): + Image(systemName: "bolt.horizontal.circle").font(.system(size: 48)).foregroundStyle(Theme.sub) + Text(L.t("session_ended")).font(.title3.weight(.semibold)).foregroundStyle(.white) + Text(Messages.problem(p)).font(.subheadline).foregroundStyle(Theme.sub).multilineTextAlignment(.center) + Button(L.t("close"), action: close).buttonStyle(SecondaryButtonStyle()) + case .live, .closed: + EmptyView() + } + } + .padding(32) + .frame(maxWidth: 460) + } + + private func spinner(_ text: String) -> some View { + VStack(spacing: 14) { + ProgressView().controlSize(.large).tint(.white) + Text(text).font(.headline).foregroundStyle(.white).multilineTextAlignment(.center) + } + } +} diff --git a/ios/Airhand/Terminal/TerminalWebView.swift b/ios/Airhand/Terminal/TerminalWebView.swift new file mode 100644 index 00000000..ea7dd746 --- /dev/null +++ b/ios/Airhand/Terminal/TerminalWebView.swift @@ -0,0 +1,127 @@ +import UIKit +import WebKit + +/// 显示远程终端的页面:xterm.js(`client/mobile-terminal/`,构建时和 xterm.js 一起拷进 App 的 terminal 文件夹, +/// 见 scripts/terminal-page.sh),和桌面控制台、Android 是同一个终端。消息的格式见那里的 terminal.js。 +/// +/// 属于 TerminalSession(整个应用一份),界面只是把它放进来、拿走:离开终端界面再回来,显示的内容都还在。 +/// 不拿键盘焦点:键盘在原生那边(TerminalController 的 KeyField),页面里的 xterm 只负责显示和手势。都在主线程上用 +final class TerminalWebView: UIView, WKNavigationDelegate { + /// 页面发来的消息(主线程) + var onMessage: ((JSON) -> Void)? + /// 页面的进程没了(系统在后台收回了内存、崩溃):这个页面不能再用了 + var onGone: (() -> Void)? + + /// 和页面的背景一样(index.html),页面出来之前不闪白 + static let background = UIColor(red: 11 / 255, green: 13 / 255, blue: 20 / 255, alpha: 1) + + private let web: WKWebView + private var ready = false + private var released = false + /// 页面好之前要调用的(按顺序):好了一起执行 + private var pending: [String] = [] + + init(fontSize: Int) { + let config = WKWebViewConfiguration() + config.websiteDataStore = .nonPersistent() + config.dataDetectorTypes = [] + let content = WKUserContentController() + config.userContentController = content + web = WKWebView(frame: .zero, configuration: config) + super.init(frame: .zero) + content.add(WeakMessageHandler(self), name: "airhand") + backgroundColor = Self.background + web.isOpaque = false + web.backgroundColor = Self.background + web.scrollView.backgroundColor = Self.background + // 手势都由页面里的 terminal.js 处理:网页自己不滚动、不缩放 + web.scrollView.isScrollEnabled = false + web.scrollView.bounces = false + web.scrollView.contentInsetAdjustmentBehavior = .never + web.scrollView.pinchGestureRecognizer?.isEnabled = false + web.navigationDelegate = self + #if DEBUG + // 调试版可以用 Mac 上的 Safari(开发 → 设备)看页面 + web.isInspectable = true + #endif + web.frame = bounds + web.autoresizingMask = [.flexibleWidth, .flexibleHeight] + addSubview(web) + load(fontSize: fontSize) + } + + required init?(coder: NSCoder) { fatalError() } + + private func load(fontSize: Int) { + guard let index = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "terminal") else { + Log.warn("the terminal page isn't in the app bundle (scripts/terminal-page.sh)") + return + } + var c = URLComponents(url: index, resolvingAgainstBaseURL: false) + c?.queryItems = [URLQueryItem(name: "font", value: String(fontSize))] + web.loadFileURL(c?.url ?? index, allowingReadAccessTo: index.deletingLastPathComponent()) + } + + /// 页面发来的消息(WKScriptMessageHandler,主线程) + fileprivate func received(_ body: Any) { + guard !released, let s = body as? String, let m = Json.parse(s) else { return } + if m.str("t") == "ready" { + ready = true + let scripts = pending + pending.removeAll() + for script in scripts { web.evaluateJavaScript(script, completionHandler: nil) } + } + onMessage?(m) + } + + /// 调用页面里的 `airhand.(args…)`(参数按 JSON 传过去)。页面还没好时先记下来 + func call(_ fn: String, _ args: Any...) { + guard !released else { return } + let script = "airhand.\(fn).apply(null, \(Json.string(args)))" + if ready { + web.evaluateJavaScript(script, completionHandler: nil) + } else { + pending.append(script) + } + } + + /// 最近 `max` 行的文字("复制文字")。页面还没好时是空的 + func copyText(_ max: Int, _ done: @escaping (String) -> Void) { + guard ready, !released else { + done("") + return + } + web.evaluateJavaScript("airhand.copyText(\(max))") { r, _ in done((r as? String) ?? "") } + } + + func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + Log.warn("the terminal page's web content process terminated") + guard !released else { return } + ready = false + onGone?() + } + + /// 会话结束了(或者换了一个新的页面):这个页面不要了 + func release() { + guard !released else { return } + released = true + pending.removeAll() + onMessage = nil + onGone = nil + web.configuration.userContentController.removeScriptMessageHandler(forName: "airhand") + web.navigationDelegate = nil + web.stopLoading() + removeFromSuperview() + } +} + +/// WKUserContentController 强引用消息的接收者:经过它弱引用页面,不然页面一直释放不了 +private final class WeakMessageHandler: NSObject, WKScriptMessageHandler { + weak var target: TerminalWebView? + + init(_ target: TerminalWebView) { self.target = target } + + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + target?.received(message.body) + } +} diff --git a/ios/Airhand/UI/ConnectView.swift b/ios/Airhand/UI/ConnectView.swift index bc6bd497..5af727d2 100644 --- a/ios/Airhand/UI/ConnectView.swift +++ b/ios/Airhand/UI/ConnectView.swift @@ -9,6 +9,9 @@ struct ConnectView: View { @State private var renaming: SavedDevice? @State private var newName = "" @State private var deleting: SavedDevice? + /// 开着一个终端又要在别的电脑上开:先问一下(同一时间一个,原来的里面的程序会结束) + @State private var replacing: String? + @State private var closingTerminal = false var body: some View { NavigationStack { @@ -21,6 +24,9 @@ struct ConnectView: View { if let s = app.session, s.phase == .live, !app.showingSession { liveCard(s) } + if let t = app.terminal, Self.showsCard(t.phase), !app.showingTerminal { + terminalCard(t) + } codeCard devices } @@ -47,6 +53,25 @@ struct ConnectView: View { } message: { d in Text(L.t("device_delete_text", d.title)) } + .confirmationDialog(L.t("terminal_replace_title"), isPresented: Binding(get: { replacing != nil }, set: { if !$0 { replacing = nil } }), + titleVisibility: .visible, presenting: replacing) { c in + Button(L.t("terminal_close"), role: .destructive) { app.openTerminal(code: c) } + } message: { _ in + Text(L.t("terminal_replace_text", app.terminal?.hostName ?? "")) + } + .confirmationDialog(L.t("terminal_close_title"), isPresented: $closingTerminal, titleVisibility: .visible) { + Button(L.t("terminal_close"), role: .destructive) { app.closeTerminal() } + } message: { + Text(L.t("terminal_close_text", app.terminal?.hostName ?? "")) + } + } + + /// 终端还开着(连着或者在重连):首页上显示它的卡片,点一下回去 + private static func showsCard(_ p: RemoteSession.Phase) -> Bool { + switch p { + case .live, .reconnecting: return true + default: return false + } } private var background: some View { @@ -98,9 +123,33 @@ struct ConnectView: View { .buttonStyle(.plain) } + /// 终端还开着:点一下回到终端,右边的 × 关掉它(先问一下) + private func terminalCard(_ t: TerminalSession) -> some View { + Button { app.showingTerminal = true } label: { + HStack(spacing: 12) { + Image(systemName: "terminal").font(.title2).foregroundStyle(.white).frame(width: 40, height: 40) + VStack(alignment: .leading, spacing: 2) { + Text(t.hostName).font(.headline).foregroundStyle(.white) + Text(L.t("terminal_live_card")).font(.caption).foregroundStyle(.white.opacity(0.8)) + } + Spacer() + Button { closingTerminal = true } label: { + Image(systemName: "xmark.circle.fill").font(.title3).foregroundStyle(.white.opacity(0.85)) + .frame(width: 40, height: 40).contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(L.t("terminal_close")) + } + .padding(14) + .background(Theme.gradient, in: RoundedRectangle(cornerRadius: 18, style: .continuous)) + } + .buttonStyle(.plain) + } + // ── 控制码 ── private var connecting: Bool { app.connectingCode != nil && app.connectingCode == Code.parse(digits) } + private var connectingTerminal: Bool { app.connectingTerminalCode != nil && app.connectingTerminalCode == Code.parse(digits) } private var codeCard: some View { Card(padding: 20) { @@ -137,22 +186,44 @@ struct ConnectView: View { .labelStyle(.titleAndIcon) .buttonBorderShape(.roundedRectangle(radius: 12)) .tint(Theme.cardHi) + Spacer() + } + // 终端(不传画面)和连接(远程画面),和桌面控制台一样并排。输满控制码时用的是最近一次点的那种(实心的) + HStack(spacing: 10) { + let ready = Code.parse(digits) != nil + let preferTerminal = app.settings.preferTerminal + Button { + if connectingTerminal { app.closeTerminal() } else { choose(terminal: true) } + } label: { + HStack(spacing: 8) { + if connectingTerminal { ProgressView().tint(preferTerminal ? .white : Theme.c3) } else { Image(systemName: "terminal") } + Text(L.t("terminal")) + } + } + .buttonStyle(ModeButtonStyle(primary: preferTerminal, enabled: ready)) Button { - if connecting { app.closeSession() } else { submit() } + if connecting { app.closeSession() } else { choose(terminal: false) } } label: { HStack(spacing: 8) { - if connecting { ProgressView().tint(.white) } + if connecting { ProgressView().tint(preferTerminal ? Theme.c3 : .white) } Text(connecting ? L.t("connecting") : L.t("connect")) } } - .buttonStyle(PrimaryButtonStyle(enabled: Code.parse(digits) != nil)) - .disabled(Code.parse(digits) == nil) + .buttonStyle(ModeButtonStyle(primary: !preferTerminal, enabled: ready)) } + Text(L.t("terminal_connect_hint")).font(.footnote).foregroundStyle(Theme.sub) + .fixedSize(horizontal: false, vertical: true) } } .animation(.easeInOut(duration: 0.2), value: app.connectError) } + /// 点了“终端” / “连接”:记住这种连法;控制码输满了就连,没输满就回到输入框(输满时按这种连法连) + private func choose(terminal: Bool) { + if app.settings.preferTerminal != terminal { app.settings.preferTerminal = terminal } + if Code.parse(digits) != nil { submit() } else { focused = true } + } + private func onDigits(_ v: String) { let clean = String(v.filter { $0.isASCII && $0.isNumber }.prefix(6)) if clean != v { digits = clean; return } @@ -167,7 +238,16 @@ struct ConnectView: View { } focused = false UIImpactFeedbackGenerator(style: .light).impactOccurred() - app.connect(code: code) + if app.settings.preferTerminal { openTerminal(code) } else { app.connect(code: code) } + } + + /// 在这台电脑上开远程终端。开着别的电脑的终端时先问一下([replacing]) + private func openTerminal(_ code: String) { + if let t = app.terminal, t.code != code, Self.showsCard(t.phase) { + replacing = code + return + } + app.openTerminal(code: code) } // ── 我的设备 ── @@ -184,8 +264,9 @@ struct ConnectView: View { } } else { ForEach(app.devices.list) { d in - DeviceRow(app: app, device: d) + DeviceRow(app: app, device: d, openTerminal: { openTerminal($0) }) .contextMenu { + Button { openTerminal(d.code) } label: { Label(L.t("terminal_open"), systemImage: "terminal") } Button { newName = d.title; renaming = d } label: { Label(L.t("rename"), systemImage: "pencil") } Button { UIPasteboard.general.string = Code.format(d.code) @@ -200,6 +281,7 @@ struct ConnectView: View { private func delete(_ d: SavedDevice) { if app.session?.code == d.code { app.closeSession() } + if app.terminal?.code == d.code { app.closeTerminal() } app.devices.remove(d.code) app.show(L.t("device_deleted", d.title), action: L.t("undo")) { app.devices.restore(d) } } @@ -256,19 +338,46 @@ struct ServerPill: View { } } -/// “我的设备”里的一行 +/// 首页的“终端” / “连接”:输满控制码时用的那种是实心的(渐变),另一种是描边的 +private struct ModeButtonStyle: ButtonStyle { + var primary: Bool + var enabled: Bool + + func makeBody(configuration: Configuration) -> some View { + let shape = RoundedRectangle(cornerRadius: 16, style: .continuous) + return configuration.label + .font(.headline) + .foregroundStyle(primary ? Color.white : Theme.text) + .frame(maxWidth: .infinity, minHeight: 52) + .background(Theme.gradient.opacity(primary ? (enabled ? 1 : 0.35) : 0), in: shape) + .background(Theme.cardHi, in: shape) + .overlay(shape.stroke(Theme.c2.opacity(primary ? 0 : 0.6))) + .opacity(!primary && !enabled ? 0.6 : 1) + .scaleEffect(configuration.isPressed ? 0.98 : 1) + .animation(.spring(duration: 0.2), value: configuration.isPressed) + } +} + +/// “我的设备”里的一行:点一下连远程画面,右边的终端图标只开终端(不传画面) struct DeviceRow: View { let app: AppModel let device: SavedDevice + var openTerminal: (String) -> Void = { _ in } private var session: RemoteSession? { app.session?.code == device.code ? app.session : nil } + private var terminal: TerminalSession? { app.terminal?.code == device.code ? app.terminal : nil } + + private var terminalWaiting: Bool { + if case .waitingHost = terminal?.phase { return true } + return false + } private var waiting: Bool { if case .waitingHost = session?.phase { return true } - return false + return terminalWaiting } - private var connecting: Bool { app.connectingCode == device.code } + private var connecting: Bool { app.connectingCode == device.code || app.connectingTerminalCode == device.code } var body: some View { Button { @@ -291,8 +400,17 @@ struct DeviceRow: View { if connecting { ProgressView().tint(Theme.c3) } else if waiting { - Button(L.t("cancel")) { app.closeSession() }.buttonStyle(SecondaryButtonStyle(tint: Theme.sub)) + Button(L.t("cancel")) { + if terminalWaiting { app.closeTerminal() } else { app.closeSession() } + } + .buttonStyle(SecondaryButtonStyle(tint: Theme.sub)) } else { + Button { openTerminal(device.code) } label: { + Image(systemName: "terminal").font(.body.weight(.semibold)).foregroundStyle(Theme.c3) + .frame(width: 40, height: 40).contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(L.t("terminal_open")) Image(systemName: "chevron.right").font(.footnote.weight(.semibold)).foregroundStyle(Theme.faint) } } @@ -347,6 +465,10 @@ struct PairingSheet: View { private func submit() { guard code.count == 6 else { return } dismiss() - app.connect(code: request.code, pairing: code) + if request.terminal { + app.openTerminal(code: request.code, pairing: code) + } else { + app.connect(code: request.code, pairing: code) + } } } diff --git a/ios/Airhand/UI/SettingsView.swift b/ios/Airhand/UI/SettingsView.swift index bf5e1909..774b48d9 100644 --- a/ios/Airhand/UI/SettingsView.swift +++ b/ios/Airhand/UI/SettingsView.swift @@ -173,6 +173,7 @@ struct SettingsView: View { .confirmationDialog(L.t("clear_devices"), isPresented: $confirmClear, titleVisibility: .visible) { Button(L.t("delete"), role: .destructive) { app.closeSession() + app.closeTerminal() app.devices.clear() } } message: { Text(L.t("clear_devices_confirm")) } @@ -234,6 +235,7 @@ struct SettingsView: View { s.deviceName = name.trimmingCharacters(in: .whitespaces) app.settings = s app.closeSession() + app.closeTerminal() app.controller.restart() UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } diff --git a/ios/Shared/L10n.swift b/ios/Shared/L10n.swift index e788f96a..56b1de29 100644 --- a/ios/Shared/L10n.swift +++ b/ios/Shared/L10n.swift @@ -212,7 +212,27 @@ enum L { "problem_pairing_unavailable": "对方暂停了配对(有人多次输错配对码):请对方换一个配对码", "problem_peer_incompatible_update_app": "与对方设备的版本不兼容:对方较新,请更新这台设备上的 Airhand", "problem_peer_incompatible_update_peer": "与对方设备的版本不兼容:对方较旧,请对方更新 Airhand", - "problem_terminal_unavailable": "对方没有开启远程终端(请对方在 Airhand 的托盘菜单里勾选“允许远程终端”)", + "problem_terminal_unavailable": "对方没有开启远程终端(请对方在 Airhand 的托盘菜单里勾选“允许远程终端”),或者那台设备(手机)不支持", + // 远程终端(不传画面,见 Terminal/) + "terminal": "终端", "terminal_open": "打开终端(不传画面)", + "terminal_connect_hint": "终端:不传画面,在对方电脑上运行命令行程序(claude、codex、pi……)", + "terminal_live_card": "终端 · 点按回到终端", "terminal_opening": "正在打开终端…", + "terminal_exited": "终端里的程序已退出", "terminal_exited_code": "终端里的程序已退出(退出码 %d)", + "terminal_failed": "打不开终端", "terminal_restart": "重新打开终端", + "terminal_gap": "……断开期间的输出太多,有一段没有留住……", "terminal_new_shell": "(原来的终端已经不在了,这是一个新的终端)", + "terminal_expired": "原来的终端已经不在了(断开太久,或者对方重启过),正在打开一个新的……", + "terminal_redrawn": "(显示重新开始了,之前的输出不再显示)", + "terminal_font_smaller": "缩小字号", "terminal_font_larger": "放大字号", "terminal_font_size": "字号 %d", + "terminal_copy": "复制文字", "terminal_copy_hint": "选中要复制的部分,或者全部复制", "terminal_copy_all": "全部复制", + "terminal_copy_empty": "还没有可以复制的文字", "terminal_paste": "粘贴", "terminal_bottom": "回到最新的输出", + "terminal_minimize": "返回(终端保持打开)", "terminal_close": "关闭终端", "terminal_close_title": "关闭终端?", + "terminal_close_text": "“%@”上终端里正在运行的程序会随之结束。", "terminal_replace_title": "关闭现在的终端?", + "terminal_replace_text": "同一时间只能开一个终端。“%@”上终端里正在运行的程序会随之结束。", + "terminal_help": "上下滑动看前面的输出,双指捏合改字号,长按复制文字。快捷键栏上的 Ctrl、Alt 对下一个键有效(点两下锁定)。断线后自动重连,终端里的程序照常运行,重连后接着显示", + "terminal_error_unavailable": "对方开不了终端(%@)", + "terminal_error_no_user": "对方电脑上没有登录的用户(停在登录界面):终端要以登录的用户的身份运行", + "terminal_error_too_many": "对方开的终端太多了,先关掉几个", "terminal_error_expired": "要接回的终端已经不在了", + "terminal_error_spawn_failed": "启动 shell 失败:%@", "problem_host_ended": "对方结束了会话", "problem_host_unresponsive": "对方无响应", "problem_kicked": "对方断开了你的连接", "problem_code_changed": "对方更换了控制码", "problem_session_ended": "会话已结束", "problem_no_session": "会话不存在", "problem_failed": "出错了:%@", @@ -406,7 +426,27 @@ enum L { "problem_pairing_unavailable": "Pairing is paused on the remote (too many wrong codes): ask them to get a new pairing code", "problem_peer_incompatible_update_app": "Incompatible with the remote: it's newer, please update Airhand here", "problem_peer_incompatible_update_peer": "Incompatible with the remote: it's older, ask them to update Airhand", - "problem_terminal_unavailable": "The remote doesn't offer a remote terminal (its user can turn on “Allow remote terminal” in the Airhand tray menu)", + "problem_terminal_unavailable": "The remote doesn't offer a remote terminal (its user can turn on “Allow remote terminal” in the Airhand tray menu), or it can't (phones)", + // Remote terminal (no screen, see Terminal/) + "terminal": "Terminal", "terminal_open": "Open a terminal (no screen)", + "terminal_connect_hint": "Terminal: run command-line programs (claude, codex, pi…) on the computer without streaming its screen", + "terminal_live_card": "Terminal · tap to return", "terminal_opening": "Opening the terminal…", + "terminal_exited": "The program in the terminal exited", "terminal_exited_code": "The program in the terminal exited (exit code %d)", + "terminal_failed": "Can't open the terminal", "terminal_restart": "Open the terminal again", + "terminal_gap": "… some output while disconnected was too much to keep …", "terminal_new_shell": "(The previous terminal is gone, this is a new one)", + "terminal_expired": "The previous terminal is gone (disconnected for too long, or the remote computer restarted), opening a new one…", + "terminal_redrawn": "(The display restarted, earlier output isn't shown)", + "terminal_font_smaller": "Smaller text", "terminal_font_larger": "Larger text", "terminal_font_size": "Text size %d", + "terminal_copy": "Copy text", "terminal_copy_hint": "Select the part you want, or copy it all", "terminal_copy_all": "Copy all", + "terminal_copy_empty": "Nothing to copy yet", "terminal_paste": "Paste", "terminal_bottom": "Jump to the latest output", + "terminal_minimize": "Back (the terminal stays open)", "terminal_close": "Close terminal", "terminal_close_title": "Close the terminal?", + "terminal_close_text": "Programs running in the terminal on “%@” will end.", "terminal_replace_title": "Close the open terminal?", + "terminal_replace_text": "Only one terminal can be open at a time. Programs running in the terminal on “%@” will end.", + "terminal_help": "Swipe to scroll back, pinch to change the text size, long-press to copy text. Ctrl and Alt on the key bar apply to the next key (tap twice to lock). If the connection drops it reconnects by itself: the programs keep running and the output catches up", + "terminal_error_unavailable": "The remote computer can't open a terminal (%@)", + "terminal_error_no_user": "Nobody is signed in on the remote computer (it's at the sign-in screen): the terminal runs as the signed-in user", + "terminal_error_too_many": "Too many terminals are open on the remote computer, close some first", "terminal_error_expired": "The terminal to resume is gone", + "terminal_error_spawn_failed": "Couldn't start the shell: %@", "problem_host_ended": "The remote ended the session", "problem_host_unresponsive": "The remote isn't responding", "problem_kicked": "The remote disconnected you", "problem_code_changed": "The remote changed its control code", "problem_session_ended": "The session ended", "problem_no_session": "No such session", "problem_failed": "Something went wrong: %@", @@ -415,6 +455,17 @@ enum L { /// 问题、提示的文字(与 Android 的 Messages.kt 相同的规则) enum Messages { + /// 远程终端开不了的原因(Rust 的 `TermError`,不认识的当作 unavailable) + static func termError(_ error: String, detail: String?) -> String { + switch error { + case "noUser": return L.t("terminal_error_no_user") + case "tooMany": return L.t("terminal_error_too_many") + case "expired": return L.t("terminal_error_expired") + case "spawnFailed": return L.t("terminal_error_spawn_failed", detail ?? "—") + default: return L.t("terminal_error_unavailable", detail ?? "—") + } + } + static func problem(_ p: Problem) -> String { let d = p.detail ?? "" switch p.kind { diff --git a/ios/Shared/SharedStore.swift b/ios/Shared/SharedStore.swift index 88b8faa9..b4db4937 100644 --- a/ios/Shared/SharedStore.swift +++ b/ios/Shared/SharedStore.swift @@ -80,6 +80,10 @@ struct AppSettings: Codable, Equatable { var updateChannel: String = "stable" /// 回到 Airhand 时自动检查更新(最多 6 小时一次) var checkUpdates: Bool = true + /// 远程终端的字号(终端页面的 CSS 像素,8...28):双指缩放、菜单里改,所有终端共用 + var terminalFont: Int = 13 + /// 首页输满控制码时开终端而不是远程画面:跟着最近一次点的是“终端”还是“连接” + var preferTerminal: Bool = false init() {} @@ -102,6 +106,8 @@ struct AppSettings: Codable, Equatable { tipsShown = (try? c.decode(Bool.self, forKey: .tipsShown)) ?? d.tipsShown updateChannel = (try? c.decode(String.self, forKey: .updateChannel)).flatMap { ["stable", "prerelease"].contains($0) ? $0 : nil } ?? d.updateChannel checkUpdates = (try? c.decode(Bool.self, forKey: .checkUpdates)) ?? d.checkUpdates + terminalFont = (try? c.decode(Int.self, forKey: .terminalFont)).flatMap { (8...28).contains($0) ? $0 : nil } ?? d.terminalFont + preferTerminal = (try? c.decode(Bool.self, forKey: .preferTerminal)) ?? d.preferTerminal } static func load() -> AppSettings { SharedStore.read(SharedStore.settingsFile, as: AppSettings.self) ?? AppSettings() } diff --git a/ios/Tests/ProtocolTests.swift b/ios/Tests/ProtocolTests.swift index 783d1b55..28e7ebe3 100644 --- a/ios/Tests/ProtocolTests.swift +++ b/ios/Tests/ProtocolTests.swift @@ -100,6 +100,24 @@ final class ProtocolTests: XCTestCase { XCTAssertTrue(same(Commands.mic(3, true), find("mic"))) XCTAssertTrue(same(Commands.clipboard(3, "hi"), find("clipboard"))) XCTAssertTrue(same(Commands.privacy(3, true), find("privacy"))) + // 远程终端(TerminalSession) + XCTAssertTrue(same(Commands.terminalOpen(3, 1, cols: 120, rows: 40, resume: (token: String(repeating: "0f", count: 16), offset: 4096)), + find("terminalOpen"))) + XCTAssertTrue(same(Commands.terminalInput(3, 1, "ls\r"), find("terminalInput"))) + XCTAssertTrue(same(Commands.terminalResize(3, 1, cols: 80, rows: 24), find("terminalResize"))) + XCTAssertTrue(same(Commands.terminalAck(3, 1, 8192), find("terminalAck"))) + XCTAssertTrue(same(Commands.terminalClose(3, 1), find("terminalClose"))) + // 新开的终端:resume 是 null + XCTAssertTrue(Commands.terminalOpen(3, 2, cols: 80, rows: 24, resume: nil)["resume"] is NSNull) + } + + /// 终端会话:连接选项里带着 terminal(ConnectOptions::terminal),不带时是普通的远程画面 + func testTerminalConnectOption() { + let q = Quality(fps: 30, kbps: 4000, maxShort: 1080, adaptive: true, codec: .h264) + let t = Commands.connect(code: "123456", resume: nil, settings: q, hostKey: nil, pairing: nil, audio: false, terminal: true) + XCTAssertEqual(t["terminal"] as? Bool, true) + let d = Commands.connect(code: "123456", resume: nil, settings: q, hostKey: nil, pairing: nil, audio: false) + XCTAssertNil(d["terminal"]) } /// 会话事件 `gamepad` 的状态(Rust 的 `GamepadSupport`);不认识的当作不支持。手柄的状态换算、合并和控制台一样 diff --git a/ios/project.yml b/ios/project.yml index b78f2573..3b838237 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -43,6 +43,11 @@ targets: - name: Rust core script: '"$PROJECT_DIR/scripts/build-rust.sh" "$PLATFORM_NAME" release' basedOnDependencyAnalysis: false + # 远程终端的页面(client/mobile-terminal 加上 client/node_modules 里的 xterm.js)拷进 App 的 terminal 文件夹 + postCompileScripts: + - name: Terminal page + script: 'bash "$PROJECT_DIR/scripts/terminal-page.sh"' + basedOnDependencyAnalysis: false dependencies: - target: AirhandBroadcast embed: true diff --git a/ios/scripts/terminal-page.sh b/ios/scripts/terminal-page.sh new file mode 100644 index 00000000..b7e72403 --- /dev/null +++ b/ios/scripts/terminal-page.sh @@ -0,0 +1,28 @@ +#!/bin/bash +# 远程终端的页面(client/mobile-terminal)加上 xterm.js(从 client/node_modules 拷,和桌面控制台同一个版本), +# 拷进 App 的 terminal 文件夹(Airhand/Terminal/TerminalWebView.swift 从那里打开)。 +# +# Xcode 的构建阶段调用(project.yml 的 postCompileScripts),也可以手动运行:terminal-page.sh <输出目录>。 +# 先在 client 里 npm ci(或者 npm install)。 +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +CLIENT="$HERE/../client" +XTERM="$CLIENT/node_modules/@xterm" +OUT="${1:-${TARGET_BUILD_DIR:?}/${UNLOCALIZED_RESOURCES_FOLDER_PATH:?}/terminal}" + +for f in "$XTERM/xterm/lib/xterm.js" "$XTERM/xterm/css/xterm.css" "$XTERM/addon-unicode11/lib/addon-unicode11.js"; do + if [ ! -f "$f" ]; then + echo "error: the remote terminal page needs xterm.js from client/node_modules: run \`npm ci\` in client/ first (missing $f)" >&2 + exit 1 + fi +done + +rm -rf "$OUT" +mkdir -p "$OUT" +cp "$CLIENT/mobile-terminal/"*.html "$CLIENT/mobile-terminal/"*.js "$OUT/" +cp "$XTERM/xterm/css/xterm.css" "$OUT/" +# 没有拷 .map:去掉指向它的注释 +for f in "$XTERM/xterm/lib/xterm.js" "$XTERM/addon-unicode11/lib/addon-unicode11.js"; do + sed '/^\/\/# sourceMappingURL=/d' "$f" > "$OUT/$(basename "$f")" +done