feat(desktop): 支持粘贴配对并修复串流与设备切换

- 支持 Ctrl+V 粘贴配对文本和二维码图片,预览确认后识别校验
- 修复控制发送阻塞、TLS 读写争锁、设备切换沿用旧连接及串流误关窗
- 优化媒体加密上下文、UDP 接收缓冲和异步诊断日志
- 安装器按路径停止主控与信令进程,统一递增版本、打包和清理旧产物
- 发布 0.1.3+4,通过三端编译、20 项 Flutter 测试和 58 项 Rust 单元测试
This commit is contained in:
tongtong committed 2026-11-28 16:08:07 +08:00
1 parent f6b7730684
commit 3cd72d70e1
38 files changed
+1173 -196

No files matched your search

+69 -105
View File
@@ -17,6 +17,7 @@ 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';
@@ -76,6 +77,8 @@ class _HomePageState extends State<HomePage> {
List<DeviceInfo> _devices = const <DeviceInfo>[];
DeviceInfo? _selected;
bool _switchingDevice = false;
bool _pairingDialogOpen = false;
ConnectionPhase _phase = ConnectionPhase.idle;
AppSettings _settings = AppSettings.defaults;
String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl;
@@ -92,6 +95,7 @@ class _HomePageState extends State<HomePage> {
bool _videoStreaming = false;
int _lastWindowFrames = 0;
DateTime? _lastVideoFrameAt;
DateTime? _lastControlErrorAt;
DateTime? _mirrorRequestedAt;
DateTime? _mirrorGrantedAt;
int _videoWindowGeneration = 0;
@@ -131,7 +135,7 @@ class _HomePageState extends State<HomePage> {
}
_bridge.watchPhase().listen((phase) {
_diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})');
if (mounted) setState(() => _phase = phase);
if (mounted && !_switchingDevice) setState(() => _phase = phase);
});
_applySignalingSettings();
_refreshDevices();
@@ -189,7 +193,7 @@ class _HomePageState extends State<HomePage> {
}
void _refreshDemoStatus() {
if (_nativeCore == null || !mounted) return;
if (_nativeCore == null || !mounted || _switchingDevice) return;
try {
final wasConnected = _phase.isConnected;
final status = _bridge.demoStatus();
@@ -344,7 +348,7 @@ class _HomePageState extends State<HomePage> {
/// 被控端上行的剪贴板内容 → 写入本机剪贴板。
Future<void> _applyRemoteClipboard(String text) async {
if (text.isEmpty || !_settings.clipboardSync) return;
if (_pairingDialogOpen || text.isEmpty || !_settings.clipboardSync) return;
// 先记住这条内容,否则本机剪贴板轮询会把它当成「本机新复制」再发回去。
_lastClipboardText = text;
await Clipboard.setData(ClipboardData(text: text));
@@ -356,7 +360,7 @@ class _HomePageState extends State<HomePage> {
/// Windows 没有可订阅的剪贴板变更事件,只能定时读一次再和上次内容比较;
/// 内容与 [_lastClipboardText] 相同说明是刚同步过来的,不再回送。
Future<void> _syncLocalClipboard() async {
if (!mounted || _nativeCore == null) return;
if (!mounted || _nativeCore == null || _pairingDialogOpen) return;
if (!_phase.isConnected || !_settings.clipboardSync) return;
if (!_grantedAccess.allowsControl) return;
final ClipboardData? data;
@@ -366,6 +370,7 @@ class _HomePageState extends State<HomePage> {
// 剪贴板被别的程序占用(Office 等的延迟渲染)时读会抛错,下一轮再试。
return;
}
if (_pairingDialogOpen) return;
final text = data?.text;
if (text == null || text.isEmpty || text == _lastClipboardText) return;
_lastClipboardText = text;
@@ -454,9 +459,9 @@ class _HomePageState extends State<HomePage> {
final lastFrame = _lastVideoFrameAt;
final granted = _mirrorGrantedAt;
final requested = _mirrorRequestedAt;
if (lastFrame != null && now.difference(lastFrame) > const Duration(seconds: 5)) {
await _abortMirror('被控端已停止发送画面,请重新请求投屏');
} else if (lastFrame == null && granted != null && now.difference(granted) > const Duration(seconds: 15)) {
// 静止画面、网络抖动都可能暂时不产出新帧。保留窗口和会话,
// 恢复收帧后自动继续;只有明确停止/断连或首次授权超时才结束投屏。
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('等待投屏确认超时');
@@ -468,7 +473,7 @@ class _HomePageState extends State<HomePage> {
///
/// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。
Future<void> _requestMirror() async {
if (_videoWindowOpen || _mirrorRequesting) return;
if (_videoWindowOpen || _mirrorRequesting || _switchingDevice) return;
if (!_mediaProtocolAgreed) {
_snack('媒体加密协议尚未协商或版本不兼容,请升级两端后重新连接');
return;
@@ -802,7 +807,8 @@ class _HomePageState extends State<HomePage> {
setState(() {
_devices = devices;
if (_selected == null ||
!devices.any((device) => PairedDeviceStore.sameDevice(device, _selected!))) {
(!_phase.isConnected && _phase != ConnectionPhase.probing &&
!_switchingDevice && !devices.any((device) => PairedDeviceStore.sameDevice(device, _selected!)))) {
_selected = devices.isEmpty ? null : devices.first;
}
_refreshing = false;
@@ -829,52 +835,22 @@ class _HomePageState extends State<HomePage> {
/// 导入 `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;
if (_pairingDialogOpen) return;
_pairingDialogOpen = true;
PairingUri? pairing;
try {
pairing = await showDialog<PairingUri>(
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) {
@@ -887,21 +863,47 @@ class _HomePageState extends State<HomePage> {
);
setState(() {
_devices = _mergePaired(_devices);
_selected = device;
});
await _selectDevice(device);
_snack('已导入 ${device.name}');
}
static String _pinKeyOf(DeviceInfo device) =>
device.id.trim().isNotEmpty ? device.id.trim() : '${device.ip}:${device.controlPort}';
Future<void> _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<void> _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;
@@ -941,7 +943,7 @@ class _HomePageState extends State<HomePage> {
if (mounted) _snack('信令连接失败:$error');
return;
}
if (!mounted) return;
if (!mounted || _selected == null || !PairedDeviceStore.sameDevice(_selected!, device)) return;
final error = _bridge.startRelay(device, signalingUrl);
if (!mounted) return;
if (error != null) {
@@ -1052,52 +1054,7 @@ class _HomePageState extends State<HomePage> {
_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('关闭'),
),
],
),
);
}
Future<void> _showPairing() => _showPairingDialog();
void _sendControl(String type, Map<String, dynamic> payload) {
// 控制栏的「发送剪贴板」:payload 不带文本时读本机剪贴板实时内容。
@@ -1105,7 +1062,14 @@ class _HomePageState extends State<HomePage> {
unawaited(_sendLocalClipboard());
return;
}
_bridge.sendControl(type, payload);
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 = {
@@ -1160,7 +1124,7 @@ class _HomePageState extends State<HomePage> {
child: DeviceList(
devices: _devices,
selectedId: _selected?.id,
onSelected: (device) => setState(() => _selected = device),
onSelected: _selectDevice,
onRefresh: _refreshDevices,
onPair: _showPairingDialog,
refreshing: _refreshing,
@@ -1184,7 +1148,7 @@ class _HomePageState extends State<HomePage> {
child: DeviceList(
devices: _devices,
selectedId: _selected?.id,
onSelected: (device) => setState(() => _selected = device),
onSelected: _selectDevice,
onRefresh: _refreshDevices,
onPair: _showPairingDialog,
refreshing: _refreshing,