| 1 | import Foundation |
| 2 | import SwiftUI |
| 3 | import VisionKit |
| 4 | import AVFoundation |
| 5 | import UniformTypeIdentifiers |
| 6 | import WebKit |
| 7 | private var simulatorPreviewEnabled: Bool { |
| 8 | #if targetEnvironment(simulator) |
| 9 | return true |
| 10 | #else |
| 11 | return false |
| 12 | #endif |
| 13 | } |
| 14 | |
| 15 | struct ConnectedDevice: Identifiable { |
| 16 | let id: String |
| 17 | var name: String |
| 18 | let connection: CMConnection? |
| 19 | let webView: WKWebView |
| 20 | } |
| 21 | |
| 22 | final class DeviceWebBridge: NSObject, WKScriptMessageHandler { |
| 23 | weak var model: ConnectionModel? |
| 24 | let id: String |
| 25 | let origin: URL |
| 26 | init(model: ConnectionModel, id: String, origin: URL) {self.model = model; self.id = id; self.origin = origin} |
| 27 | func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { |
| 28 | guard let model, model.devices.contains(where: {$0.id == id && $0.webView === message.webView}), |
| 29 | message.frameInfo.isMainFrame, let url = message.frameInfo.request.url, |
| 30 | url.scheme == origin.scheme, url.host == origin.host, url.port == origin.port, |
| 31 | let body = message.body as? [String: Any], let action = body["action"] as? String else {return} |
| 32 | if action == "name" { |
| 33 | if let name = body["name"] as? String {model.nameDevice(id, name)} |
| 34 | return |
| 35 | } |
| 36 | guard model.showingWorkspace, model.selectedDeviceID == id else {return} |
| 37 | if action == "home" {model.leaveWorkspace()} |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | final class ConnectionModel: ObservableObject { |
| 42 | |
| 43 | @Published var relay = CMConnection.defaultRelay() |
| 44 | @Published var pin = "" |
| 45 | @Published var fingerprint = "" |
| 46 | @Published var verified = false |
| 47 | @Published var hasInvitation = false |
| 48 | @Published var hasSaved = false |
| 49 | @Published var needsTrust = false |
| 50 | @Published var status = "" |
| 51 | @Published var connecting = false |
| 52 | @Published var session: CMConnection? |
| 53 | @Published var devices: [ConnectedDevice] = [] |
| 54 | @Published var selectedDeviceID: String? |
| 55 | @Published var showingWorkspace = false |
| 56 | var selectedDevice: ConnectedDevice? {devices.first {$0.id == selectedDeviceID}} |
| 57 | |
| 58 | private var invitation: Invitation? |
| 59 | private var imported: HostAccess? |
| 60 | private var trusted: Host? |
| 61 | private var generation = 0 |
| 62 | private var openArchivedAfterConnect = false |
| 63 | private let trustKey = "independently-verified-host-v1" |
| 64 | private let linkQueue = DispatchQueue(label: "CageMobile.connection") |
| 65 | var canForget: Bool { trusted != nil } |
| 66 | var canConnect: Bool { !connecting && !needsTrust && !fingerprint.isEmpty && (hasInvitation || hasSaved) } |
| 67 | |
| 68 | init() { |
| 69 | if let data = UserDefaults.standard.data(forKey: trustKey), let host = try? JSONDecoder().decode(Host.self, from: data) { |
| 70 | trusted = host; relay = host.relay; pin = host.pin |
| 71 | } |
| 72 | do { |
| 73 | if let saved = try HostKeychain.read() { |
| 74 | trusted = saved.host; relay = saved.host.relay; pin = saved.host.pin; hasSaved = true |
| 75 | } |
| 76 | } catch { |
| 77 | status = "无法读取已保存的连接,请解锁手机后重新打开。" |
| 78 | } |
| 79 | if let selected = UserDefaults.standard.string(forKey:"preferred-relay") {relay = selected} |
| 80 | DispatchQueue.global(qos: .userInitiated).async { |
| 81 | do { |
| 82 | let value = try CMConnection.deviceFingerprint() |
| 83 | DispatchQueue.main.async { self.fingerprint = value } |
| 84 | } catch { |
| 85 | DispatchQueue.main.async { self.status = error.localizedDescription } |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | func pair(code: String) { |
| 90 | guard !connecting else {return} |
| 91 | connecting = true; generation += 1 |
| 92 | let attempt = generation |
| 93 | let address = UserDefaults.standard.string(forKey: "preferred-relay") ?? trusted?.relay ?? CMConnection.defaultRelay() |
| 94 | status = "正在与电脑配对…" |
| 95 | linkQueue.async { |
| 96 | let result = Result { () throws -> HostAccess in |
| 97 | let data = Data(try CMConnection.pair(code: code, relay: address).utf8) |
| 98 | guard case .persistent(let access) = try ConnectionFile.parse(data) else {throw InputError.invalid} |
| 99 | return access |
| 100 | } |
| 101 | DispatchQueue.main.async { |
| 102 | guard attempt == self.generation else {return} |
| 103 | self.connecting = false |
| 104 | do { |
| 105 | let saved = try result.get() |
| 106 | try HostKeychain.write(saved) |
| 107 | UserDefaults.standard.set(saved.host.relay,forKey:"preferred-relay") |
| 108 | self.trusted = saved.host; self.pin = saved.host.pin; self.relay = saved.host.relay |
| 109 | self.imported = nil; self.invitation = nil; self.hasInvitation = false |
| 110 | self.hasSaved = true; self.needsTrust = false; self.verified = false |
| 111 | self.connect() |
| 112 | } catch { self.status = error.localizedDescription } |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | func saveRelay() { |
| 117 | let input = relay.trimmingCharacters(in: .whitespacesAndNewlines) |
| 118 | guard let u = URLComponents(string: input), u.scheme?.lowercased() == "https", |
| 119 | let host=u.host, !host.isEmpty, u.user==nil, u.password==nil, u.query==nil, u.fragment==nil, |
| 120 | (u.path=="" || u.path=="/"), (1...65535).contains(u.port ?? 443) else {status="请填写有效的 HTTPS 地址。";return} |
| 121 | relay=input.hasSuffix("/") ? String(input.dropLast()) : input |
| 122 | UserDefaults.standard.set(relay,forKey:"preferred-relay") |
| 123 | status="中继设置已保存。" |
| 124 | } |
| 125 | func saveTrust() { |
| 126 | guard verified, let host = try? Host(relay: relay, pin: pin), let data = try? JSONEncoder().encode(host) else { |
| 127 | status = "请填写有效的中继地址,核对电脑指纹后再保存。"; return |
| 128 | } |
| 129 | do { |
| 130 | if let record = imported { |
| 131 | guard record.host == host else { status = "填写内容与连接文件不一致,请重新核对。"; return } |
| 132 | try HostKeychain.write(record) |
| 133 | hasSaved = true |
| 134 | } else if trusted != host { |
| 135 | hasSaved = try HostKeychain.read(host: host) != nil |
| 136 | } |
| 137 | } catch { status = "无法安全保存主机,请解锁手机后重试。"; return } |
| 138 | trusted = host; UserDefaults.standard.set(host.relay,forKey:"preferred-relay"); UserDefaults.standard.set(data, forKey: trustKey); verified = false |
| 139 | imported = nil; needsTrust = false |
| 140 | status = hasSaved ? "已保存这台电脑,可以重新连接。" : "已保存主机指纹。" |
| 141 | } |
| 142 | func loadInvitation(_ file: URL) { |
| 143 | invitation = nil; imported = nil; needsTrust = false; hasInvitation = false; verified = false |
| 144 | do { |
| 145 | switch try ConnectionFile.load(file) { |
| 146 | case .temporary(let room): |
| 147 | invitation = room; hasInvitation = true; status = "已导入本次临时邀请。" |
| 148 | case .persistent(let saved): |
| 149 | imported = saved; needsTrust = true; relay = saved.host.relay; pin = saved.host.pin |
| 150 | status = "请与电脑上独立显示的指纹核对,再保存这台主机。" |
| 151 | } |
| 152 | } catch { status = "文件无效或临时邀请已过期,请重新导入。" } |
| 153 | } |
| 154 | func forget() { |
| 155 | do { try HostKeychain.forget(host: trusted) } catch { status = "移除未完成,请解锁手机后重试。"; return } |
| 156 | UserDefaults.standard.removeObject(forKey: trustKey) |
| 157 | trusted = nil; imported = nil; invitation = nil; relay = UserDefaults.standard.string(forKey:"preferred-relay") ?? CMConnection.defaultRelay(); pin = "" |
| 158 | hasSaved = false; needsTrust = false; verified = false; hasInvitation = false |
| 159 | status = "已忘记主机。" |
| 160 | } |
| 161 | func connect() { |
| 162 | connect(openArchived: false) |
| 163 | } |
| 164 | private func connect(openArchived: Bool) { |
| 165 | guard !connecting, !needsTrust, let host = trusted else { |
| 166 | status = "请先核对并保存这台主机。"; return |
| 167 | } |
| 168 | openArchivedAfterConnect = openArchived |
| 169 | if let existing = devices.first(where: {$0.id == host.relay + "|" + host.pin}) { |
| 170 | selectDevice(existing.id) |
| 171 | if openArchivedAfterConnect { |
| 172 | openArchivedAfterConnect = false |
| 173 | existing.webView.evaluateJavaScript("window.dispatchEvent(new Event('cage-open-archives'))") |
| 174 | } |
| 175 | return |
| 176 | } |
| 177 | let item = invitation |
| 178 | |
| 179 | guard item != nil || hasSaved else { status = "请导入连接文件或有效的临时邀请。"; return } |
| 180 | if let item, (item.expiry ?? .distantPast) <= Date() { invitation = nil; hasInvitation = false; status = "临时邀请已过期,请重新连接或导入新邀请。"; return } |
| 181 | guard let directory = Bundle.main.url(forResource: "mobile-ui", withExtension: nil) else { status = "安装包缺少工作台资源。"; return } |
| 182 | invitation = nil; hasInvitation = false; connecting = true; generation += 1 |
| 183 | let attempt = generation |
| 184 | status = "正在验证电脑并连接…" |
| 185 | linkQueue.async { |
| 186 | let result = Result { |
| 187 | if let item { return try CMConnection.connect(relay: host.relay, room: item.id, token: item.client_token, pin: host.pin, assets: directory.path) } |
| 188 | guard let saved = try HostKeychain.read(host: host), saved.host == host else { throw InputError.unavailable } |
| 189 | return try CMConnection.connectSaved(relay: host.relay, lookup: saved.lookup, pin: host.pin, assets: directory.path) |
| 190 | } |
| 191 | DispatchQueue.main.async { |
| 192 | guard attempt == self.generation else { |
| 193 | if case .success(let old) = result { DispatchQueue.global().async { old.close() } } |
| 194 | return |
| 195 | } |
| 196 | self.connecting = false |
| 197 | switch result { |
| 198 | case .success(let session): self.status = ""; self.addDevice(session, host: host) |
| 199 | case .failure(let error): self.status = error.localizedDescription |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | func leaveWorkspace() {showingWorkspace = false} |
| 205 | func openArchivedSessions() { |
| 206 | if let device = selectedDevice { |
| 207 | selectDevice(device.id) |
| 208 | device.webView.evaluateJavaScript("window.dispatchEvent(new Event('cage-open-archives'))") |
| 209 | } else { |
| 210 | connect(openArchived: true) |
| 211 | } |
| 212 | } |
| 213 | func selectDevice(_ id: String) { |
| 214 | guard devices.contains(where: {$0.id == id}) else {return} |
| 215 | selectedDeviceID = id; showingWorkspace = true |
| 216 | session = selectedDevice?.connection |
| 217 | publishDevices() |
| 218 | } |
| 219 | func nameDevice(_ id: String, _ value: String) { |
| 220 | guard let index = devices.firstIndex(where: {$0.id == id}) else {return} |
| 221 | let name = value.trimmingCharacters(in: .whitespacesAndNewlines) |
| 222 | guard !name.isEmpty, devices[index].name != name else {return} |
| 223 | devices[index].name = String(name.prefix(120)); publishDevices() |
| 224 | } |
| 225 | private func addDevice(_ connection: CMConnection, host: Host) { |
| 226 | let id = host.relay + "|" + host.pin |
| 227 | let config = WKWebViewConfiguration() |
| 228 | config.websiteDataStore = .nonPersistent() |
| 229 | config.allowsInlineMediaPlayback = true |
| 230 | config.preferences.javaScriptCanOpenWindowsAutomatically = false |
| 231 | config.applicationNameForUserAgent = "CageMobile/1" |
| 232 | let delegate = WorkspaceNavigation(connection.launchURL) |
| 233 | config.userContentController.add(DeviceWebBridge(model: self, id: id, origin: connection.launchURL), name: "cageDevices") |
| 234 | config.userContentController.addUserScript(WKUserScript(source: deviceScript(id), injectionTime: .atDocumentStart, forMainFrameOnly: true)) |
| 235 | let web = WKWebView(frame: .zero, configuration: config) |
| 236 | web.scrollView.contentInsetAdjustmentBehavior = .never |
| 237 | web.navigationDelegate = delegate |
| 238 | |
| 239 | navigationDelegates[id] = delegate |
| 240 | devices.append(ConnectedDevice(id: id, name: "已连接电脑", connection: connection, webView: web)) |
| 241 | selectDevice(id) |
| 242 | var launch = connection.launchURL |
| 243 | if openArchivedAfterConnect { |
| 244 | var parts = URLComponents(url: launch, resolvingAgainstBaseURL: false)! |
| 245 | parts.queryItems = (parts.queryItems ?? []) + [URLQueryItem(name: "page", value: "archived")] |
| 246 | launch = parts.url! |
| 247 | openArchivedAfterConnect = false |
| 248 | } |
| 249 | web.load(URLRequest(url: launch)) |
| 250 | } |
| 251 | private var navigationDelegates: [String: WKNavigationDelegate] = [:] |
| 252 | private func deviceScript(_ current: String) -> String { |
| 253 | let value: [String: Any] = ["current": current, "devices": devices.map {["id": $0.id, "name": $0.name]}] |
| 254 | let data = try! JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) |
| 255 | return "window.__cageDevices=" + String(decoding: data, as: UTF8.self) + ";window.dispatchEvent(new CustomEvent('cage-devices',{detail:window.__cageDevices}));" |
| 256 | } |
| 257 | func publishDevices() { |
| 258 | for device in devices { |
| 259 | let script = deviceScript(device.id) |
| 260 | device.webView.configuration.userContentController.removeAllUserScripts() |
| 261 | device.webView.configuration.userContentController.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true)) |
| 262 | |
| 263 | #if targetEnvironment(simulator) |
| 264 | if device.connection == nil { |
| 265 | device.webView.configuration.userContentController.addUserScript(WKUserScript(source: SimulatorWorkspacePreview.fixture, injectionTime: .atDocumentStart, forMainFrameOnly: true)) |
| 266 | } |
| 267 | #endif |
| 268 | device.webView.evaluateJavaScript(script) |
| 269 | } |
| 270 | } |
| 271 | func disconnectDevice(_ id: String) { |
| 272 | guard let old = devices.first(where: {$0.id == id}) else {return} |
| 273 | old.webView.stopLoading(); old.webView.navigationDelegate = nil |
| 274 | old.webView.configuration.userContentController.removeScriptMessageHandler(forName: "cageDevices") |
| 275 | devices.removeAll {$0.id == id}; navigationDelegates.removeValue(forKey: id) |
| 276 | if selectedDeviceID == id { |
| 277 | selectedDeviceID = devices.first?.id; session = selectedDevice?.connection |
| 278 | if selectedDeviceID == nil {showingWorkspace = false} |
| 279 | } |
| 280 | if let connection = old.connection {linkQueue.async {connection.close()}} |
| 281 | publishDevices() |
| 282 | } |
| 283 | func disconnect() {if let id = selectedDeviceID {disconnectDevice(id)}} |
| 284 | func reconnect() {disconnect(); connect()} |
| 285 | func startPreview() { |
| 286 | #if targetEnvironment(simulator) |
| 287 | for (id, name) in [("preview-mac", "我的电脑 · 模拟器预览"), ("preview-linux", "Linux 工作站 · 模拟器预览")] { |
| 288 | if !devices.contains(where: {$0.id == id}) { |
| 289 | let preview = SimulatorWorkspacePreview.makeWebView(model: self, id: id) |
| 290 | devices.append(ConnectedDevice(id: id, name: name, connection: nil, webView: preview.web)) |
| 291 | navigationDelegates[id] = preview.delegate |
| 292 | } |
| 293 | } |
| 294 | selectDevice("preview-mac") |
| 295 | #endif |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | private final class WorkspaceNavigation: NSObject, WKNavigationDelegate { |
| 300 | let origin: URL |
| 301 | init(_ origin: URL) {self.origin = origin} |
| 302 | func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, |
| 303 | decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { |
| 304 | guard let url = action.request.url, action.targetFrame?.isMainFrame == true, |
| 305 | url.scheme == origin.scheme, url.host == origin.host, url.port == origin.port, |
| 306 | url.user == nil, url.password == nil else {decisionHandler(.cancel); return} |
| 307 | decisionHandler(.allow) |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | private struct Workspace: UIViewRepresentable { |
| 312 | let webView: WKWebView |
| 313 | func makeUIView(context: Context) -> WKWebView {webView} |
| 314 | func updateUIView(_ view: WKWebView, context: Context) {} |
| 315 | } |
| 316 | |
| 317 | private enum CageStyle { |
| 318 | static let paper = Color(uiColor: UIColor { traits in |
| 319 | traits.userInterfaceStyle == .dark ? UIColor(white: 0.075, alpha: 1) : UIColor(red: 0.982, green: 0.978, blue: 0.967, alpha: 1) |
| 320 | }) |
| 321 | static let ink = Color(uiColor: .label) |
| 322 | static let inverse = Color(uiColor: .systemBackground) |
| 323 | } |
| 324 | |
| 325 | private struct CageButtonStyle: ButtonStyle { |
| 326 | @Environment(\.isEnabled) private var enabled |
| 327 | func makeBody(configuration: Configuration) -> some View { |
| 328 | configuration.label |
| 329 | .opacity(enabled ? (configuration.isPressed ? 0.9 : 1) : 0.5) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | private struct ActionLabel: View { |
| 334 | let title: String |
| 335 | let symbol: String |
| 336 | var primary = true |
| 337 | var height: CGFloat = 52 |
| 338 | var body: some View { |
| 339 | Label(title, systemImage: symbol) |
| 340 | .font(.headline).frame(maxWidth: .infinity, minHeight: height) |
| 341 | .foregroundStyle(primary ? CageStyle.inverse : CageStyle.ink) |
| 342 | .background(primary ? CageStyle.ink : Color(uiColor: .secondarySystemFill), |
| 343 | in: RoundedRectangle(cornerRadius: 16)) |
| 344 | .contentShape(Rectangle()) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | private struct QRScanner: UIViewControllerRepresentable { |
| 349 | let region: CGRect |
| 350 | @Binding var hint: String |
| 351 | let result: (String?) -> Void |
| 352 | final class Delegate: NSObject, DataScannerViewControllerDelegate { |
| 353 | let result: (String?) -> Void |
| 354 | var hint: Binding<String> |
| 355 | var finished = false |
| 356 | init(_ result: @escaping (String?) -> Void, hint: Binding<String>) {self.result = result; self.hint = hint} |
| 357 | func dataScanner(_ scanner: DataScannerViewController, didAdd items: [RecognizedItem], allItems: [RecognizedItem]) { |
| 358 | for case .barcode(let barcode) in items { |
| 359 | guard !finished, let code = barcode.payloadStringValue else {continue} |
| 360 | guard code.hasPrefix("CAGE1:"), code.utf8.count <= 4096 else { |
| 361 | hint.wrappedValue = "请扫描电脑「设置 → 远程连接」中的 Cage 配对二维码"; continue |
| 362 | } |
| 363 | UINotificationFeedbackGenerator().notificationOccurred(.success) |
| 364 | finished = true; scanner.stopScanning(); result(code); return |
| 365 | } |
| 366 | } |
| 367 | func dataScanner(_ scanner: DataScannerViewController, becameUnavailableWithError error: DataScannerViewController.ScanningUnavailable) { |
| 368 | if !finished {finished = true; result(nil)} |
| 369 | } |
| 370 | } |
| 371 | func makeCoordinator() -> Delegate { Delegate(result, hint: $hint) } |
| 372 | func makeUIViewController(context: Context) -> DataScannerViewController { |
| 373 | let scanner = DataScannerViewController(recognizedDataTypes: [.barcode(symbologies: [.qr])], qualityLevel: .balanced, isGuidanceEnabled: false, isHighlightingEnabled: false) |
| 374 | scanner.delegate = context.coordinator |
| 375 | DispatchQueue.main.async { |
| 376 | guard !context.coordinator.finished else {return} |
| 377 | scanner.regionOfInterest = region |
| 378 | do { try scanner.startScanning() } catch {context.coordinator.finished = true; result(nil)} |
| 379 | } |
| 380 | return scanner |
| 381 | } |
| 382 | func updateUIViewController(_ scanner: DataScannerViewController, context: Context) {scanner.regionOfInterest = region} |
| 383 | static func dismantleUIViewController(_ scanner: DataScannerViewController, coordinator: Delegate) {coordinator.finished = true; scanner.stopScanning()} |
| 384 | } |
| 385 | |
| 386 | private struct FinderMask: Shape { |
| 387 | let box: CGRect |
| 388 | func path(in rect: CGRect) -> Path { |
| 389 | var path = Path(rect) |
| 390 | path.addRoundedRect(in: box, cornerSize: CGSize(width: 18, height: 18)) |
| 391 | return path |
| 392 | } |
| 393 | } |
| 394 | private struct FinderCorners: Shape { |
| 395 | func path(in rect: CGRect) -> Path { |
| 396 | var path = Path() |
| 397 | for x in [CGFloat(0), CGFloat(1)] {for y in [CGFloat(0), CGFloat(1)] { |
| 398 | var corner = Path() |
| 399 | corner.move(to: CGPoint(x: 0, y: 30)); corner.addLine(to: CGPoint(x: 0, y: 18)) |
| 400 | corner.addQuadCurve(to: CGPoint(x: 18, y: 0), control: .zero); corner.addLine(to: CGPoint(x: 30, y: 0)) |
| 401 | let transform = CGAffineTransform(a: x == 0 ? 1 : -1, b: 0, c: 0, d: y == 0 ? 1 : -1, tx: x * rect.width, ty: y * rect.height) |
| 402 | path.addPath(corner, transform: transform) |
| 403 | }} |
| 404 | return path |
| 405 | } |
| 406 | } |
| 407 | private struct QRScannerScreen: View { |
| 408 | let result: (String?) -> Void |
| 409 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 410 | @State private var sweeping = false |
| 411 | @State private var hint = "将 Cage 配对二维码放入框内\n在电脑「设置 → 远程连接」中生成" |
| 412 | private let accent = Color(red: 0.91, green: 0.72, blue: 0.62) |
| 413 | var body: some View { |
| 414 | GeometryReader { geometry in |
| 415 | let side = max(96, min(280, min(geometry.size.width - 56, geometry.size.height - 190))) |
| 416 | let box = CGRect(x: (geometry.size.width - side) / 2, y: 24 + max(0, (geometry.size.height - 190 - side) / 2), width: side, height: side) |
| 417 | ZStack(alignment: .bottom) { |
| 418 | #if targetEnvironment(simulator) |
| 419 | Color(white: 0.15) |
| 420 | Image(systemName: "qrcode").resizable().interpolation(.none).scaledToFit() |
| 421 | .foregroundStyle(.white.opacity(0.8)).frame(width: side * 0.65, height: side * 0.65) |
| 422 | .position(x: box.midX, y: box.midY).accessibilityHidden(true) |
| 423 | #else |
| 424 | QRScanner(region: box, hint: $hint, result: result) |
| 425 | #endif |
| 426 | FinderMask(box: box).fill(Color(red: 0.08, green: 0.09, blue: 0.09).opacity(0.72), style: FillStyle(eoFill: true)) |
| 427 | RoundedRectangle(cornerRadius: 18).stroke(.white.opacity(0.45), lineWidth: 1) |
| 428 | .frame(width: side, height: side).position(x: box.midX, y: box.midY) |
| 429 | FinderCorners().stroke(accent, style: StrokeStyle(lineWidth: 4, lineCap: .round)) |
| 430 | .frame(width: side, height: side).position(x: box.midX, y: box.midY) |
| 431 | VStack(spacing: 0) { |
| 432 | LinearGradient(colors: [accent.opacity(0), accent.opacity(0.22)], startPoint: .top, endPoint: .bottom).frame(height: 26) |
| 433 | Capsule().fill(accent).frame(height: 2) |
| 434 | }.frame(width: side - 24) |
| 435 | .position(x: box.midX, y: reduceMotion ? box.midY : box.minY + 24 + (sweeping ? side - 48 : 0)) |
| 436 | .animation(reduceMotion ? nil : .linear(duration: 2.4).repeatForever(autoreverses: true), value: sweeping) |
| 437 | .accessibilityHidden(true) |
| 438 | VStack(spacing: 12) { |
| 439 | Text("连接你的电脑").font(.title2.bold()) |
| 440 | Text(hint).font(.subheadline).foregroundStyle(.white.opacity(0.88)).multilineTextAlignment(.center) |
| 441 | Text(simulatorPreviewEnabled ? "模拟器预览 · 即将进入示例工作台" : "仅识别 Cage 配对码") |
| 442 | .font(.caption).foregroundStyle(.white.opacity(0.6)) |
| 443 | }.foregroundStyle(.white).padding(.horizontal, 24).padding(.bottom, 24).accessibilityElement(children: .combine) |
| 444 | }.background(Color.black).onAppear {sweeping = true} |
| 445 | .task { |
| 446 | #if targetEnvironment(simulator) |
| 447 | do {try await Task.sleep(for: .seconds(2))} catch {return} |
| 448 | result(nil) |
| 449 | #endif |
| 450 | } |
| 451 | }.toolbarColorScheme(.dark, for: .navigationBar) |
| 452 | .toolbarBackground(Color(red: 0.08, green: 0.09, blue: 0.09), for: .navigationBar).toolbarBackground(.visible, for: .navigationBar) |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | private struct ConnectionSheet: View { |
| 457 | @ObservedObject var model: ConnectionModel |
| 458 | let previewConnected: () -> Void |
| 459 | @State private var manual = false |
| 460 | @State private var scanning = false |
| 461 | @State private var disconnecting: ConnectedDevice? |
| 462 | @State private var previewScanned = false |
| 463 | @State private var code = "" |
| 464 | var body: some View { |
| 465 | NavigationStack { |
| 466 | ScrollView { |
| 467 | VStack(spacing: 12) { |
| 468 | Image("PairDevices").resizable().scaledToFit().frame(maxWidth: .infinity) |
| 469 | .frame(height: 150).accessibilityHidden(true) |
| 470 | Text("连接电脑").font(.title.bold()) |
| 471 | Text("在电脑的 Cage 设置中打开「远程连接」,生成配对二维码或复制配对码。") |
| 472 | .font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center) |
| 473 | .padding(.bottom, 10) |
| 474 | Button { |
| 475 | Task { @MainActor in |
| 476 | if simulatorPreviewEnabled {scanning = true; return} |
| 477 | guard DataScannerViewController.isSupported, |
| 478 | await AVCaptureDevice.requestAccess(for: .video), |
| 479 | DataScannerViewController.isAvailable else { |
| 480 | model.status = "相机暂不可用,请检查相机权限或使用配对码。"; return |
| 481 | } |
| 482 | scanning = true |
| 483 | } |
| 484 | } label: {ActionLabel(title: "扫码连接", symbol: "qrcode.viewfinder")} |
| 485 | Button {manual = true} label: {ActionLabel(title: "使用配对码", symbol: "key", primary: false)} |
| 486 | if model.hasSaved || model.hasInvitation { |
| 487 | Button("重新连接", action: model.connect).frame(minHeight: 44).disabled(!model.canConnect) |
| 488 | } |
| 489 | if !model.devices.isEmpty { |
| 490 | Divider().padding(.vertical, 8) |
| 491 | Text("已连接设备").font(.headline).frame(maxWidth: .infinity, alignment: .leading) |
| 492 | Text("长按设备可取消连接").font(.footnote).foregroundStyle(.secondary) |
| 493 | .frame(maxWidth: .infinity, alignment: .leading) |
| 494 | ForEach(model.devices) {device in |
| 495 | Button {if disconnecting == nil {model.selectDevice(device.id)}} label: { |
| 496 | HStack {Image(systemName: "desktopcomputer"); Text(device.name); Spacer(); Image(systemName: "chevron.right")} |
| 497 | .frame(minHeight: 48).contentShape(Rectangle()) |
| 498 | } |
| 499 | .simultaneousGesture(LongPressGesture().onEnded { _ in disconnecting = device }) |
| 500 | .accessibilityAction(named: Text("取消连接")) {disconnecting = device} |
| 501 | } |
| 502 | } |
| 503 | status |
| 504 | }.padding(24).frame(maxWidth: 520) |
| 505 | .frame(maxWidth: .infinity) |
| 506 | }.background(CageStyle.paper).buttonStyle(CageButtonStyle()) |
| 507 | .navigationDestination(isPresented: $manual) { |
| 508 | Form { |
| 509 | Section { |
| 510 | SecureField("粘贴电脑上的一次性配对码", text: $code) |
| 511 | .textInputAutocapitalization(.never).autocorrectionDisabled() |
| 512 | Button("连接电脑") {model.pair(code: code); code = ""} |
| 513 | .accessibilityIdentifier("redeem-pair-code") |
| 514 | .disabled(code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.connecting) |
| 515 | } |
| 516 | if !model.status.isEmpty {Section {status}} |
| 517 | }.navigationTitle("配对码") |
| 518 | } |
| 519 | .sheet(item: $disconnecting) {device in |
| 520 | VStack(spacing: 20) { |
| 521 | Text("取消连接?").font(.title2.bold()) |
| 522 | Text(device.name).foregroundStyle(.secondary) |
| 523 | Text("将关闭这台设备的连接。已保存的配对信息会保留。") |
| 524 | .font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center) |
| 525 | Button("取消连接", role: .destructive) { |
| 526 | model.disconnectDevice(device.id) |
| 527 | disconnecting = nil |
| 528 | }.frame(maxWidth: .infinity, minHeight: 48) |
| 529 | Button("保留连接") {disconnecting = nil}.frame(minHeight: 44) |
| 530 | }.padding(24).presentationDetents([.height(300)]).presentationDragIndicator(.visible) |
| 531 | } |
| 532 | .sheet(isPresented: $scanning, onDismiss: { |
| 533 | if previewScanned {previewScanned = false; previewConnected()} |
| 534 | }) { |
| 535 | NavigationStack { |
| 536 | QRScannerScreen { result in |
| 537 | scanning = false |
| 538 | if simulatorPreviewEnabled {previewScanned = true} |
| 539 | else if let result {model.pair(code: result)} |
| 540 | else {model.status = "无法读取二维码,请重试或使用配对码。"} |
| 541 | }.navigationTitle("扫描电脑二维码").navigationBarTitleDisplayMode(.inline) |
| 542 | .toolbar {Button("取消") {scanning = false}} |
| 543 | } |
| 544 | } |
| 545 | }.disabled(model.connecting).interactiveDismissDisabled(model.connecting) |
| 546 | .presentationDetents([.fraction(0.72), .large]).presentationDragIndicator(.visible) |
| 547 | } |
| 548 | @ViewBuilder private var status: some View { |
| 549 | if !model.status.isEmpty { |
| 550 | Text(model.status).font(.footnote).foregroundStyle(.secondary) |
| 551 | .accessibilityAddTraits(.updatesFrequently) |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | private enum CageTheme: String, CaseIterable { |
| 557 | case system = "跟随系统", light = "浅色", dark = "深色" |
| 558 | var scheme: ColorScheme? { |
| 559 | switch self {case .system: return nil; case .light: return .light; case .dark: return .dark} |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | private struct SettingsScreen: View { |
| 564 | @ObservedObject var model: ConnectionModel |
| 565 | @Binding var theme: CageTheme |
| 566 | let connect: () -> Void |
| 567 | @State private var relaySettings = false |
| 568 | @State private var advanced = false |
| 569 | @State private var themes = false |
| 570 | @State private var picking = false |
| 571 | @State private var confirmingForget = false |
| 572 | |
| 573 | var body: some View { |
| 574 | Form { |
| 575 | Section("外观") { |
| 576 | DisclosureGroup(isExpanded: $themes) { |
| 577 | ForEach(CageTheme.allCases, id: \.self) {option in |
| 578 | Button { |
| 579 | theme = option; themes = false |
| 580 | } label: { |
| 581 | HStack {Text(option.rawValue); Spacer(); if theme == option {Image(systemName: "checkmark")}} |
| 582 | .frame(minHeight: 44).contentShape(Rectangle()) |
| 583 | }.accessibilityAddTraits(theme == option ? .isSelected : []) |
| 584 | } |
| 585 | } label: { |
| 586 | HStack { |
| 587 | Label("主题", systemImage: "circle.lefthalf.filled") |
| 588 | Spacer(); Text(theme.rawValue).foregroundStyle(.secondary) |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | Section("电脑连接") { |
| 593 | Button("已归档会话", action: model.openArchivedSessions) |
| 594 | .disabled(model.selectedDevice == nil && !model.canConnect) |
| 595 | DisclosureGroup("中继设置", isExpanded: $relaySettings) { |
| 596 | Toggle("使用自建中继", isOn: Binding(get: {model.relay != CMConnection.defaultRelay()}, |
| 597 | set: {model.relay = $0 ? "" : CMConnection.defaultRelay()})) |
| 598 | if model.relay != CMConnection.defaultRelay() { |
| 599 | TextField("自建 VPS 的 HTTPS 地址", text: $model.relay) |
| 600 | .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled() |
| 601 | } else {Text("Cage 官方中继").foregroundStyle(.secondary)} |
| 602 | Button("保存中继设置", action: model.saveRelay) |
| 603 | } |
| 604 | DisclosureGroup("指纹与连接文件", isExpanded: $advanced) { |
| 605 | Text(CMConnection.usesSimulatorIdentity ? "模拟器测试身份的指纹" : "这台手机的指纹").font(.headline) |
| 606 | Text(model.fingerprint).font(.caption.monospaced()).textSelection(.enabled) |
| 607 | Button("复制手机指纹") {UIPasteboard.general.string = model.fingerprint; model.status = "手机指纹已复制"} |
| 608 | .disabled(model.fingerprint.isEmpty) |
| 609 | Button("导入连接文件") {picking = true} |
| 610 | TextField("电脑指纹 sha256:…", text: $model.pin).textInputAutocapitalization(.never).autocorrectionDisabled() |
| 611 | Toggle("已核对电脑指纹", isOn: $model.verified) |
| 612 | Button("保存已核对的主机", action: model.saveTrust).disabled(!model.verified) |
| 613 | if model.hasInvitation || model.hasSaved {Button("连接工作台", action: connect).disabled(!model.canConnect)} |
| 614 | } |
| 615 | if model.canForget {Button("忘记主机", role: .destructive) {confirmingForget = true}} |
| 616 | } |
| 617 | if !model.status.isEmpty {Section {Text(model.status).font(.footnote).foregroundStyle(.secondary)}} |
| 618 | }.navigationTitle("设置").disabled(model.connecting) |
| 619 | .alert("忘记主机?", isPresented: $confirmingForget) { |
| 620 | Button("取消", role: .cancel) {} |
| 621 | Button("忘记主机", role: .destructive, action: model.forget) |
| 622 | } message: {Text("将移除这台电脑的地址、指纹和重连凭据。")} |
| 623 | .fileImporter(isPresented: $picking, allowedContentTypes: [.json, .plainText]) {result in |
| 624 | if case .success(let file) = result {model.loadInvitation(file)} |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | @main |
| 630 | struct CageMobileApp: App { |
| 631 | @StateObject private var model = ConnectionModel() |
| 632 | @AppStorage("appearance-theme") private var theme = CageTheme.system |
| 633 | @State private var showingSettings = false |
| 634 | @State private var pairing = false |
| 635 | |
| 636 | var body: some Scene { |
| 637 | WindowGroup { |
| 638 | NavigationStack { |
| 639 | Group { |
| 640 | if model.showingWorkspace, let device = model.selectedDevice { |
| 641 | Workspace(webView: device.webView).id(device.id) |
| 642 | } else { |
| 643 | home |
| 644 | } |
| 645 | } |
| 646 | .navigationDestination(isPresented: $showingSettings) { |
| 647 | SettingsScreen(model: model, theme: $theme, connect: model.connect) |
| 648 | } |
| 649 | }.buttonStyle(CageButtonStyle()).tint(CageStyle.ink).preferredColorScheme(theme.scheme) |
| 650 | .sheet(isPresented: $pairing) { |
| 651 | ConnectionSheet(model: model, previewConnected: { |
| 652 | pairing = false; showingSettings = false; model.startPreview() |
| 653 | }).buttonStyle(CageButtonStyle()).tint(CageStyle.ink).preferredColorScheme(theme.scheme) |
| 654 | } |
| 655 | .onChange(of: model.showingWorkspace) { _, connected in |
| 656 | if connected {pairing = false; showingSettings = false} |
| 657 | } |
| 658 | .onChange(of: model.relay) {model.verified = false} |
| 659 | .onChange(of: model.pin) {model.verified = false} |
| 660 | } |
| 661 | } |
| 662 | private var home: some View { |
| 663 | GeometryReader { geometry in |
| 664 | let brandSpacing = min(60, max(28, geometry.size.height * 0.075)) + 32 |
| 665 | ScrollView { |
| 666 | VStack(spacing: 0) { |
| 667 | Spacer(minLength: 12) |
| 668 | VStack(spacing: brandSpacing) { |
| 669 | VStack(spacing: 12) { |
| 670 | Image("CageMark").resizable().scaledToFit().frame(width: 120, height: 120) |
| 671 | .clipShape(RoundedRectangle(cornerRadius: 16)).accessibilityHidden(true) |
| 672 | Text("Cage").font(.system(size: 36, weight: .semibold, design: .rounded)) |
| 673 | } |
| 674 | Button {pairing = true} label: { |
| 675 | ActionLabel(title: "连接电脑", symbol: "desktopcomputer", height: 60) |
| 676 | } |
| 677 | }.frame(maxWidth: 276).padding(.top, 32) |
| 678 | Spacer(minLength: 12) |
| 679 | }.padding(.horizontal, 24).frame(maxWidth: .infinity).frame(minHeight: geometry.size.height) |
| 680 | }.scrollBounceBehavior(.basedOnSize) |
| 681 | }.background(CageStyle.paper.ignoresSafeArea()).buttonStyle(CageButtonStyle()) |
| 682 | .navigationBarTitleDisplayMode(.inline) |
| 683 | .toolbar { |
| 684 | ToolbarItem(placement: .topBarTrailing) { |
| 685 | Button {showingSettings = true} label: {Image(systemName: "gearshape")} |
| 686 | .accessibilityLabel("设置") |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 | } |