import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'core/bridge.dart'; import 'core/discovery_client.dart'; import 'core/signaling_endpoint.dart'; import 'core/diagnostic_log.dart'; import 'core/control_file_client.dart'; import 'core/native_core.dart'; import 'core/models.dart'; import 'core/pairing.dart'; import 'core/pin_store.dart'; import 'core/watch_client.dart'; import 'features/control/control_toolbar.dart'; import 'features/discovery/device_list.dart'; import 'features/discovery/pairing_paste_dialog.dart'; import 'features/file/file_browser_page.dart'; import 'features/session/connect_bar.dart'; import 'features/session/mirror_bar.dart'; import 'features/settings/settings_page.dart'; void main() => runApp(const TTSTDConnectApp()); class TTSTDConnectApp extends StatelessWidget { const TTSTDConnectApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'TTSTD Connect', debugShowCheckedModeBanner: false, theme: ThemeData( useMaterial3: true, colorSchemeSeed: const Color(0xFF5468FF), brightness: Brightness.dark, ), home: const HomePage(), ); } } class HomePage extends StatefulWidget { const HomePage({super.key}); @override State createState() => _HomePageState(); } class _HomePageState extends State { NativeCore? _nativeCore; late final SenderBridge _bridge; final DiagnosticLog _diagnosticLog = DiagnosticLog(); final PinStore _pins = PinStore(); final PairedDeviceStore _paired = PairedDeviceStore(); Timer? _demoStatusTimer; Timer? _diagnosticTimer; Timer? _connectWatchdog; Timer? _discoveryTimer; Timer? _videoStatsTimer; Timer? _eventTimer; Timer? _clipboardTimer; Timer? _watchRefreshTimer; SignalingWatch? _watch; bool _watchConnected = false; bool _refreshQueued = false; /// 当前控制通道是否走信令中继(媒体分片经中继加密转发,延迟高于直连)。 bool _relayActive = false; /// 被控端回送的有效权限等级(msgType=10);被控端未应答前仅允许查看。 AccessLevel _grantedAccess = AccessLevel.view; bool _mediaProtocolAgreed = false; /// 权限不足提示的去抖时间,避免连续手势把 SnackBar 刷爆。 DateTime? _lastAccessWarnAt; List _devices = const []; DeviceInfo? _selected; bool _switchingDevice = false; bool _pairingDialogOpen = false; ConnectionPhase _phase = ConnectionPhase.idle; AppSettings _settings = AppSettings.defaults; String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl; bool _localSignalingRunning = false; bool _refreshing = false; Map _demoStatus = const {'running': false}; Map _videoStats = const {}; int? _textureId; /// 串流画面是否已弹出到独立原生窗口。 bool _videoWindowOpen = false; /// 正在拉起窗口并下发投屏请求。 bool _mirrorRequesting = false; bool _mirrorGranted = false; bool _videoStreaming = false; int _lastWindowFrames = 0; DateTime? _lastVideoFrameAt; DateTime? _lastControlErrorAt; DateTime? _mirrorRequestedAt; DateTime? _mirrorGrantedAt; int _videoWindowGeneration = 0; /// 因关窗而停流只下发一次 stopMirror。 bool _stopSentForWindowClose = false; /// 最近一次同步过的剪贴板文本(收/发都记),用来避免两端来回回送同一条内容。 String? _lastClipboardText; String? _nativeError; @override void initState() { super.initState(); try { _nativeCore = NativeCore(); } on Object catch (error) { _nativeError = error.toString(); } _bridge = SenderBridge(nativeCore: _nativeCore); _settings = _bridge.loadSettings(); // 独立窗口被用户关闭 → 停止投屏。 _bridge.onVideoWindowClosed = _onStreamWindowClosed; // 串流窗口里的鼠标点击/拖拽 → 触摸控制帧。 _bridge.onVideoPointer = _onVideoPointer; // 右键/中键、滚轮、键盘 → 对应的控制帧。 _bridge.onVideoMouseButton = _onVideoMouseButton; _bridge.onVideoWheel = _onVideoWheel; _bridge.onVideoKey = _onVideoKey; _diagnosticLog.start(); _diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}'); _pins.load(); _diagnosticLog.write('pinned devices file: ${_pins.path}'); _paired.load(); _diagnosticLog.write('paired devices file: ${_paired.path}'); if (_paired.devices.isNotEmpty) { _devices = _mergePaired(const []); } _bridge.watchPhase().listen((phase) { _diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})'); if (mounted && !_switchingDevice) setState(() => _phase = phase); }); _applySignalingSettings(); _refreshDevices(); _demoStatusTimer = Timer.periodic( const Duration(seconds: 1), (_) => _refreshDemoStatus(), ); _diagnosticTimer = Timer.periodic( const Duration(seconds: 1), (_) => _writeDiagnosticLog(), ); _discoveryTimer = Timer.periodic( const Duration(seconds: 5), (_) => _refreshDevices(), ); _videoStatsTimer = Timer.periodic( const Duration(milliseconds: 500), (_) => _refreshVideoStats(), ); // 被控端上行事件(投屏应答 / 剪贴板 / pong):Windows runner 没有 EventChannel // 实现,只能主动轮询 FFI 队列。 _eventTimer = Timer.periodic( const Duration(milliseconds: 250), (_) => _drainInboundEvents(), ); // 本机剪贴板 → 被控端:Windows 侧没有可用的剪贴板变更通知,只能轮询比较。 _clipboardTimer = Timer.periodic( const Duration(milliseconds: 700), (_) => _syncLocalClipboard(), ); _refreshVideoTextureId(); // 自测/演示用开关:TTSTD_DEMO_AUTOSTART=1 时启动即开启本机监听。 if (Platform.environment['TTSTD_DEMO_AUTOSTART'] == '1') { _startDemoListener(); } _writeDiagnosticLog(); } @override void dispose() { _demoStatusTimer?.cancel(); _diagnosticTimer?.cancel(); _connectWatchdog?.cancel(); _discoveryTimer?.cancel(); _videoStatsTimer?.cancel(); _eventTimer?.cancel(); _clipboardTimer?.cancel(); _watchRefreshTimer?.cancel(); _watch?.stop(); _diagnosticLog.dispose(); _bridge.stopDemoServer(); _bridge.stopLocalSignaling(); _nativeCore?.dispose(); super.dispose(); } void _refreshDemoStatus() { if (_nativeCore == null || !mounted || _switchingDevice) return; try { final wasConnected = _phase.isConnected; final status = _bridge.demoStatus(); final running = status['running'] == true; final connected = status['peerConnected'] == true; final keyEstablished = status['keyEstablished'] == true; final relay = status['relay'] == true; final sessionEnded = _relayActive && !relay && _phase == ConnectionPhase.direct; setState(() { _demoStatus = status; _relayActive = relay; if (connected && keyEstablished) { _connectWatchdog?.cancel(); _phase = ConnectionPhase.direct; } else if (wasConnected) { // 直连监听仍在运行时继续等设备重连。 _phase = running && !sessionEnded ? ConnectionPhase.probing : ConnectionPhase.idle; } else if ((running || relay) && _phase != ConnectionPhase.idle && _phase != ConnectionPhase.failed) { _phase = ConnectionPhase.probing; } }); if (wasConnected && !_phase.isConnected && _videoWindowOpen) { unawaited(_abortMirror('被控端已断开,串流窗口已关闭')); } else if (sessionEnded) { _snack('中继会话已断开'); } // 刚连上时主动下发一次会话配置,顺带把权限等级请求发过去; // 被控端会用 msgType=10 回送裁剪后的有效等级。 if (!wasConnected && _phase.isConnected) { _grantedAccess = AccessLevel.view; _mediaProtocolAgreed = false; _applySessionConfig(); } } on Object catch (error) { _diagnosticLog.write('demoStatus refresh failed: $error'); } } /// 取空原生上行事件队列,逐条处理。 /// /// 单次最多取 32 条,避免某次积压后一帧 setState 处理太久。 void _drainInboundEvents() { if (_nativeCore == null || !mounted) return; for (var i = 0; i < 32; i++) { final event = _bridge.nextInboundEvent(); if (event == null) break; _handleInboundEvent(event); } } void _handleInboundEvent(Map event) { final type = (event['type'] as num?)?.toInt() ?? -1; final action = (event['action'] as num?)?.toInt() ?? -1; final text = (event['text'] as String? ?? '').trim(); switch (type) { case 8: _handleMirrorEvent(action, text); case 4: unawaited(_applyRemoteClipboard(text)); case 10: _handleAccessEvent(text); case 6: _diagnosticLog.write('pong received'); default: _diagnosticLog.write('inbound event type=$type action=$action text=$text'); } } /// 被控端的投屏应答。 /// /// action 与协议 MirrorAction 一致:0=请求 1=停止 2=已允许 3=已拒绝 /// 4=已停止 5=出错。以前没有这条通道,被控端拒绝后主控端只能干等画面。 void _handleMirrorEvent(int action, String text) { _diagnosticLog.write('mirror event action=$action text=$text'); if (!_videoWindowOpen || _stopSentForWindowClose) return; switch (action) { case 2: _mirrorGrantedAt = DateTime.now(); setState(() => _mirrorGranted = true); _snack('被控端已允许投屏'); case 3: unawaited(_abortMirror(text.isEmpty ? '被控端拒绝了投屏请求' : '被控端拒绝了投屏请求:$text')); case 4: unawaited(_abortMirror('被控端已停止投屏')); case 5: unawaited(_abortMirror(text.isEmpty ? '被控端投屏失败' : '被控端投屏失败:$text')); } } /// 投屏没建立起来或对端已停流:关掉独立窗口,避免一直停在「等待画面」。 /// /// [_stopSentForWindowClose] 置位是必须的——窗口是我们自己关的, /// 不能再给对端补发一条 stopMirror。 Future _abortMirror(String message) async { if (_phase.isConnected && _videoWindowOpen && !_stopSentForWindowClose) { _bridge.sendControl('stopMirror', const {}); } _stopSentForWindowClose = true; final close = _bridge.closeVideoWindow(); _clearMirrorState(); await close; if (mounted && !_videoWindowOpen) _snack(message); } void _clearMirrorState() { setState(() { _videoWindowGeneration++; _videoWindowOpen = false; _mirrorGranted = false; _videoStreaming = false; _lastWindowFrames = 0; _lastVideoFrameAt = null; _mirrorRequestedAt = null; _mirrorGrantedAt = null; }); } /// 被控端回送的权限等级(msgType=10,payload 是 JSON)。 /// /// 有效等级可能低于请求值:被控端有自己的上限,且不允许主控端自行提权。 /// 降级时明确提示,否则用户会以为「点了没反应」是自己网络卡了。 void _handleAccessEvent(String text) { if (text.isEmpty) return; AccessLevel level; int max; try { final decoded = jsonDecode(text); if (decoded is! Map) return; _mediaProtocolAgreed = decoded['mediaProtocol'] == NativeCore.mediaProtocol; level = AccessLevel.fromValue(decoded['level'], fallback: _grantedAccess); max = AccessLevel.fromValue(decoded['max'], fallback: level).value; } on Object catch (error) { _diagnosticLog.write('access event parse failed: $error ($text)'); return; } final requested = _settings.access; final capped = level.cap(_settings.access); _diagnosticLog.write( 'access event: granted=${level.code} max=$max requested=${requested.code}', ); if (!mounted) return; setState(() => _grantedAccess = capped); if (capped.value < requested.value) { _snack('被控端将权限限制为「${capped.label}」,超出部分的操作不可用'); } } /// 被控端上行的剪贴板内容 → 写入本机剪贴板。 Future _applyRemoteClipboard(String text) async { if (_pairingDialogOpen || text.isEmpty || !_settings.clipboardSync) return; // 先记住这条内容,否则本机剪贴板轮询会把它当成「本机新复制」再发回去。 _lastClipboardText = text; await Clipboard.setData(ClipboardData(text: text)); _diagnosticLog.write('clipboard from peer applied (${text.length} chars)'); } /// 本机剪贴板变化 → 下发被控端。 /// /// Windows 没有可订阅的剪贴板变更事件,只能定时读一次再和上次内容比较; /// 内容与 [_lastClipboardText] 相同说明是刚同步过来的,不再回送。 Future _syncLocalClipboard() async { if (!mounted || _nativeCore == null || _pairingDialogOpen) return; if (!_phase.isConnected || !_settings.clipboardSync) return; if (!_grantedAccess.allowsControl) return; final ClipboardData? data; try { data = await Clipboard.getData(Clipboard.kTextPlain); } on Object { // 剪贴板被别的程序占用(Office 等的延迟渲染)时读会抛错,下一轮再试。 return; } if (_pairingDialogOpen) return; final text = data?.text; if (text == null || text.isEmpty || text == _lastClipboardText) return; _lastClipboardText = text; _bridge.sendControl('clipboard', {'text': text}); _diagnosticLog.write('clipboard -> peer (${text.length} chars)'); } /// 手动发送一次本机剪贴板内容(控制栏「发送剪贴板」按钮)。 Future _sendLocalClipboard() async { if (!_phase.isConnected) { _snack('请先连接被控端'); return; } if (!_requireControl()) return; final data = await Clipboard.getData(Clipboard.kTextPlain); final text = data?.text; if (text == null || text.isEmpty) { _snack('本机剪贴板为空'); return; } _lastClipboardText = text; _bridge.sendControl('clipboard', {'text': text}); _snack('已发送剪贴板内容(${text.length} 字)'); } /// 把本机会话偏好下发给被控端(msgType=9 会话配置帧)。 /// /// 必须在请求投屏之前下发:被控端按该配置决定编码格式、码率、音频与剪贴板同步。 void _applySessionConfig() { if (!_phase.isConnected) return; final payload = { 'preferH265': _settings.preferH265, 'bitrateMbps': _settings.bitrateMbps, 'audioEnabled': _settings.audioEnabled, 'mediaProtocol': NativeCore.mediaProtocol, 'clipboardSync': _settings.clipboardSync, // 权限只能「请求」:被控端会按本机上限裁剪并用 msgType=10 回送有效等级。 'access': _settings.access.code, }; _bridge.sendControl('sessionConfig', payload); _diagnosticLog.write('sessionConfig sent: $payload'); } /// 首帧前先取一次纹理 ID,避免等待轮询。 Future _refreshVideoTextureId() async { final id = await _bridge.videoTextureId(); if (!mounted || id == null || id == _textureId) return; setState(() => _textureId = id); } /// 轮询原生解码统计:纹理 ID、分辨率、PTS 与失败原因。 Future _refreshVideoStats() async { if (!mounted) return; final generation = _videoWindowGeneration; final stats = await _bridge.videoStats(); if (!mounted || generation != _videoWindowGeneration || stats.isEmpty) { return; } final id = stats['textureId']; final windowOpen = stats['windowOpen']; final windowFrames = stats['windowFrames']; final now = DateTime.now(); if (_videoWindowOpen && windowFrames is int && windowFrames > _lastWindowFrames) { _lastWindowFrames = windowFrames; _lastVideoFrameAt = now; } // 原生窗口被用户关掉(方法通道回调丢失时的兜底)。 final closedByUser = windowOpen is bool && !windowOpen && _videoWindowOpen; setState(() { _videoStats = stats; if (_textureId == null && id is int && id > 0) { _textureId = id; } if (_videoWindowOpen && windowOpen == true && windowFrames is int && windowFrames > 0) { _videoStreaming = _lastVideoFrameAt != null && now.difference(_lastVideoFrameAt!) < const Duration(seconds: 5); } }); if (closedByUser) { await _onStreamWindowClosed(); } else if (_videoWindowOpen) { final lastFrame = _lastVideoFrameAt; final granted = _mirrorGrantedAt; final requested = _mirrorRequestedAt; // 静止画面、网络抖动都可能暂时不产出新帧。保留窗口和会话, // 恢复收帧后自动继续;只有明确停止/断连或首次授权超时才结束投屏。 if (lastFrame == null && granted != null && now.difference(granted) > const Duration(seconds: 15)) { await _abortMirror('投屏已允许,但等待首帧超时'); } else if (lastFrame == null && granted == null && requested != null && now.difference(requested) > const Duration(minutes: 1)) { await _abortMirror('等待投屏确认超时'); } } } /// 请求投屏:先把独立串流窗口打开,再向被控端下发投屏请求。 /// /// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。 Future _requestMirror() async { if (_videoWindowOpen || _mirrorRequesting || _switchingDevice) return; if (!_mediaProtocolAgreed) { _snack('媒体加密协议尚未协商或版本不兼容,请升级两端后重新连接'); return; } if (!_phase.isConnected) { _snack('请先连接被控端'); return; } setState(() { _mirrorRequesting = true; _stopSentForWindowClose = false; }); final generation = _videoWindowGeneration; try { final size = _deviceScreenSize(); final opened = await _bridge.openVideoWindow( width: size?.$1, height: size?.$2, ); if (!mounted || generation != _videoWindowGeneration) return; if (!opened) { _snack('当前平台不支持独立串流窗口'); return; } setState(() { _videoWindowGeneration++; _videoWindowOpen = true; _lastWindowFrames = 0; _lastVideoFrameAt = null; _mirrorGrantedAt = null; _mirrorRequestedAt = DateTime.now(); }); if (!_phase.isConnected) { await _abortMirror('被控端已断开,串流窗口已关闭'); return; } // 先下发会话配置,被控端据此决定编码器参数后再开流。 _applySessionConfig(); _sendControl('requestMirror', const {}); _diagnosticLog.write('mirror request sent'); } finally { if (mounted) setState(() => _mirrorRequesting = false); } } /// 被控端屏幕尺寸(发现信标里的 `res`,如 "1080x2400");拿不到时返回 null。 (int, int)? _deviceScreenSize() { final text = (_selected?.resolution ?? '').trim(); final match = RegExp(r'^(\d+)\s*[xX*]\s*(\d+)$').firstMatch(text); if (match == null) return null; final width = int.tryParse(match.group(1)!); final height = int.tryParse(match.group(2)!); if (width == null || height == null || width <= 0 || height <= 0) return null; return (width, height); } /// 用户关掉独立串流窗口(点关闭按钮 / 按 ESC)→ 直接停止投屏。 /// /// 两个入口都会走到这里:原生的 `windowClosed` 回调,以及轮询 `stats.windowOpen` /// 发现窗口已关闭的兜底。用 [_stopSentForWindowClose] 去重,避免重复下发。 Future _onStreamWindowClosed() async { if (!mounted) return; if (_stopSentForWindowClose) return; _stopSentForWindowClose = true; _clearMirrorState(); if (_phase.isConnected) { _bridge.sendControl('stopMirror', const {}); _diagnosticLog.write('video window closed -> stopMirror'); _snack('串流窗口已关闭,已停止投屏'); } } /// 串流窗口里的鼠标事件 → 触摸控制帧。 /// /// 坐标是画面像素(与编码分辨率一致),被控端会按「画面尺寸 → 真实屏幕尺寸」 /// 换算后再注入,因此主控端不需要知道手机的真实分辨率。 void _onVideoPointer(int action, int x, int y) { if (!_phase.isConnected || !_requireControl()) return; _sendControl('touch', { 'action': action, 'pointerId': 1, 'x': x, 'y': y, // 按下/拖动保持满压力,抬起与取消归零。 'pressure': (action == 0 || action == 2) ? 1000 : 0, }); } /// 串流窗口里的右键/中键 → 鼠标控制帧。 /// /// 被控端把右键映射成「返回」、中键映射成「多任务」,符合桌面操作习惯。 void _onVideoMouseButton(int button, int action, int x, int y) { if (!_phase.isConnected || !_requireControl()) return; final buttons = switch (button) { 1 => 0x02, // bit1 = 右键 2 => 0x04, // bit2 = 中键 _ => 0x01, // bit0 = 左键 }; _sendControl('mouse', { 'action': action, 'x': x, 'y': y, 'buttons': buttons, }); } /// 串流窗口里的滚轮 → 滚轮控制帧(被控端用屏幕中心作为滚动起点)。 void _onVideoWheel(int deltaX, int deltaY) { if (!_phase.isConnected || !_requireControl()) return; if (deltaX == 0 && deltaY == 0) return; _sendControl('wheel', { 'deltaX': deltaX, 'deltaY': deltaY, 'buttons': 0, }); } /// 串流窗口里的键盘 → 按键控制帧。 void _onVideoKey(int action, int vk, int modifiers) { if (!_phase.isConnected || !_requireControl()) return; final keycode = _androidKeycodeFromVk(vk); if (keycode == null) return; _sendControl('key', { 'action': action, 'keycode': keycode, 'modifiers': modifiers, }); } /// 输入/剪贴板需要 control 权限;不足时去抖提示一次。 bool _requireControl() { if (_grantedAccess.allowsControl) return true; _warnAccess(); return false; } /// 文件子协议需要 full 权限。 bool _requireFiles() { if (_grantedAccess.allowsFiles) return true; _warnAccess(); return false; } void _warnAccess() { final now = DateTime.now(); final last = _lastAccessWarnAt; if (last != null && now.difference(last) < const Duration(seconds: 3)) return; _lastAccessWarnAt = now; _snack('被控端当前权限为「${_grantedAccess.label}」,该操作不可用'); } void _snack(String message) { if (!mounted) return; ScaffoldMessenger.of(context) ..hideCurrentSnackBar() ..showSnackBar(SnackBar(content: Text(message))); } /// 文件传输入口:浏览 / 下载 / 上传被控端文件。 Widget _buildFileTransferCard() { final device = _selected; final host = device?.ip ?? ''; return Card( child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( children: [ const Icon(Icons.folder_shared_outlined, size: 18), const SizedBox(width: 8), Text('文件传输', style: Theme.of(context).textTheme.titleMedium), const Spacer(), Text( host.isEmpty ? '未拿到被控端 IP' : '$host:${_settings.filePort}', style: Theme.of(context).textTheme.bodySmall, ), ], ), const SizedBox(height: 6), Text( '浏览被控端目录、下载到本机 Downloads/TTSTD,或上传文件到被控端当前目录。' '需要被控端待命服务运行,并填写其主界面显示的文件服务令牌。', style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 10), FilledButton.tonalIcon( onPressed: _settings.fileTransfer && _grantedAccess.allowsFiles ? _openFileBrowser : null, icon: const Icon(Icons.folder_open, size: 18), label: Text( _grantedAccess.allowsFiles ? '浏览被控端文件' : '浏览被控端文件(需要全权限)', ), ), ], ), ), ); } /// 文件服务要连的被控端地址。 /// /// 优先用设备列表里的局域网 IP;设备信息没带 IP 时退回到控制通道的对端 IP /// (`peerIp`),避免出现「连 127.0.0.1」这种必然失败的情况。 String get _fileHost { final candidate = _selected?.ip.trim() ?? ''; if (_isUsableHost(candidate)) return candidate; final peer = (_demoStatus['peerIp'] as String? ?? '').trim(); if (_isUsableHost(peer)) return peer; return candidate; } static bool _isUsableHost(String host) { if (host.isEmpty) return false; return host != '127.0.0.1' && host != '0.0.0.0' && host != '::1' && host != 'localhost'; } Future _openFileBrowser() async { if (!_requireFiles()) return; if (_selected == null) { _snack('请先选中被控端设备'); return; } final host = _fileHost; if (!_isUsableHost(host)) { _snack('还没拿到被控端 IP:请先连接设备,或在文件页手动填写 IP'); } await Navigator.of(context).push( MaterialPageRoute( builder: (_) => FileBrowserPage( host: host, initialPort: _settings.filePort, initialToken: _settings.fileToken, // 控制通道文件子协议只在已连接时可用(需要控制密钥)。 controlChannel: _phase.isConnected && _nativeCore != null ? ControlFileClient(send: _bridge.sendFileRequest) : null, onConfigChanged: (host, port, token) { final updated = _settings.copyWith(filePort: port, fileToken: token); setState(() => _settings = updated); _bridge.saveSettings(updated); }, ), ), ); } void _writeDiagnosticLog() { Map status; if (_nativeCore == null) { status = {'available': false, 'error': _nativeError ?? ''}; } else { try { status = _bridge.demoStatus(); } on Object catch (error) { status = {'available': true, 'error': error.toString()}; } } final selected = _selected; final target = selected == null ? '-' : '${selected.id} ${selected.ip}:${selected.mediaPort}/${selected.controlPort}'; _diagnosticLog.write( 'phase=${_phase.wireName} label=${_phase.label}; ' 'devices=${_devices.length} target=$target refreshing=$_refreshing; ' 'signaling local=${_settings.useLocalSignaling} ' 'running=$_localSignalingRunning url=${SignalingEndpoint.publicUrl(_effectiveSignalingUrl)}; ' 'nativeError=${_nativeError ?? '-'}; textureId=${_textureId ?? '-'}; ' 'video=$_videoStats; demoStatus=$status', ); } Future _applySignalingSettings() async { if (_settings.localSignalingEnabled) { final started = await _bridge.startLocalSignaling(_settings.localSignalingPort); if (!mounted) return; setState(() => _localSignalingRunning = started); } else { await _bridge.stopLocalSignaling(); if (!mounted) return; setState(() => _localSignalingRunning = false); } final url = await _bridge.resolveSignalingUrl(_settings); if (!mounted) return; setState(() => _effectiveSignalingUrl = url); _restartWatch(url); unawaited(_refreshDevices()); } /// 重启 `/watch` 订阅:信令地址或本机信令开关变化后必须换一条连接。 void _restartWatch(String signalingUrl) { _watchRefreshTimer?.cancel(); _watch?.stop(); _watch = SignalingWatch( signalingUrl: signalingUrl, onChanged: _onWatchEvent, onStateChanged: (connected) { _watchConnected = connected; _diagnosticLog.write( 'signaling watch ${connected ? 'connected' : 'disconnected'} ($signalingUrl)', ); if (mounted) setState(() {}); }, ); _watch!.start(); } /// `/watch` 说设备列表变了 → 去抖后拉一次,避免多设备同时上线时连环刷新。 void _onWatchEvent() { _watchRefreshTimer?.cancel(); _watchRefreshTimer = Timer(const Duration(milliseconds: 300), () { if (!mounted) return; _diagnosticLog.write('signaling watch -> refresh devices'); unawaited(_refreshDevices()); }); } Future _refreshDevices() async { if (_refreshing) { // 正在刷新时又来一次请求:记下来,等本轮结束后补一次,避免事件被吞掉。 _refreshQueued = true; return; } setState(() => _refreshing = true); final discovered = await _bridge.discover(signalingUrl: _effectiveSignalingUrl); if (!mounted) return; final devices = _mergePaired(discovered); setState(() { _devices = devices; if (_selected == null || (!_phase.isConnected && _phase != ConnectionPhase.probing && !_switchingDevice && !devices.any((device) => PairedDeviceStore.sameDevice(device, _selected!)))) { _selected = devices.isEmpty ? null : devices.first; } _refreshing = false; }); _diagnosticLog.write( 'discover result: ${discovered.length} found, ${devices.length} shown ' '(${_paired.devices.length} paired)', ); if (_refreshQueued) { _refreshQueued = false; unawaited(_refreshDevices()); } } /// 发现结果与已导入的配对设备合并:发现结果优先,导入记录补位。 List _mergePaired(List discovered) { final merged = [...discovered]; for (final paired in _paired.devices) { final index = merged.indexWhere((device) => PairedDeviceStore.sameDevice(device, paired)); if (index < 0) merged.add(paired); } return merged; } /// 导入 `lancast://pair?...`(扫码内容或手工粘贴)。 Future _showPairingDialog() async { if (_pairingDialogOpen) return; _pairingDialogOpen = true; PairingUri? pairing; try { pairing = await showDialog( context: context, builder: (_) => const PairingPasteDialog(), ); } finally { // Do not forward pairing secrets to an already connected remote device. try { _lastClipboardText = (await Clipboard.getData(Clipboard.kTextPlain))?.text; } on Object { /* Clipboard may be temporarily unavailable. */ } _pairingDialogOpen = false; } if (!mounted || pairing == null) return; final device = pairing.toDevice(); // 配对链接本身就是带外渠道,导入即可信:直接写 pin,后续连接走一致性校验。 if (device.fingerprint.isNotEmpty) { _pins.pin(_pinKeyOf(device), device.fingerprint); } _paired.save(device); _diagnosticLog.write( 'paired device imported: ${device.id} ${device.ip}:${device.controlPort} ' 'tls=${device.tlsFingerprint.isEmpty ? '-' : device.tlsFingerprint}', ); setState(() { _devices = _mergePaired(_devices); }); await _selectDevice(device); _snack('已导入 ${device.name}'); } static String _pinKeyOf(DeviceInfo device) => device.id.trim().isNotEmpty ? device.id.trim() : '${device.ip}:${device.controlPort}'; Future _selectDevice(DeviceInfo device) async { if (_switchingDevice || (_selected != null && PairedDeviceStore.sameDevice(_selected!, device))) return; _switchingDevice = true; try { final needsDisconnect = _phase != ConnectionPhase.idle || _demoRunning || _relayActive || _videoWindowOpen; if (needsDisconnect) { _diagnosticLog.write('device switch: ${_selected?.ip} -> ${device.ip}; disconnect old session'); // Disable controls before the first await; selection must not relabel a live socket. setState(() { _phase = ConnectionPhase.idle; _mediaProtocolAgreed = false; _grantedAccess = AccessLevel.view; }); await _disconnect(); } if (mounted) setState(() => _selected = device); } on Object catch (error) { _diagnosticLog.write('device switch failed: $error'); if (mounted) _snack('旧设备断开失败,请重试切换设备'); } finally { _switchingDevice = false; } } Future _connect() async { if (_switchingDevice) return; final device = _selected; if (device == null) return; _diagnosticLog.write( 'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}', ); if (!await _confirmFingerprint(device)) return; if (!mounted || _selected == null || !PairedDeviceStore.sameDevice(_selected!, device)) return; if (_settings.relayEnabled) { await _connectViaRelay(device); return; } _connectWatchdog?.cancel(); setState(() => _phase = ConnectionPhase.probing); _connectWatchdog = Timer(const Duration(seconds: 10), () { if (!mounted || _phase != ConnectionPhase.probing) return; _diagnosticLog.write('connect timeout after 10s'); _writeDiagnosticLog(); setState(() => _phase = ConnectionPhase.failed); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('连接超时:被控端未接入,请检查 IP、端口和网络')), ); }); try { await _bridge.connect(device); } on Object catch (error) { _connectWatchdog?.cancel(); _diagnosticLog.write('connect failed: $error'); if (!mounted) return; setState(() => _phase = ConnectionPhase.failed); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('连接失败:$error')), ); } } /// 跨网段连接:控制帧经信令服务器中转,不依赖被控端能反连本机。 /// /// 中继同时承载控制帧与加密媒体分片;媒体延迟高于直连,但可跨网段。 Future _connectViaRelay(DeviceInfo device) async { final signalingUrl = await _bridge.resolveSignalingUrl(_settings); try { await DiscoveryClient.listDevices(signalingUrl, throwOnError: true); } on Object catch (error) { if (mounted) _snack('信令连接失败:$error'); return; } if (!mounted || _selected == null || !PairedDeviceStore.sameDevice(_selected!, device)) return; final error = _bridge.startRelay(device, signalingUrl); if (!mounted) return; if (error != null) { _diagnosticLog.write('relay start failed: $error'); setState(() => _phase = ConnectionPhase.failed); _snack('中继连接失败:$error'); return; } _diagnosticLog.write('relay start: ${device.id} via $signalingUrl'); setState(() => _phase = ConnectionPhase.probing); _connectWatchdog?.cancel(); // 中继要多等几次 `/relay` 轮询(被控端可能刚开始轮询),窗口放宽到 20 秒。 _connectWatchdog = Timer(const Duration(seconds: 20), () { if (!mounted || _phase != ConnectionPhase.probing) return; _diagnosticLog.write('relay handshake timeout after 20s'); setState(() => _phase = ConnectionPhase.failed); _snack('中继握手超时:确认被控端也注册到同一信令服务器'); }); } /// 设备指纹校验(TOFU)。 /// /// 首次连接记录被控端公布的指纹;以后必须一致,不一致时弹窗让用户确认 /// (重装/换签名会变,中间人也会变)。被控端没公布指纹时拒绝连接。 Future _confirmFingerprint(DeviceInfo device) async { final key = device.id.trim().isNotEmpty ? device.id.trim() : '${device.ip}:${device.controlPort}'; final announced = device.fingerprint.trim(); if (announced.isEmpty) { _diagnosticLog.write('peer announced empty fp, reject missing fp ($key)'); _snack('被控端未公布指纹(旧版本),已拒绝连接,请更新被控端'); return false; } final pinned = _pins.pinOf(key); if (pinned == null) { _pins.pin(key, announced); _diagnosticLog.write('pinned device $key fp=$announced'); return true; } if (PinStore.same(pinned, announced)) return true; _diagnosticLog.write('fingerprint mismatch $key pinned=$pinned announced=$announced'); if (!mounted) return false; final trusted = await showDialog( context: context, builder: (context) => AlertDialog( title: const Text('设备指纹变化'), content: Text( '这台设备公布的指纹和上次记录的不一致。\n\n' '旧:$pinned\n新:$announced\n\n' '重装应用或更换签名会改指纹;如果不是你做的,请先取消并检查网络。', ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(false), child: const Text('取消连接'), ), FilledButton( onPressed: () => Navigator.of(context).pop(true), child: const Text('仍然信任'), ), ], ), ); if (trusted != true) { _diagnosticLog.write('fingerprint rejected by user: $key'); _snack('已拒绝连接:设备指纹不匹配'); return false; } _pins.pin(key, announced); _diagnosticLog.write('re-pinned device $key fp=$announced'); return true; } Future _disconnect() async { _diagnosticLog.write('disconnect requested'); _connectWatchdog?.cancel(); // 断开时连串流窗口一起关掉,否则重连后窗口还挂在那儿显示上一路的旧帧。 if (_videoWindowOpen) { _stopSentForWindowClose = true; final close = _bridge.closeVideoWindow(); _clearMirrorState(); await close; } await _bridge.disconnect(); if (!mounted) return; setState(() { _phase = ConnectionPhase.idle; _relayActive = false; // 断开后回到「未协商」状态,重连时按设置重新请求。 _grantedAccess = AccessLevel.view; _mediaProtocolAgreed = false; }); } Future _openSettings() async { final updated = await Navigator.of(context).push( MaterialPageRoute( builder: (_) => SettingsPage(settings: _settings, bridge: _bridge), ), ); if (updated == null) return; setState(() => _settings = updated); await _bridge.saveSettings(updated); await _applySignalingSettings(); // 已连接时立刻把新配置推给被控端,投屏中改码率/音频也能生效。 _applySessionConfig(); } Future _showPairing() => _showPairingDialog(); void _sendControl(String type, Map payload) { // 控制栏的「发送剪贴板」:payload 不带文本时读本机剪贴板实时内容。 if (type == 'clipboard' && payload['text'] == null) { unawaited(_sendLocalClipboard()); return; } unawaited(_bridge.sendControl(type, payload).catchError((Object error) { final now = DateTime.now(); final previous = _lastControlErrorAt; if (previous != null && now.difference(previous) < const Duration(seconds: 3)) return; _lastControlErrorAt = now; _diagnosticLog.write('control enqueue failed ($type): $error'); if (mounted) _snack('控制发送队列不可用,请重新连接被控端'); })); // 只有一次性动作才弹提示:触摸/鼠标/按键/滚轮是连续事件(拖拽时每秒几十条), // 每条都弹 SnackBar 会把 Flutter UI 线程压满,串流反而更卡。 const labels = { 'requestMirror': '投屏请求', 'stopMirror': '停止投屏', 'clipboard': '剪贴板内容', }; final label = labels[type]; if (label == null) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('已发送$label'), duration: const Duration(milliseconds: 900), ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('TTSTD Connect'), actions: [ IconButton( tooltip: '扫码配对', onPressed: _showPairing, icon: const Icon(Icons.qr_code_scanner), ), IconButton( tooltip: '设置', onPressed: _openSettings, icon: const Icon(Icons.settings), ), ], ), floatingActionButton: FloatingActionButton( onPressed: _showPairing, tooltip: '扫码配对', child: const Icon(Icons.add_link), ), body: LayoutBuilder( builder: (context, constraints) { if (constraints.maxWidth >= 1000) { return Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( width: 360, child: Card( margin: const EdgeInsets.all(12), clipBehavior: Clip.antiAlias, child: DeviceList( devices: _devices, selectedId: _selected?.id, onSelected: _selectDevice, onRefresh: _refreshDevices, onPair: _showPairingDialog, refreshing: _refreshing, ), ), ), const VerticalDivider(width: 1), Expanded(child: SingleChildScrollView(child: _buildStage())), ], ); } return SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( height: 360, child: Card( margin: const EdgeInsets.fromLTRB(12, 12, 12, 0), clipBehavior: Clip.antiAlias, child: DeviceList( devices: _devices, selectedId: _selected?.id, onSelected: _selectDevice, onRefresh: _refreshDevices, onPair: _showPairingDialog, refreshing: _refreshing, ), ), ), _buildStage(), ], ), ); }, ), ); } Widget _buildConnectionStatusCard() { final status = _demoStatus; final connected = status['peerConnected'] == true; final keyEstablished = status['keyEstablished'] == true; final relay = status['relay'] == true; final peerIp = (status['peerIp'] as String? ?? '').trim(); return Card( child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( children: [ const Icon(Icons.link, size: 18), const SizedBox(width: 8), const Text('连接状态', style: TextStyle(fontWeight: FontWeight.bold)), ], ), const SizedBox(height: 8), if (_nativeError != null) Text( _nativeError!, style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12), ) else Text( '${relay ? '信令中继' : '直连'} · ' '被控端 ${connected ? '已连接' : '未连接'} · ' '${keyEstablished ? '会话密钥已建立' : '等待 ECDH 协商'}' + (peerIp.isEmpty ? '' : ' · 对端 $peerIp'), style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 6), Text( "诊断日志:${_diagnosticLog.path.isEmpty ? '不可写' : _diagnosticLog.path}", style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 10), Row( children: [ FilledButton.tonalIcon( onPressed: _nativeError != null || _demoRunning ? null : _startDemoListener, icon: const Icon(Icons.dns_outlined, size: 18), label: const Text('启动本机监听'), ), const SizedBox(width: 8), OutlinedButton.icon( onPressed: _demoRunning ? _stopDemoListener : null, icon: const Icon(Icons.stop_circle_outlined, size: 18), label: const Text('停止'), ), const SizedBox(width: 12), Expanded( child: Text( _demoRunning ? 'TCP 41001 / UDP 41000 已监听,等待被控端接入' : '监听未开启:被控端无法反连本机', style: Theme.of(context).textTheme.bodySmall, overflow: TextOverflow.ellipsis, ), ), ], ), ], ), ), ); } bool get _demoRunning => _demoStatus['running'] == true; void _startDemoListener() { final started = _bridge.startDemoServer(); _diagnosticLog.write('demo listener start -> $started'); if (!mounted) return; setState(() { if (started) { _phase = ConnectionPhase.probing; } }); if (!started) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('启动本机监听失败:端口可能被占用')), ); } } void _stopDemoListener() { _bridge.stopDemoServer(); _diagnosticLog.write('demo listener stopped'); if (!mounted) return; setState(() => _phase = ConnectionPhase.idle); } String get _videoResolution { final width = _videoStats['width']; final height = _videoStats['height']; if (width is int && height is int && width > 0 && height > 0) { return '${width}x$height'; } return _selected?.resolution ?? ''; } String get _videoError => (_videoStats['error'] as String? ?? '').trim(); int get _videoFrames { final decoded = _videoStats['windowFrames']; return decoded is int ? decoded : 0; } Widget _buildStage() { return Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ ConnectBar( phase: _phase, device: _selected, onConnect: _connect, onDisconnect: _disconnect, ), const SizedBox(height: 12), MirrorBar( connected: _phase.isConnected, streaming: _videoStreaming, windowOpen: _videoWindowOpen, granted: _mirrorGranted, busy: _mirrorRequesting, resolution: _videoResolution, frames: _videoFrames, error: _videoError, onRequest: _requestMirror, ), const SizedBox(height: 12), ControlToolbar( enabled: _phase.isConnected, onEvent: _sendControl, ), const SizedBox(height: 8), Row( children: [ Icon( _grantedAccess.allowsFiles ? Icons.verified_user_outlined : Icons.lock_outline, size: 14, color: _phase.isConnected ? Theme.of(context).colorScheme.primary : Theme.of(context).disabledColor, ), const SizedBox(width: 6), Text( _phase.isConnected ? '权限:${_grantedAccess.label}(请求 ${_settings.access.label})' : '权限:未协商,连接后由被控端确认', style: Theme.of(context).textTheme.labelSmall, ), ], ), const SizedBox(height: 12), _buildFileTransferCard(), const SizedBox(height: 12), _buildConnectionStatusCard(), const SizedBox(height: 12), Card( child: Padding( padding: const EdgeInsets.all(12), child: Text( _settings.useLocalSignaling ? 'mDNS 同网段优先;本机信令${_localSignalingRunning ? '运行中' : '未运行'} · ${SignalingEndpoint.publicUrl(_effectiveSignalingUrl)},探测失败自动降级到信令中转。' : 'mDNS 同网段优先;外部信令 · ${SignalingEndpoint.publicUrl(_effectiveSignalingUrl)},探测失败自动降级到信令中转。', style: Theme.of(context).textTheme.bodySmall, ), ), ), const SizedBox(height: 8), Row( children: [ Icon( _watchConnected ? Icons.bolt : Icons.bolt_outlined, size: 14, color: _watchConnected ? Theme.of(context).colorScheme.primary : Theme.of(context).disabledColor, ), const SizedBox(width: 6), Text( _watchConnected ? '信令 /watch 实时订阅已连接' : '信令 /watch 未连接,仅靠轮询刷新', style: Theme.of(context).textTheme.labelSmall, ), ], ), ], ), ); } } /// Windows 虚拟键码(VK_*)→ Android KeyEvent keycode;不支持的键返回 null。 /// /// 只覆盖常见键:字母/数字/编辑键/方向键/功能键与标点。中文等文本输入依赖输入法, /// 注入按键无法替代,属于已知限制。 int? _androidKeycodeFromVk(int vk) { if (vk >= 0x41 && vk <= 0x5A) return 29 + (vk - 0x41); // A-Z if (vk >= 0x30 && vk <= 0x39) return 7 + (vk - 0x30); // 0-9 if (vk >= 0x70 && vk <= 0x7B) return 131 + (vk - 0x70); // F1-F12 return switch (vk) { 0x08 => 67, // Backspace 0x09 => 61, // Tab 0x0D => 66, // Enter 0x10 => 59, // Shift → KEYCODE_SHIFT_LEFT 0x11 => 113, // Ctrl → KEYCODE_CTRL_LEFT 0x12 => 57, // Alt → KEYCODE_ALT_LEFT 0x14 => 115, // CapsLock 0x1B => 111, // Escape 0x20 => 62, // Space 0x21 => 92, // PageUp 0x22 => 93, // PageDown 0x23 => 123, // End 0x24 => 122, // Home 0x25 => 21, // Left 0x26 => 19, // Up 0x27 => 22, // Right 0x28 => 20, // Down 0x2D => 124, // Insert 0x2E => 112, // Delete 0x5B || 0x5C => 117, // Win → KEYCODE_META_LEFT 0xBA => 74, // 分号 0xBB => 70, // 等号 0xBC => 55, // 逗号 0xBD => 69, // 减号 0xBE => 56, // 句点 0xBF => 76, // 斜杠 0xC0 => 68, // 反引号 0xDB => 71, // 左方括号 0xDC => 73, // 反斜杠 0xDD => 72, // 右方括号 0xDE => 75, // 单引号 _ => null, }; }