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

+26 -13
View File
@@ -5,6 +5,8 @@ class DiagnosticLog {
final String fileName;
File? _file;
Future<void> _writes = Future<void>.value();
int _pendingCharacters = 0;
String get path => _file?.path ?? '';
@@ -32,25 +34,36 @@ class DiagnosticLog {
}
void write(String message) {
message = message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]');
message =
message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]');
final file = _file;
if (file == null) return;
try {
if (file.lengthSync() > 2 * 1024 * 1024) {
file.writeAsStringSync(
'=== log rotated: ${DateTime.now().toIso8601String()} ===\n',
mode: FileMode.write,
flush: true,
final line = '${DateTime.now().toIso8601String()} $message\n';
// Slow disks must not block input/painting or create an unbounded log queue.
if (_pendingCharacters + line.length > 256 * 1024) return;
_pendingCharacters += line.length;
_writes = _writes.then((_) async {
try {
if (await file.length() > 2 * 1024 * 1024) {
await file.writeAsString(
'=== log rotated: ${DateTime.now().toIso8601String()} ===\n',
mode: FileMode.write,
);
}
await file.writeAsString(
line,
mode: FileMode.append,
);
} on Object catch (_) {
// Logging failure must not interrupt the stream or poison later writes.
} finally {
_pendingCharacters -= line.length;
}
file.writeAsStringSync(
'${DateTime.now().toIso8601String()} $message\n',
mode: FileMode.append,
flush: true,
);
} on Object catch (_) {}
});
}
Future<void> flush() => _writes;
void dispose() {
write('=== stopped ===');
_file = null;
+120
View File
@@ -0,0 +1,120 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:image/image.dart' as img;
import 'package:pasteboard/pasteboard.dart';
import 'package:zxing2/qrcode.dart';
import 'pairing.dart';
const maxPairingImageBytes = 16 * 1024 * 1024;
class PairingClipboardContent {
const PairingClipboardContent({this.text, this.image});
final String? text;
final Uint8List? image;
}
Future<PairingClipboardContent> readPairingClipboard() async {
final image = await Pasteboard.image;
if (image != null && image.isNotEmpty) {
if (image.length > maxPairingImageBytes)
throw const FormatException('图片过大,请复制较小的二维码截图(不超过 16 MB)');
return PairingClipboardContent(image: image);
}
final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
if (text != null && text.trim().isNotEmpty) {
if (text.length > 32768) throw const FormatException('配对文本过长,请只复制配对链接');
return PairingClipboardContent(text: text);
}
for (final path in await Pasteboard.files()) {
if (!RegExp(r'\.(png|jpe?g|bmp|webp|gif)$', caseSensitive: false)
.hasMatch(path)) continue;
final file = File(path);
if (await file.length() > maxPairingImageBytes)
throw const FormatException('图片过大,请使用不超过 16 MB 的图片');
final bytes = await file.readAsBytes();
if (bytes.length > maxPairingImageBytes)
throw const FormatException('图片过大');
return PairingClipboardContent(image: bytes);
}
throw const FormatException('剪贴板中没有配对文本或图片,请复制后重试');
}
PairingUri parsePairingText(String text) {
try {
final links =
RegExp(r'''lancast://pair\?[^\s<>"']+''', caseSensitive: false)
.allMatches(text)
.toList();
if (links.length > 1) throw const FormatException('检测到多个配对链接,请只粘贴一个设备的信息');
final pairing =
PairingUri.parse(links.isEmpty ? text : links.single.group(0)!);
if (pairing == null || InternetAddress.tryParse(pairing.ip) == null) {
throw const FormatException('配对链接无效,请检查 IP 地址和端口');
}
bool validDigest(String value) =>
RegExp(r'^(sha256:)?[0-9a-f]{64}$', caseSensitive: false)
.hasMatch(value);
if (!validDigest(pairing.fingerprint))
throw const FormatException('配对链接缺少有效的设备指纹,请重新复制被控端的配对信息');
if (pairing.tlsFingerprint.isNotEmpty &&
!validDigest(pairing.tlsFingerprint)) {
throw const FormatException('配对链接中的 TLS 指纹无效');
}
return pairing;
} on FormatException {
rethrow;
} on Object {
throw const FormatException('无法解析配对链接,请重新复制');
}
}
// Called in a background isolate only after the user confirms the preview.
PairingUri parsePairingImage(Uint8List bytes) {
if (bytes.isEmpty || bytes.length > maxPairingImageBytes)
throw const FormatException('图片大小无效');
final decoder = img.findDecoderForData(bytes);
final info = decoder?.startDecode(bytes);
if (info == null) throw const FormatException('无法读取图片,请粘贴 PNG、JPEG 或二维码截图');
if (info.width <= 0 ||
info.height <= 0 ||
info.width * info.height > 16000000) {
throw const FormatException('图片分辨率过大,请裁剪到二维码区域后重试');
}
var image = decoder!.decodeFrame(0);
if (image == null) throw const FormatException('图片已损坏或不受支持');
image = img.bakeOrientation(image);
if (image.width > 2048 || image.height > 2048) {
image = img.copyResize(image,
width: image.width >= image.height ? 2048 : null,
height: image.height > image.width ? 2048 : null);
}
// White background also handles transparent QR images correctly.
final flattened =
img.Image(width: image.width, height: image.height, numChannels: 4);
img.fill(flattened, color: img.ColorRgba8(255, 255, 255, 255));
img.compositeImage(flattened, image);
var oriented = flattened;
for (var rotation = 0; rotation < 4; rotation++) {
final pixels = oriented.getBytes(order: img.ChannelOrder.bgra);
final source = RGBLuminanceSource(
oriented.width,
oriented.height,
Int32List.view(
pixels.buffer, pixels.offsetInBytes, pixels.length ~/ 4));
String? text;
for (final candidate in [source, source.invert()]) {
try {
text = QRCodeReader()
.decode(BinaryBitmap(HybridBinarizer(candidate)))
.text;
break;
} on ReaderException {/* Try the other orientation/polarity. */}
}
if (text != null) return parsePairingText(text);
oriented = img.copyRotate(oriented, angle: 90);
}
throw const FormatException('未识别到二维码,请使用清晰、完整的单个配对二维码图片');
}
@@ -0,0 +1,136 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/pairing.dart';
import '../../core/pairing_input.dart';
class PairingPasteDialog extends StatefulWidget {
const PairingPasteDialog(
{super.key, this.readClipboard = readPairingClipboard, this.decodeImage});
final Future<PairingClipboardContent> Function() readClipboard;
final Future<PairingUri> Function(Uint8List)? decodeImage;
@override
State<PairingPasteDialog> createState() => _PairingPasteDialogState();
}
class _PairingPasteDialogState extends State<PairingPasteDialog> {
PairingClipboardContent? _content;
bool _busy = false;
String? _error;
Future<void> _paste() async {
if (_busy) return;
setState(() {
_busy = true;
_error = null;
});
try {
final content = await widget.readClipboard();
if (mounted) setState(() => _content = content);
} on Object catch (error) {
if (mounted)
setState(() {
_content = null;
_error = _message(error);
});
} finally {
if (mounted) setState(() => _busy = false);
}
}
String _message(Object error) =>
error is FormatException ? error.message : '读取或识别失败,请重新复制后重试';
Future<void> _confirm() async {
final content = _content;
if (_busy || content == null) return;
setState(() {
_busy = true;
_error = null;
});
try {
final image = content.image;
final PairingUri pairing;
if (image != null) {
pairing = await (widget.decodeImage?.call(image) ??
compute(parsePairingImage, image));
} else {
pairing = parsePairingText(content.text ?? '');
}
if (mounted) Navigator.of(context).pop(pairing);
} on Object catch (error) {
if (mounted) setState(() => _error = _message(error));
} finally {
if (mounted) setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
final image = _content?.image;
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.keyV, control: true): _paste,
const SingleActivator(LogicalKeyboardKey.keyV, meta: true): _paste,
},
child: Focus(
autofocus: true,
child: AlertDialog(
title: const Text('扫码配对'),
content: SizedBox(
width: 480,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('按 Ctrl+V 粘贴配对文本或二维码图片。核对预览后,点击确认配对进行识别和校验。'),
const SizedBox(height: 16),
Container(
constraints:
const BoxConstraints(minHeight: 140, maxHeight: 260),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: image == null ? null : Colors.white,
border: Border.all(
color: Theme.of(context).colorScheme.outline),
borderRadius: BorderRadius.circular(8)),
child: image != null
? Image.memory(image,
fit: BoxFit.contain,
cacheWidth: 640,
errorBuilder: (_, __, ___) =>
const Text('图片预览不可用,可点击确认尝试识别或重新粘贴'))
: SingleChildScrollView(
child: Text(_content?.text ?? '等待粘贴…')),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(_error!,
style: TextStyle(
color: Theme.of(context).colorScheme.error))),
if (_busy)
const Padding(
padding: EdgeInsets.only(top: 12),
child: LinearProgressIndicator()),
]),
),
),
actions: [
TextButton(
onPressed: _busy ? null : () => Navigator.of(context).pop(),
child: const Text('取消')),
TextButton(
onPressed: _busy ? null : _paste, child: const Text('粘贴')),
FilledButton(
onPressed: _busy || _content == null ? null : _confirm,
child: const Text('确认配对')),
],
),
),
);
}
}
+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,