feat(desktop): 支持粘贴配对并修复串流与设备切换
- 支持 Ctrl+V 粘贴配对文本和二维码图片,预览确认后识别校验 - 修复控制发送阻塞、TLS 读写争锁、设备切换沿用旧连接及串流误关窗 - 优化媒体加密上下文、UDP 接收缓冲和异步诊断日志 - 安装器按路径停止主控与信令进程,统一递增版本、打包和清理旧产物 - 发布 0.1.3+4,通过三端编译、20 项 Flutter 测试和 58 项 Rust 单元测试
This commit is contained in:
1 parent
f6b7730684
commit
3cd72d70e1
38 files changed
+1173
-196
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <pasteboard/pasteboard_plugin.h>
|
||||
|
||||
void fl_register_plugins(FlPluginRegistry* registry) {
|
||||
g_autoptr(FlPluginRegistrar) pasteboard_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "PasteboardPlugin");
|
||||
pasteboard_plugin_register_with_registrar(pasteboard_registrar);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
pasteboard
|
||||
)
|
||||
|
||||
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import pasteboard
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin"))
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
archive:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: archive
|
||||
sha256: "2fda90592c0afd219c5e285618a98da835cd10df38372666093d25dfe457a2d0"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "4.7.1"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -25,6 +33,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.4.1"
|
||||
charcode:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: charcode
|
||||
sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
clock:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -65,6 +81,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
fixnum:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: fixnum
|
||||
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@@ -75,6 +99,19 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_web_plugins:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
image:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: image
|
||||
sha256: bc13f61f0f5cb77936e78ae5dae3800f442718dac5d2bc4654f03c239230ed0c
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "4.13.1"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -131,6 +168,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.19.0"
|
||||
pasteboard:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: pasteboard
|
||||
sha256: "7b1c7ed83b4ff27acced26e96b87c16ac37fb6c57d7886eb3130faccb28b2cc2"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.6.2"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -139,6 +184,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.9.1"
|
||||
posix:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: posix
|
||||
sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "6.5.4"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
@@ -192,6 +245,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.7.14"
|
||||
uuid:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: uuid
|
||||
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "4.6.0"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -208,6 +269,22 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "15.4.0"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web
|
||||
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
zxing2:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: zxing2
|
||||
sha256: "2677c49a3b9ca9457cb1d294fd4bd5041cac6aab8cdb07b216ba4e98945c684f"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.2.4"
|
||||
sdks:
|
||||
dart: ">=3.13.0-0 <4.0.0"
|
||||
flutter: ">=3.18.0-18.0.pre.54"
|
||||
dart: ">=3.13.0 <4.0.0"
|
||||
flutter: ">=3.44.0"
|
||||
@@ -1,7 +1,7 @@
|
||||
name: ttstd_sender
|
||||
description: TTSTDConnect 跨平台主控端(Flutter UI + Rust Core 桥接)
|
||||
publish_to: none
|
||||
version: 0.1.0+1
|
||||
version: 0.1.3+4
|
||||
|
||||
environment:
|
||||
sdk: '>=3.4.0 <4.0.0'
|
||||
@@ -11,6 +11,9 @@ dependencies:
|
||||
sdk: flutter
|
||||
ffi: ^2.1.0
|
||||
crypto: ^3.0.6
|
||||
pasteboard: ^0.6.2
|
||||
zxing2: ^0.2.4
|
||||
image: ^4.13.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ttstd_sender/core/diagnostic_log.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'asynchronous logs preserve order, redact tokens and finish after dispose',
|
||||
() async {
|
||||
final log = DiagnosticLog(
|
||||
'ttstd_log_test_${DateTime.now().microsecondsSinceEpoch}.log');
|
||||
log.start();
|
||||
final file = File(log.path);
|
||||
addTearDown(() async {
|
||||
await log.flush();
|
||||
if (await file.exists()) await file.delete();
|
||||
});
|
||||
log.write('first #token=secret');
|
||||
log.write('second');
|
||||
log.dispose();
|
||||
await log.flush();
|
||||
final text = await file.readAsString();
|
||||
expect(text, contains('first #token=[redacted]'));
|
||||
expect(text, isNot(contains('secret')));
|
||||
expect(text.indexOf('first'), lessThan(text.indexOf('second')));
|
||||
expect(text.indexOf('second'), lessThan(text.indexOf('=== stopped ===')));
|
||||
});
|
||||
|
||||
test('log rotation and failed writes do not prevent later writes', () async {
|
||||
final log = DiagnosticLog(
|
||||
'ttstd_log_test_${DateTime.now().microsecondsSinceEpoch}.log');
|
||||
log.start();
|
||||
final file = File(log.path);
|
||||
addTearDown(() async {
|
||||
log.dispose();
|
||||
await log.flush();
|
||||
if (await file.exists()) await file.delete();
|
||||
});
|
||||
await file.writeAsString('x' * (2 * 1024 * 1024 + 1));
|
||||
log.write('after rotation');
|
||||
await log.flush();
|
||||
expect(
|
||||
await file.readAsString(),
|
||||
allOf(contains('log rotated:'), contains('after rotation'),
|
||||
isNot(startsWith('xxx'))));
|
||||
await file.delete();
|
||||
log.write('unavailable file');
|
||||
await log.flush();
|
||||
await file.writeAsString('recovered\n');
|
||||
log.write('after recovery');
|
||||
await log.flush();
|
||||
expect(await file.readAsString(), contains('after recovery'));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ttstd_sender/core/pairing_input.dart';
|
||||
import '../fixtures/pairing_qr.dart';
|
||||
|
||||
void main() {
|
||||
test('parses pairing links in copied text and validates identity fields', () {
|
||||
expect(parsePairingText('配对信息:\n$pairingText\n').ip, '192.168.100.141');
|
||||
for (final invalid in [
|
||||
'hello',
|
||||
'$pairingText\n$pairingText',
|
||||
pairingText.replaceFirst('41001', '70000'),
|
||||
pairingText.replaceFirst('192.168.100.141', 'invalid'),
|
||||
'lancast://pair?ip=127.0.0.1&port=41001',
|
||||
'$pairingText&tls=invalid'
|
||||
]) {
|
||||
expect(() => parsePairingText(invalid), throwsFormatException);
|
||||
}
|
||||
});
|
||||
test('decodes color, grayscale and rotated QR images', () {
|
||||
for (final bytes in [
|
||||
pairingQr(),
|
||||
pairingQr(grayscale: true),
|
||||
pairingQr(rotate: true)
|
||||
]) {
|
||||
final result = parsePairingImage(bytes);
|
||||
expect(result.deviceId, 'test-qr');
|
||||
expect(result.ip, '192.168.100.141');
|
||||
}
|
||||
});
|
||||
test('rejects malformed or oversized image data', () {
|
||||
expect(() => parsePairingImage(Uint8List.fromList([1, 2, 3])),
|
||||
throwsFormatException);
|
||||
expect(() => parsePairingImage(Uint8List(maxPairingImageBytes + 1)),
|
||||
throwsFormatException);
|
||||
});
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:image/image.dart' as img;
|
||||
import 'package:zxing2/qrcode.dart';
|
||||
|
||||
final pairingText =
|
||||
'lancast://pair?ip=192.168.100.141&port=41001&fp=${'ab' * 32}&id=test-qr&name=Receiver';
|
||||
|
||||
Uint8List pairingQr({bool rotate = false, bool grayscale = false}) {
|
||||
final matrix = Encoder.encode(pairingText, ErrorCorrectionLevel.m).matrix!;
|
||||
const scale = 5, margin = 4;
|
||||
var image = img.Image(
|
||||
width: (matrix.width + margin * 2) * scale,
|
||||
height: (matrix.height + margin * 2) * scale,
|
||||
numChannels: grayscale ? 1 : 4);
|
||||
img.fill(image, color: img.ColorRgba8(255, 255, 255, 255));
|
||||
for (var y = 0; y < matrix.height; y++) {
|
||||
for (var x = 0; x < matrix.width; x++) {
|
||||
if (matrix.get(x, y) == 1) {
|
||||
img.fillRect(image,
|
||||
x1: (x + margin) * scale,
|
||||
y1: (y + margin) * scale,
|
||||
x2: (x + margin + 1) * scale - 1,
|
||||
y2: (y + margin + 1) * scale - 1,
|
||||
color: img.ColorRgba8(0, 0, 0, 255));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rotate) image = img.copyRotate(image, angle: 90);
|
||||
return img.encodePng(image);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ttstd_sender/core/pairing.dart';
|
||||
import 'package:ttstd_sender/core/pairing_input.dart';
|
||||
import 'package:ttstd_sender/features/discovery/pairing_paste_dialog.dart';
|
||||
import 'fixtures/pairing_qr.dart';
|
||||
|
||||
void main() {
|
||||
Future<void> open(WidgetTester tester, PairingPasteDialog dialog,
|
||||
void Function(PairingUri?) result) async {
|
||||
await tester.pumpWidget(MaterialApp(
|
||||
home: Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () async => result(await showDialog<PairingUri>(
|
||||
context: context, builder: (_) => dialog)),
|
||||
child: const Text('open'),
|
||||
))));
|
||||
await tester.tap(find.text('open'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('Ctrl+V previews text; only confirmation returns a pairing',
|
||||
(tester) async {
|
||||
PairingUri? result;
|
||||
await open(
|
||||
tester,
|
||||
PairingPasteDialog(
|
||||
readClipboard: () async =>
|
||||
PairingClipboardContent(text: pairingText)),
|
||||
(value) => result = value);
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyV);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(pairingText), findsOneWidget);
|
||||
expect(result, isNull);
|
||||
await tester.tap(find.text('确认配对'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(result?.ip, '192.168.100.141');
|
||||
});
|
||||
|
||||
testWidgets('pasting image does not decode until confirmation',
|
||||
(tester) async {
|
||||
var decodes = 0;
|
||||
PairingUri? result;
|
||||
await open(
|
||||
tester,
|
||||
PairingPasteDialog(
|
||||
readClipboard: () async =>
|
||||
PairingClipboardContent(image: pairingQr()),
|
||||
decodeImage: (_) async {
|
||||
decodes++;
|
||||
return parsePairingText(pairingText);
|
||||
},
|
||||
),
|
||||
(value) => result = value);
|
||||
await tester.tap(find.text('粘贴'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(Image), findsOneWidget);
|
||||
expect(decodes, 0);
|
||||
expect(result, isNull);
|
||||
await tester.tap(find.text('确认配对'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(decodes, 1);
|
||||
expect(result?.deviceId, 'test-qr');
|
||||
});
|
||||
|
||||
testWidgets('invalid text remains in dialog and can be replaced or cancelled',
|
||||
(tester) async {
|
||||
var text = 'invalid text';
|
||||
PairingUri? result;
|
||||
await open(
|
||||
tester,
|
||||
PairingPasteDialog(
|
||||
readClipboard: () async => PairingClipboardContent(text: text)),
|
||||
(value) => result = value);
|
||||
await tester.tap(find.text('粘贴'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('配对链接无效'), findsNothing);
|
||||
await tester.tap(find.text('确认配对'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('配对链接无效'), findsOneWidget);
|
||||
expect(find.byType(PairingPasteDialog), findsOneWidget);
|
||||
text = pairingText;
|
||||
await tester.tap(find.text('粘贴'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('配对链接无效'), findsNothing);
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(result, isNull);
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ttstd_sender/core/models.dart';
|
||||
import 'package:ttstd_sender/main.dart';
|
||||
import 'package:ttstd_sender/features/session/connect_bar.dart';
|
||||
import 'package:ttstd_sender/features/session/mirror_bar.dart';
|
||||
|
||||
const MethodChannel _methodChannel = MethodChannel('ttstd/sender');
|
||||
const EventChannel _eventChannel = EventChannel('ttstd/sender/events');
|
||||
@@ -22,7 +26,8 @@ DeviceInfo _testDevice() => const DeviceInfo(
|
||||
);
|
||||
|
||||
void _mockChannels({List<DeviceInfo> devices = const [], String? pairingUri}) {
|
||||
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(_methodChannel, (call) async {
|
||||
switch (call.method) {
|
||||
case 'discover':
|
||||
@@ -41,11 +46,69 @@ void _mockChannels({List<DeviceInfo> devices = const [], String? pairingUri}) {
|
||||
|
||||
void main() {
|
||||
tearDown(() {
|
||||
final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(_methodChannel, null);
|
||||
messenger.setMockStreamHandler(_eventChannel, null);
|
||||
});
|
||||
|
||||
testWidgets('切换设备先断开旧连接,发现刷新不替换活动设备', (tester) async {
|
||||
final first = _testDevice();
|
||||
const second = DeviceInfo(
|
||||
id: 'second-device',
|
||||
name: '另一设备',
|
||||
ip: '192.168.100.141',
|
||||
mediaPort: 41000,
|
||||
controlPort: 41001,
|
||||
fingerprint: 'second-fingerprint',
|
||||
);
|
||||
final devices = [first, second];
|
||||
final disconnected = Completer<void>();
|
||||
var disconnectCalls = 0;
|
||||
late void Function(Object?) emitPhase;
|
||||
_mockChannels(devices: devices);
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(_methodChannel, (call) async {
|
||||
if (call.method == 'discover')
|
||||
return devices.map((device) => device.toJson()).toList();
|
||||
if (call.method == 'disconnect') {
|
||||
disconnectCalls++;
|
||||
await disconnected.future;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
messenger.setMockStreamHandler(_eventChannel, MockStreamHandler.inline(
|
||||
onListen: (arguments, events) {
|
||||
emitPhase = events.success;
|
||||
},
|
||||
));
|
||||
await tester.pumpWidget(const TTSTDConnectApp());
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
emitPhase('direct');
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
expect(tester.widget<MirrorBar>(find.byType(MirrorBar)).connected, isTrue);
|
||||
devices.remove(first);
|
||||
await tester.tap(find.byIcon(Icons.refresh));
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
expect(tester.widget<ConnectBar>(find.byType(ConnectBar)).device?.id,
|
||||
first.id);
|
||||
|
||||
await tester.tap(find.text('另一设备'));
|
||||
await tester.pump();
|
||||
expect(disconnectCalls, 1);
|
||||
expect(tester.widget<MirrorBar>(find.byType(MirrorBar)).connected, isFalse);
|
||||
expect(tester.widget<ConnectBar>(find.byType(ConnectBar)).device?.id,
|
||||
first.id);
|
||||
disconnected.complete();
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
final bar = tester.widget<ConnectBar>(find.byType(ConnectBar));
|
||||
expect(bar.device?.ip, '192.168.100.141');
|
||||
expect(bar.phase, ConnectionPhase.idle);
|
||||
expect(tester.widget<MirrorBar>(find.byType(MirrorBar)).connected, isFalse);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('首页无设备时显示空态', (tester) async {
|
||||
_mockChannels();
|
||||
await tester.pumpWidget(const TTSTDConnectApp());
|
||||
@@ -69,28 +132,22 @@ void main() {
|
||||
expect(find.text('可连接设备'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('扫码配对对话框展示原生返回的 pairing URI', (tester) async {
|
||||
const uri = 'lancast://pair?ip=10.0.0.2&port=41001&fp=test-fingerprint';
|
||||
_mockChannels(pairingUri: uri);
|
||||
await tester.pumpWidget(const TTSTDConnectApp());
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
await tester.tap(find.byTooltip('扫码配对').first);
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
expect(find.text('扫码配对'), findsOneWidget);
|
||||
expect(find.text(uri), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('配对码不可用时提示而不展示假 URI', (tester) async {
|
||||
testWidgets('扫码配对入口打开粘贴窗口,不依赖原生扫码', (tester) async {
|
||||
_mockChannels();
|
||||
await tester.pumpWidget(const TTSTDConnectApp());
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
await tester.tap(find.byTooltip('扫码配对').first);
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
|
||||
expect(find.text('当前平台不支持扫码配对'), findsOneWidget);
|
||||
expect(find.text('确认配对'), findsOneWidget);
|
||||
expect(find.textContaining('Ctrl+V'), findsOneWidget);
|
||||
expect(find.text('等待粘贴…'), findsOneWidget);
|
||||
expect(
|
||||
tester
|
||||
.widget<FilledButton>(find.widgetWithText(FilledButton, '确认配对'))
|
||||
.onPressed,
|
||||
isNull);
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle(_settleTimeout);
|
||||
});
|
||||
|
||||
testWidgets('设置页可切换本机信令与外部信令', (tester) async {
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <pasteboard/pasteboard_plugin.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
PasteboardPluginRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("PasteboardPlugin"));
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
pasteboard
|
||||
)
|
||||
|
||||
list(APPEND FLUTTER_FFI_PLUGIN_LIST
|
||||
|
||||
@@ -907,6 +907,10 @@ class VideoTexturePlugin : public flutter::Plugin {
|
||||
}
|
||||
|
||||
~VideoTexturePlugin() override {
|
||||
stop_.store(true);
|
||||
if (worker_.joinable()) {
|
||||
worker_.join();
|
||||
}
|
||||
// 先摘掉回调,避免析构期间 DestroyWindow 触发 InvokeMethod。
|
||||
video_window_.SetCloseHandler(nullptr);
|
||||
video_window_.SetInputHandler(nullptr);
|
||||
@@ -914,10 +918,6 @@ class VideoTexturePlugin : public flutter::Plugin {
|
||||
video_window_.SetWheelHandler(nullptr);
|
||||
video_window_.SetKeyboardHandler(nullptr);
|
||||
video_window_.Close();
|
||||
stop_.store(true);
|
||||
if (worker_.joinable()) {
|
||||
worker_.join();
|
||||
}
|
||||
if (texture_registrar_ != nullptr && texture_id_ != 0) {
|
||||
texture_registrar_->UnregisterTexture(texture_id_,
|
||||
std::function<void()>());
|
||||
@@ -1028,7 +1028,7 @@ class VideoTexturePlugin : public flutter::Plugin {
|
||||
? decoded - window_start_frame_
|
||||
: 0));
|
||||
map[flutter::EncodableValue("pending")] =
|
||||
flutter::EncodableValue(static_cast<int64_t>(api_.Pending()));
|
||||
flutter::EncodableValue(pending_count_.load());
|
||||
map[flutter::EncodableValue("received")] =
|
||||
flutter::EncodableValue(static_cast<int64_t>(received_));
|
||||
map[flutter::EncodableValue("width")] =
|
||||
@@ -1037,7 +1037,11 @@ class VideoTexturePlugin : public flutter::Plugin {
|
||||
flutter::EncodableValue(static_cast<int64_t>(height));
|
||||
map[flutter::EncodableValue("pts")] =
|
||||
flutter::EncodableValue(static_cast<int64_t>(frames_->pts()));
|
||||
std::string error = api_.error() + decoder_.error();
|
||||
std::string error;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(diagnostic_mutex_);
|
||||
error = diagnostic_error_;
|
||||
}
|
||||
if (error.empty() && !saw_codec_config_.load() && keyframes_.load() > 0 &&
|
||||
frames_->frames() == 0) {
|
||||
// 关键帧都收到了却始终没有 SPS/PPS,解码器会一直「吃数据不出图」且不报错,
|
||||
@@ -1071,6 +1075,13 @@ class VideoTexturePlugin : public flutter::Plugin {
|
||||
bool has_pending = false;
|
||||
|
||||
while (!stop_.load()) {
|
||||
// API function pointers and decoder strings belong to the worker thread.
|
||||
// Publish a protected snapshot instead of reading them from the UI thread.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(diagnostic_mutex_);
|
||||
diagnostic_error_ = api_.error() + decoder_.error();
|
||||
}
|
||||
pending_count_.store(static_cast<int64_t>(api_.Pending()));
|
||||
if (!has_pending) {
|
||||
if (!api_.EnsureLoaded()) {
|
||||
Sleep(kRetrySleepMs);
|
||||
@@ -1162,6 +1173,9 @@ class VideoTexturePlugin : public flutter::Plugin {
|
||||
bool closing_from_channel_ = false;
|
||||
RustVideoApi api_;
|
||||
VideoDecoder decoder_;
|
||||
std::mutex diagnostic_mutex_;
|
||||
std::string diagnostic_error_;
|
||||
std::atomic<int64_t> pending_count_{0};
|
||||
std::atomic<bool> stop_{false};
|
||||
std::thread worker_;
|
||||
int64_t texture_id_ = 0;
|
||||
|
||||
@@ -88,7 +88,7 @@ class VideoWindow {
|
||||
void EnsureBackBuffer(HDC reference, int width, int height);
|
||||
void ReleaseBackBuffer();
|
||||
|
||||
HWND hwnd_ = nullptr;
|
||||
std::atomic<HWND> hwnd_{nullptr};
|
||||
std::atomic<bool> open_{false};
|
||||
std::atomic<bool> repaint_pending_{false};
|
||||
FrameProvider provider_;
|
||||
|
||||
Reference in new issue
Block a user