- SnackBar 只保留 requestMirror / stopMirror / clipboard 这类一次性动作 - 拖拽时触摸事件每秒几十条,每条弹一次提示会把 Flutter UI 线程压满, 既刷屏又拖慢串流
801 lines
27 KiB
Dart
801 lines
27 KiB
Dart
import 'dart:async';
|
||
import 'dart:io';
|
||
|
||
import 'package:flutter/material.dart';
|
||
|
||
import 'core/bridge.dart';
|
||
import 'core/diagnostic_log.dart';
|
||
import 'core/native_core.dart';
|
||
import 'core/models.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();
|
||
Timer? _demoStatusTimer;
|
||
Timer? _diagnosticTimer;
|
||
Timer? _connectWatchdog;
|
||
Timer? _discoveryTimer;
|
||
Timer? _videoStatsTimer;
|
||
|
||
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;
|
||
|
||
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;
|
||
_diagnosticLog.start();
|
||
_diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}');
|
||
_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(),
|
||
);
|
||
_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();
|
||
_diagnosticLog.dispose();
|
||
_bridge.stopDemoServer();
|
||
_bridge.stopLocalSignaling();
|
||
_nativeCore?.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
void _refreshDemoStatus() {
|
||
if (_nativeCore == null || !mounted) return;
|
||
try {
|
||
final status = _bridge.demoStatus();
|
||
setState(() {
|
||
_demoStatus = status;
|
||
final running = status['running'] == true;
|
||
final connected = status['peerConnected'] == true;
|
||
final keyEstablished = status['keyEstablished'] == true;
|
||
if (running && connected && keyEstablished) {
|
||
_connectWatchdog?.cancel();
|
||
_phase = ConnectionPhase.direct;
|
||
} else if (running &&
|
||
_phase != ConnectionPhase.idle &&
|
||
_phase != ConnectionPhase.failed) {
|
||
_phase = ConnectionPhase.probing;
|
||
}
|
||
});
|
||
} on Object catch (error) {
|
||
_diagnosticLog.write('demoStatus refresh failed: $error');
|
||
}
|
||
}
|
||
|
||
/// 首帧前先取一次纹理 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);
|
||
}
|
||
_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) return;
|
||
_sendControl('touch', {
|
||
'action': action,
|
||
'pointerId': 1,
|
||
'x': x,
|
||
'y': y,
|
||
// 按下/拖动保持满压力,抬起与取消归零。
|
||
'pressure': (action == 0 || action == 2) ? 1000 : 0,
|
||
});
|
||
}
|
||
|
||
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 ? _openFileBrowser : null,
|
||
icon: const Icon(Icons.folder_open, size: 18),
|
||
label: const Text('浏览被控端文件'),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
/// 文件服务要连的被控端地址。
|
||
///
|
||
/// 优先用设备列表里的局域网 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 (_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,
|
||
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);
|
||
unawaited(_refreshDevices());
|
||
}
|
||
|
||
Future<void> _refreshDevices() async {
|
||
if (_refreshing) return;
|
||
setState(() => _refreshing = true);
|
||
final devices = await _bridge.discover(signalingUrl: _effectiveSignalingUrl);
|
||
if (!mounted) return;
|
||
setState(() {
|
||
_devices = devices;
|
||
if (_selected == null || !devices.any((device) => device.id == _selected!.id)) {
|
||
_selected = devices.isEmpty ? null : devices.first;
|
||
}
|
||
_refreshing = false;
|
||
});
|
||
_diagnosticLog.write('discover result: ${devices.length} devices');
|
||
}
|
||
|
||
Future<void> _connect() async {
|
||
final device = _selected;
|
||
if (device == null) return;
|
||
_diagnosticLog.write(
|
||
'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}',
|
||
);
|
||
_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> _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);
|
||
}
|
||
|
||
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();
|
||
}
|
||
|
||
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) {
|
||
_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,
|
||
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,
|
||
refreshing: _refreshing,
|
||
),
|
||
),
|
||
),
|
||
_buildStage(),
|
||
],
|
||
),
|
||
);
|
||
},
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _buildConnectionStatusCard() {
|
||
final status = _demoStatus;
|
||
final connected = status['peerConnected'] == true;
|
||
final keyEstablished = status['keyEstablished'] == 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(
|
||
'被控端 ${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: 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,
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
}
|