- relay 信封新增 kind=media(video/audio 两个 base64 数组),可省略空数组 - rust_core:媒体分片经 AES-256-GCM(AAD=relay-media)加密,中继读循环解密后复用 UDP 的重组/解码路径 - rust_core:把 UDP 单包消费逻辑抽成 consume_media_packet,直连与中继共用,避免两套解码行为 - android_receiver:SessionCrypto 增加 encodeRelayMedia(随机 12B nonce + 密文 + tag) - android_receiver:中继模式下媒体分片入队,由独立线程每 40ms 批量发送,积压丢最旧避免延迟累积 - android_receiver:移除中继拒绝投屏的分支,投屏请求与直连一致 - flutter_sender:解除「中继不能投屏」的界面限制与文案 - docs:README/AGENTS 补充 media 信封、加密方式与延迟取舍
1401 lines
50 KiB
Dart
1401 lines
50 KiB
Dart
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/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/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<HomePage> createState() => _HomePageState();
|
||
}
|
||
|
||
class _HomePageState extends State<HomePage> {
|
||
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.full;
|
||
/// 权限不足提示的去抖时间,避免连续手势把 SnackBar 刷爆。
|
||
DateTime? _lastAccessWarnAt;
|
||
|
||
List<DeviceInfo> _devices = const <DeviceInfo>[];
|
||
DeviceInfo? _selected;
|
||
ConnectionPhase _phase = ConnectionPhase.idle;
|
||
AppSettings _settings = AppSettings.defaults;
|
||
String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl;
|
||
bool _localSignalingRunning = false;
|
||
bool _refreshing = false;
|
||
Map<String, dynamic> _demoStatus = const <String, dynamic>{'running': false};
|
||
Map<String, dynamic> _videoStats = const <String, dynamic>{};
|
||
int? _textureId;
|
||
/// 串流画面是否已弹出到独立原生窗口。
|
||
bool _videoWindowOpen = false;
|
||
/// 正在拉起窗口并下发投屏请求。
|
||
bool _mirrorRequesting = false;
|
||
/// 最近一次统计到的累计解码帧数,用于判断是否还在收画面。
|
||
int _lastDecoded = 0;
|
||
/// 最近一次收到新帧的时间;超过 [streamingIdleTimeout] 视为已停止推流。
|
||
DateTime? _lastFrameAt;
|
||
/// 因关窗而停流只下发一次 stopMirror。
|
||
bool _stopSentForWindowClose = false;
|
||
/// 最近一次同步过的剪贴板文本(收/发都记),用来避免两端来回回送同一条内容。
|
||
String? _lastClipboardText;
|
||
|
||
static const Duration streamingIdleTimeout = Duration(seconds: 2);
|
||
String? _nativeError;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
try {
|
||
_nativeCore = NativeCore();
|
||
} on Object catch (error) {
|
||
_nativeError = error.toString();
|
||
}
|
||
_bridge = SenderBridge(nativeCore: _nativeCore);
|
||
// 独立窗口被用户关闭 → 停止投屏。
|
||
_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 <DeviceInfo>[]);
|
||
}
|
||
_bridge.watchPhase().listen((phase) {
|
||
_diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})');
|
||
if (mounted) 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) 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 (sessionEnded) {
|
||
// 中继线程退出后 status 不再有进行中的会话,别把界面卡在「连接中」。
|
||
_phase = ConnectionPhase.idle;
|
||
} else if ((running || relay) &&
|
||
_phase != ConnectionPhase.idle &&
|
||
_phase != ConnectionPhase.failed) {
|
||
_phase = ConnectionPhase.probing;
|
||
}
|
||
});
|
||
if (sessionEnded) _snack('中继会话已断开');
|
||
// 刚连上时主动下发一次会话配置,顺带把权限等级请求发过去;
|
||
// 被控端会用 msgType=10 回送裁剪后的有效等级。
|
||
if (!wasConnected && _phase.isConnected) {
|
||
_grantedAccess = _settings.access;
|
||
_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<String, dynamic> 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');
|
||
switch (action) {
|
||
case 2:
|
||
_snack('被控端已允许投屏');
|
||
case 3:
|
||
unawaited(_abortMirror(text.isEmpty ? '被控端拒绝了投屏请求' : '被控端拒绝了投屏请求:$text'));
|
||
case 4:
|
||
unawaited(_abortMirror('被控端已停止投屏'));
|
||
case 5:
|
||
unawaited(_abortMirror(text.isEmpty ? '被控端投屏失败' : '被控端投屏失败:$text'));
|
||
}
|
||
}
|
||
|
||
/// 投屏没建立起来或对端已停流:关掉独立窗口,避免一直停在「等待画面」。
|
||
///
|
||
/// [_stopSentForWindowClose] 置位是必须的——窗口是我们自己关的,
|
||
/// 不能再给对端补发一条 stopMirror。
|
||
Future<void> _abortMirror(String message) async {
|
||
_stopSentForWindowClose = true;
|
||
if (_videoWindowOpen) {
|
||
await _bridge.closeVideoWindow();
|
||
}
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_videoWindowOpen = false;
|
||
_lastFrameAt = null;
|
||
});
|
||
_snack(message);
|
||
}
|
||
|
||
/// 被控端回送的权限等级(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;
|
||
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<void> _applyRemoteClipboard(String text) async {
|
||
if (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<void> _syncLocalClipboard() async {
|
||
if (!mounted || _nativeCore == null) 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;
|
||
}
|
||
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<void> _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 = <String, dynamic>{
|
||
'preferH265': _settings.preferH265,
|
||
'bitrateMbps': _settings.bitrateMbps,
|
||
'audioEnabled': _settings.audioEnabled,
|
||
'clipboardSync': _settings.clipboardSync,
|
||
// 权限只能「请求」:被控端会按本机上限裁剪并用 msgType=10 回送有效等级。
|
||
'access': _settings.access.code,
|
||
};
|
||
_bridge.sendControl('sessionConfig', payload);
|
||
_diagnosticLog.write('sessionConfig sent: $payload');
|
||
}
|
||
|
||
/// 首帧前先取一次纹理 ID,避免等待轮询。
|
||
Future<void> _refreshVideoTextureId() async {
|
||
final id = await _bridge.videoTextureId();
|
||
if (!mounted || id == null || id == _textureId) return;
|
||
setState(() => _textureId = id);
|
||
}
|
||
|
||
/// 轮询原生解码统计:纹理 ID、分辨率、PTS 与失败原因。
|
||
Future<void> _refreshVideoStats() async {
|
||
if (!mounted) return;
|
||
final stats = await _bridge.videoStats();
|
||
if (!mounted || stats.isEmpty) return;
|
||
final id = stats['textureId'];
|
||
final windowOpen = stats['windowOpen'];
|
||
final decoded = stats['decoded'];
|
||
final decodedCount = decoded is int ? decoded : 0;
|
||
|
||
// 帧计数变化说明还在收画面;累计值不变就说明推流已停。
|
||
final framesAdvanced = decodedCount != _lastDecoded;
|
||
// 原生窗口被用户关掉(方法通道回调丢失时的兜底)。
|
||
final closedByUser = windowOpen is bool && !windowOpen && _videoWindowOpen;
|
||
|
||
setState(() {
|
||
_videoStats = stats;
|
||
if (_textureId == null && id is int && id > 0) {
|
||
_textureId = id;
|
||
}
|
||
if (windowOpen is bool) {
|
||
_videoWindowOpen = windowOpen;
|
||
}
|
||
if (framesAdvanced) {
|
||
_lastDecoded = decodedCount;
|
||
_lastFrameAt = DateTime.now();
|
||
}
|
||
if (closedByUser) {
|
||
_lastFrameAt = null;
|
||
}
|
||
});
|
||
|
||
if (closedByUser) {
|
||
await _onStreamWindowClosed();
|
||
}
|
||
}
|
||
|
||
/// 请求投屏:先把独立串流窗口打开,再向被控端下发投屏请求。
|
||
///
|
||
/// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。
|
||
Future<void> _requestMirror() async {
|
||
if (!_phase.isConnected) {
|
||
_snack('请先连接被控端');
|
||
return;
|
||
}
|
||
setState(() {
|
||
_mirrorRequesting = true;
|
||
// 新一轮请求:清掉上一轮「关窗已停流」的标记与旧帧时间。
|
||
_stopSentForWindowClose = false;
|
||
_lastFrameAt = null;
|
||
});
|
||
try {
|
||
if (!_videoWindowOpen) {
|
||
final size = _deviceScreenSize();
|
||
final opened = await _bridge.openVideoWindow(
|
||
width: size?.$1,
|
||
height: size?.$2,
|
||
);
|
||
if (!mounted) return;
|
||
if (!opened) {
|
||
_snack('当前平台不支持独立串流窗口');
|
||
return;
|
||
}
|
||
setState(() => _videoWindowOpen = true);
|
||
}
|
||
// 先下发会话配置,被控端据此决定编码器参数后再开流。
|
||
_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<void> _onStreamWindowClosed() async {
|
||
if (!mounted) return;
|
||
if (_stopSentForWindowClose) return;
|
||
_stopSentForWindowClose = true;
|
||
|
||
setState(() {
|
||
_videoWindowOpen = false;
|
||
_lastFrameAt = null;
|
||
});
|
||
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<void> _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<void>(
|
||
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<String, dynamic> status;
|
||
if (_nativeCore == null) {
|
||
status = <String, dynamic>{'available': false, 'error': _nativeError ?? ''};
|
||
} else {
|
||
try {
|
||
status = _bridge.demoStatus();
|
||
} on Object catch (error) {
|
||
status = <String, dynamic>{'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=$_effectiveSignalingUrl; '
|
||
'nativeError=${_nativeError ?? '-'}; textureId=${_textureId ?? '-'}; '
|
||
'video=$_videoStats; demoStatus=$status',
|
||
);
|
||
}
|
||
|
||
Future<void> _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<void> _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 ||
|
||
!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<DeviceInfo> _mergePaired(List<DeviceInfo> discovered) {
|
||
final merged = <DeviceInfo>[...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<void> _showPairingDialog() async {
|
||
final controller = TextEditingController();
|
||
final text = await showDialog<String>(
|
||
context: context,
|
||
builder: (context) => AlertDialog(
|
||
title: const Text('导入配对信息'),
|
||
content: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
const Text(
|
||
'用手机扫描被控端界面上的二维码,把得到的链接粘贴到这里;'
|
||
'也可以让被控端把链接文本发给你。',
|
||
style: TextStyle(fontSize: 13),
|
||
),
|
||
const SizedBox(height: 12),
|
||
TextField(
|
||
controller: controller,
|
||
autofocus: true,
|
||
minLines: 1,
|
||
maxLines: 3,
|
||
decoration: const InputDecoration(
|
||
labelText: 'lancast://pair?...',
|
||
hintText: 'lancast://pair?ip=192.168.1.10&port=41001&fp=...',
|
||
),
|
||
),
|
||
],
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
child: const Text('取消'),
|
||
),
|
||
FilledButton(
|
||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||
child: const Text('导入'),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
controller.dispose();
|
||
if (text == null || text.trim().isEmpty) return;
|
||
final pairing = PairingUri.parse(text);
|
||
if (pairing == null) {
|
||
_snack('配对信息无法识别,请确认粘贴的是 lancast://pair?... 链接');
|
||
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);
|
||
_selected = device;
|
||
});
|
||
_snack('已导入 ${device.name}');
|
||
}
|
||
|
||
static String _pinKeyOf(DeviceInfo device) =>
|
||
device.id.trim().isNotEmpty ? device.id.trim() : '${device.ip}:${device.controlPort}';
|
||
|
||
Future<void> _connect() async {
|
||
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 (_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<void> _connectViaRelay(DeviceInfo device) async {
|
||
final signalingUrl = await _bridge.resolveSignalingUrl(_settings);
|
||
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<bool> _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, skip pinning ($key)');
|
||
_snack('被控端未公布指纹(旧版本),本次连接未经身份校验');
|
||
return true;
|
||
}
|
||
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<bool>(
|
||
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<void> _disconnect() async {
|
||
_diagnosticLog.write('disconnect requested');
|
||
_connectWatchdog?.cancel();
|
||
// 断开时连串流窗口一起关掉,否则重连后窗口还挂在那儿显示上一路的旧帧。
|
||
if (_videoWindowOpen) {
|
||
_stopSentForWindowClose = true;
|
||
await _bridge.closeVideoWindow();
|
||
_videoWindowOpen = false;
|
||
_lastFrameAt = null;
|
||
}
|
||
await _bridge.disconnect();
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_phase = ConnectionPhase.idle;
|
||
_relayActive = false;
|
||
// 断开后回到「未协商」状态,重连时按设置重新请求。
|
||
_grantedAccess = _settings.access;
|
||
});
|
||
}
|
||
|
||
Future<void> _openSettings() async {
|
||
final updated = await Navigator.of(context).push<AppSettings>(
|
||
MaterialPageRoute(
|
||
builder: (_) => SettingsPage(settings: _settings, bridge: _bridge),
|
||
),
|
||
);
|
||
if (updated == null) return;
|
||
setState(() => _settings = updated);
|
||
await _bridge.saveSettings(updated);
|
||
await _applySignalingSettings();
|
||
// 已连接时立刻把新配置推给被控端,投屏中改码率/音频也能生效。
|
||
_applySessionConfig();
|
||
}
|
||
|
||
Future<void> _showPairing() async {
|
||
final uri = await _bridge.pairingUri();
|
||
if (!mounted) return;
|
||
if (uri == null) {
|
||
ScaffoldMessenger.of(context).showSnackBar(
|
||
const SnackBar(content: Text('当前平台不支持扫码配对')),
|
||
);
|
||
return;
|
||
}
|
||
showDialog<void>(
|
||
context: context,
|
||
builder: (context) => AlertDialog(
|
||
title: const Text('扫码配对'),
|
||
content: SingleChildScrollView(
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
Container(
|
||
width: 180,
|
||
height: 180,
|
||
decoration: BoxDecoration(
|
||
color: Colors.white,
|
||
borderRadius: BorderRadius.circular(12),
|
||
),
|
||
child: const Icon(Icons.qr_code_2, size: 140, color: Colors.black87),
|
||
),
|
||
const SizedBox(height: 16),
|
||
SelectableText(uri, textAlign: TextAlign.center),
|
||
const SizedBox(height: 12),
|
||
Text(
|
||
'首次连接需在被控端确认指纹;配对时可选择“仅查看 / 查看+控制 / 全权限”。',
|
||
style: Theme.of(context).textTheme.bodySmall,
|
||
textAlign: TextAlign.center,
|
||
),
|
||
],
|
||
),
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () => Navigator.of(context).pop(),
|
||
child: const Text('关闭'),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
void _sendControl(String type, Map<String, dynamic> payload) {
|
||
// 控制栏的「发送剪贴板」:payload 不带文本时读本机剪贴板实时内容。
|
||
if (type == 'clipboard' && payload['text'] == null) {
|
||
unawaited(_sendLocalClipboard());
|
||
return;
|
||
}
|
||
_bridge.sendControl(type, payload);
|
||
// 只有一次性动作才弹提示:触摸/鼠标/按键/滚轮是连续事件(拖拽时每秒几十条),
|
||
// 每条都弹 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: (device) => setState(() => _selected = device),
|
||
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: (device) => setState(() => _selected = device),
|
||
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['decoded'];
|
||
return decoded is int ? decoded : 0;
|
||
}
|
||
|
||
/// 是否正在接收画面。
|
||
///
|
||
/// 三个条件同时满足才算:独立窗口还开着、没有解码错误、最近 [streamingIdleTimeout]
|
||
/// 内还有新帧。累计帧数只增不减,单看它会导致关窗后永远显示「接收画面中」。
|
||
bool get _videoStreaming {
|
||
if (!_videoWindowOpen || _videoError.isNotEmpty) return false;
|
||
final last = _lastFrameAt;
|
||
if (last == null) return false;
|
||
return DateTime.now().difference(last) < streamingIdleTimeout;
|
||
}
|
||
|
||
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,
|
||
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 ? '运行中' : '未运行'} · $_effectiveSignalingUrl,探测失败自动降级到信令中转。'
|
||
: 'mDNS 同网段优先;外部信令 · $_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,
|
||
};
|
||
}
|