feat(sender): 首页移除投屏画面,请求投屏直开独立窗口,新增文件传输

- 删除首页 VideoView:画面只在独立原生窗口显示,首页改为状态卡片(分辨率/帧数/错误)

- 新增 MirrorBar 卡片,请求投屏/停止投屏从控制工具栏独立出来;点请求即打开独立窗口再下发 msg_type=8

- 停止投屏同时下发 stop 并关闭窗口;控制工具栏移除投屏按钮

- 独立窗口无画面时居中提示「等待被控端画面…」

- 新增 core/file_client.dart 与 file_browser_page:浏览/下载到 Downloads/TTSTD/上传,带进度与错误提示

- AppSettings 增加 filePort/fileToken 并接入设置页与首页文件卡片
This commit is contained in:
tongtong committed 2026-11-27 09:59:55 +08:00
1 parent 993097df00
commit d3ff293877
10 files changed
+1029 -189

No files matched your search

@@ -65,18 +65,6 @@ class ControlToolbar extends StatelessWidget {
enabled: enabled,
onPressed: () => onEvent('clipboard', {'text': 'TTSTD Connect'}),
),
_Action(
icon: Icons.screen_share,
label: '请求投屏',
enabled: enabled,
onPressed: () => onEvent('requestMirror', const {}),
),
_Action(
icon: Icons.stop_screen_share,
label: '停止投屏',
enabled: enabled,
onPressed: () => onEvent('stopMirror', const {}),
),
],
),
],
@@ -0,0 +1,435 @@
import 'dart:io';
import 'package:flutter/material.dart';
import '../../core/file_client.dart';
/// 浏览 / 下载 / 上传被控端文件。
///
/// 走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317),与串流控制通道互不影响。
class FileBrowserPage extends StatefulWidget {
const FileBrowserPage({
super.key,
required this.host,
required this.initialPort,
required this.initialToken,
this.onConfigChanged,
});
final String host;
final int initialPort;
final String initialToken;
/// 用户改了端口/令牌并保存时通知主界面写回设置。
final void Function(int port, String token)? onConfigChanged;
@override
State<FileBrowserPage> createState() => _FileBrowserPageState();
}
class _FileBrowserPageState extends State<FileBrowserPage> {
late final TextEditingController _portController =
TextEditingController(text: widget.initialPort.toString());
late final TextEditingController _tokenController =
TextEditingController(text: widget.initialToken);
late int _port = widget.initialPort;
late String _token = widget.initialToken;
AndroidFileClient? _client;
RemoteDirectory? _directory;
String? _error;
bool _loading = false;
String _alias = '';
double? _progress;
String _progressLabel = '';
@override
void initState() {
super.initState();
_connect();
}
@override
void dispose() {
_portController.dispose();
_tokenController.dispose();
super.dispose();
}
Future<void> _connect() async {
if (widget.host.isEmpty) {
setState(() => _error = '还没有选中设备,请先连接被控端');
return;
}
setState(() {
_loading = true;
_error = null;
});
final client = AndroidFileClient(host: widget.host, port: _port, token: _token);
try {
final info = await client.info();
final directory = await client.browse('');
if (!mounted) return;
setState(() {
_client = client;
_alias = (info['alias'] ?? '').toString();
_directory = directory;
_loading = false;
});
} on FileClientException catch (error) {
if (!mounted) return;
setState(() {
_error = error.message;
_loading = false;
});
} catch (error) {
if (!mounted) return;
setState(() {
_error = '$error';
_loading = false;
});
}
}
Future<void> _open(String path) async {
final client = _client;
if (client == null) return;
setState(() {
_loading = true;
_error = null;
});
try {
final directory = await client.browse(path);
if (!mounted) return;
setState(() {
_directory = directory;
_loading = false;
});
} on FileClientException catch (error) {
if (!mounted) return;
setState(() {
_error = error.message;
_loading = false;
});
}
}
Future<String> _downloadsDir() async {
final env = Platform.environment;
final home = env['USERPROFILE'] ?? env['HOME'] ?? Directory.current.path;
final dir = Directory('$home${Platform.pathSeparator}Downloads'
'${Platform.pathSeparator}TTSTD');
if (!await dir.exists()) {
await dir.create(recursive: true);
}
return dir.path;
}
Future<void> _download(RemoteFileEntry entry) async {
final client = _client;
if (client == null) return;
final dir = await _downloadsDir();
final target = '$dir${Platform.pathSeparator}${entry.name}';
setState(() {
_progress = 0;
_progressLabel = '下载 ${entry.name}';
});
try {
final written = await client.download(
entry.path,
target,
onProgress: (received, total) {
if (!mounted) return;
setState(() {
_progress = total > 0 ? received / total : null;
_progressLabel = '下载 ${entry.name} · ${_size(received)} / ${_size(total)}';
});
},
);
if (!mounted) return;
_toast('已保存到 $target(${_size(written)})');
} on FileClientException catch (error) {
if (!mounted) return;
_toast(error.message, error: true);
} finally {
if (mounted) {
setState(() {
_progress = null;
_progressLabel = '';
});
}
}
}
Future<void> _upload() async {
final client = _client;
final directory = _directory;
if (client == null || directory == null) return;
final controller = TextEditingController();
final localPath = await showDialog<String>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('上传到当前目录'),
content: TextField(
controller: controller,
autofocus: true,
decoration: const InputDecoration(
labelText: '本地文件绝对路径',
hintText: r'C:\Users\me\Pictures\a.jpg',
),
),
actions: [
TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('取消')),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, controller.text.trim()),
child: const Text('上传'),
),
],
),
);
controller.dispose();
if (localPath == null || localPath.isEmpty) return;
setState(() {
_progress = 0;
_progressLabel = '上传 ${localPath.split(Platform.pathSeparator).last}';
});
try {
final remote = await client.upload(
localPath,
directory.path,
onProgress: (sent, total) {
if (!mounted) return;
setState(() {
_progress = total > 0 ? sent / total : null;
_progressLabel = '上传中 · ${_size(sent)} / ${_size(total)}';
});
},
);
if (!mounted) return;
_toast('已上传到 $remote');
await _open(directory.path);
} on FileClientException catch (error) {
if (!mounted) return;
_toast(error.message, error: true);
} finally {
if (mounted) {
setState(() {
_progress = null;
_progressLabel = '';
});
}
}
}
void _saveConfig() {
final port = int.tryParse(_portController.text.trim()) ?? _port;
final token = _tokenController.text.trim();
setState(() {
_port = port;
_token = token;
});
widget.onConfigChanged?.call(port, token);
_toast('参数已保存');
_connect();
}
void _toast(String message, {bool error = false}) {
if (!mounted) return;
final messenger = ScaffoldMessenger.of(context);
messenger.hideCurrentSnackBar();
messenger.showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: error ? Theme.of(context).colorScheme.error : null,
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final directory = _directory;
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.host.isEmpty ? '文件传输' : '${widget.host}:$_port'),
if (_alias.isNotEmpty)
Text(_alias, style: theme.textTheme.bodySmall),
],
),
actions: [
IconButton(
tooltip: '刷新',
onPressed: _loading ? null : () => _open(directory?.path ?? ''),
icon: const Icon(Icons.refresh),
),
IconButton(
tooltip: '上传文件到当前目录',
onPressed: directory == null || _loading ? null : _upload,
icon: const Icon(Icons.upload_file),
),
],
),
body: Column(
children: [
_buildConfigCard(theme),
if (_progress != null)
LinearProgressIndicator(value: _progress, minHeight: 3),
if (_progressLabel.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Align(
alignment: Alignment.centerLeft,
child: Text(_progressLabel, style: theme.textTheme.bodySmall),
),
),
_buildBreadcrumb(theme, directory),
Expanded(child: _buildBody(theme, directory)),
],
),
);
}
Widget _buildConfigCard(ThemeData theme) {
return Card(
margin: const EdgeInsets.fromLTRB(12, 12, 12, 4),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('被控端文件服务', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextField(
controller: _portController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '端口',
isDense: true,
),
),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: TextField(
controller: _tokenController,
decoration: const InputDecoration(
labelText: '令牌(被控端主界面显示)',
isDense: true,
),
),
),
const SizedBox(width: 8),
FilledButton.tonal(
onPressed: _loading ? null : _saveConfig,
child: const Text('应用'),
),
],
),
],
),
),
);
}
Widget _buildBreadcrumb(ThemeData theme, RemoteDirectory? directory) {
if (directory == null) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
children: [
IconButton(
tooltip: '上一级',
onPressed: directory.parent.isEmpty || _loading
? null
: () => _open(directory.parent),
icon: const Icon(Icons.arrow_upward),
),
Expanded(
child: SelectableText(
directory.path,
style: theme.textTheme.bodySmall,
maxLines: 1,
),
),
Text('${directory.entries.length} 项', style: theme.textTheme.bodySmall),
],
),
);
}
Widget _buildBody(ThemeData theme, RemoteDirectory? directory) {
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.folder_off, size: 56, color: theme.colorScheme.error),
const SizedBox(height: 12),
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 16),
FilledButton.tonal(onPressed: _connect, child: const Text('重试')),
],
),
),
);
}
if (_loading && directory == null) {
return const Center(child: CircularProgressIndicator());
}
if (directory == null) {
return const Center(child: Text('暂无数据'));
}
if (directory.entries.isEmpty) {
return const Center(child: Text('这个目录是空的'));
}
return ListView.separated(
itemCount: directory.entries.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = directory.entries[index];
return ListTile(
dense: true,
leading: Icon(
entry.isDir ? Icons.folder : Icons.insert_drive_file_outlined,
color: entry.isDir ? theme.colorScheme.primary : null,
),
title: Text(entry.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(entry.sizeLabel),
trailing: entry.isDir
? const Icon(Icons.chevron_right)
: IconButton(
tooltip: '下载到本机 Downloads/TTSTD',
onPressed: _progress == null ? () => _download(entry) : null,
icon: const Icon(Icons.download),
),
onTap: entry.isDir
? (_loading ? null : () => _open(entry.path))
: () => _download(entry),
);
},
);
}
}
String _size(int bytes) {
if (bytes <= 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
var value = bytes.toDouble();
var index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index++;
}
return index == 0 ? '$bytes B' : '${value.toStringAsFixed(1)} ${units[index]}';
}
@@ -1,136 +0,0 @@
import 'package:flutter/material.dart';
class VideoView extends StatelessWidget {
const VideoView({
super.key,
this.textureId,
this.connected = false,
this.resolution = '',
this.pts,
this.error = '',
this.standalone = false,
this.aspectRatio = 16 / 9,
});
final int? textureId;
final bool connected;
final String resolution;
final int? pts;
/// 原生解码链路的失败原因,为空表示没有错误。
final String error;
/// 画面已弹出到独立窗口:主界面不再渲染纹理,只显示提示。
final bool standalone;
/// 按实际码流宽高算出的比例(竖屏投屏时不再是 16:9)。
final double aspectRatio;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AspectRatio(
aspectRatio: aspectRatio > 0 ? aspectRatio : 16 / 9,
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
theme.colorScheme.surfaceContainerHighest,
theme.colorScheme.surfaceContainerLowest,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: Stack(
fit: StackFit.expand,
children: [
if (standalone)
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.open_in_new,
size: 72,
color: theme.colorScheme.primary.withValues(alpha: 0.6)),
const SizedBox(height: 12),
Text('画面已在独立窗口播放', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text('把它拖到任意显示器,双击可全屏;关闭独立窗口后画面回到这里',
style: theme.textTheme.bodySmall,
textAlign: TextAlign.center),
],
)
else if (textureId != null)
Texture(textureId: textureId!)
else
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.connected_tv, size: 72, color: theme.colorScheme.primary.withValues(alpha: 0.6)),
const SizedBox(height: 12),
Text(connected ? '视频通道已建立' : '等待投屏画面',
style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
error.isNotEmpty ? error : 'H.264/H.265 → External Texture',
style: theme.textTheme.bodySmall?.copyWith(
color: error.isNotEmpty
? theme.colorScheme.error
: theme.textTheme.bodySmall?.color,
),
textAlign: TextAlign.center,
),
],
),
if (resolution.isNotEmpty)
Positioned(
top: 12,
left: 12,
child: _Badge(
icon: Icons.videocam,
label: resolution,
color: connected ? theme.colorScheme.primary : theme.colorScheme.outline,
),
),
if (pts != null)
Positioned(
top: 12,
right: 12,
child: _Badge(icon: Icons.timer, label: 'PTS $pts', color: theme.colorScheme.outline),
),
],
),
),
),
);
}
}
class _Badge extends StatelessWidget {
const _Badge({required this.icon, required this.label, required this.color});
final IconData icon;
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: color),
const SizedBox(width: 6),
Text(label, style: const TextStyle(color: Colors.white, fontSize: 12)),
],
),
);
}
}
@@ -0,0 +1,132 @@
import 'package:flutter/material.dart';
/// 串流控制卡片。
///
/// 主界面不渲染投屏画面,画面统一显示在独立原生窗口里;这里只负责
/// 「请求投屏 / 停止投屏」与窗口显隐、状态展示。
class MirrorBar extends StatelessWidget {
const MirrorBar({
super.key,
required this.connected,
required this.streaming,
required this.windowOpen,
required this.busy,
required this.resolution,
required this.frames,
required this.error,
required this.onRequest,
required this.onStop,
required this.onToggleWindow,
});
final bool connected;
final bool streaming;
final bool windowOpen;
final bool busy;
final String resolution;
final int frames;
final String error;
final VoidCallback onRequest;
final VoidCallback onStop;
final VoidCallback onToggleWindow;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final status = _statusText();
final statusColor = _statusColor(theme);
return Card(
margin: const EdgeInsets.fromLTRB(12, 8, 12, 4),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(Icons.screen_share, size: 18, color: statusColor),
const SizedBox(width: 8),
Text('串流', style: theme.textTheme.titleMedium),
const SizedBox(width: 10),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: statusColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(10),
),
child: Text(
status,
style: theme.textTheme.labelSmall?.copyWith(color: statusColor),
),
),
const Spacer(),
if (windowOpen)
IconButton(
tooltip: '显示/隐藏串流窗口',
onPressed: onToggleWindow,
icon: const Icon(Icons.picture_in_picture_alt),
),
],
),
const SizedBox(height: 4),
Text(
_detailText(),
style: theme.textTheme.bodySmall,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: FilledButton.icon(
onPressed: connected && !busy ? onRequest : null,
icon: const Icon(Icons.play_circle_outline),
label: const Text('请求投屏'),
),
),
const SizedBox(width: 10),
Expanded(
child: OutlinedButton.icon(
onPressed: onStop,
icon: const Icon(Icons.stop_circle_outlined),
label: const Text('停止投屏'),
),
),
],
),
],
),
),
);
}
String _statusText() {
if (error.isNotEmpty) return '异常';
if (streaming) return '接收画面中';
if (windowOpen) return '等待被控端确认';
if (connected) return '已连接,未投屏';
return '未连接';
}
Color _statusColor(ThemeData theme) {
if (error.isNotEmpty) return theme.colorScheme.error;
if (streaming) return Colors.green;
if (windowOpen) return Colors.orange;
if (connected) return theme.colorScheme.primary;
return theme.colorScheme.outline;
}
String _detailText() {
if (error.isNotEmpty) return error;
if (!connected) return '先在上方连接被控端,再请求投屏';
if (streaming) {
final size = resolution.isEmpty ? '未知分辨率' : resolution;
return '$size · 已接收 $frames 帧 · 画面在独立窗口显示';
}
if (windowOpen) return '已向被控端发送投屏请求,请在其弹窗中点击「允许」';
return '点击「请求投屏」后会弹出独立窗口播放画面';
}
}
@@ -21,6 +21,8 @@ class SettingsPage extends StatefulWidget {
class _SettingsPageState extends State<SettingsPage> {
late final TextEditingController _signalingUrl;
late final TextEditingController _localPort;
late final TextEditingController _filePort;
late final TextEditingController _fileToken;
late bool _useLocalSignaling;
late bool _localSignalingEnabled;
late bool _localRunning;
@@ -39,6 +41,8 @@ class _SettingsPageState extends State<SettingsPage> {
super.initState();
_signalingUrl = TextEditingController(text: widget.settings.signalingUrl);
_localPort = TextEditingController(text: '${widget.settings.localSignalingPort}');
_filePort = TextEditingController(text: '${widget.settings.filePort}');
_fileToken = TextEditingController(text: widget.settings.fileToken);
_useLocalSignaling = widget.settings.useLocalSignaling;
_localSignalingEnabled = widget.settings.localSignalingEnabled;
_localRunning = widget.bridge.isLocalSignalingRunning;
@@ -55,6 +59,8 @@ class _SettingsPageState extends State<SettingsPage> {
void dispose() {
_signalingUrl.dispose();
_localPort.dispose();
_filePort.dispose();
_fileToken.dispose();
super.dispose();
}
@@ -204,6 +210,8 @@ class _SettingsPageState extends State<SettingsPage> {
clipboardSync: _clipboardSync,
fileTransfer: _fileTransfer,
bitrateMbps: _bitrateMbps,
filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort,
fileToken: _fileToken.text.trim(),
));
}
@@ -398,10 +406,38 @@ class _SettingsPageState extends State<SettingsPage> {
),
SwitchListTile(
title: const Text('允许文件传输'),
subtitle: const Text('复用 TLS 会话,支持分片续传'),
subtitle: const Text('浏览/下载/上传被控端文件(LocalSend 风格 HTTP)'),
value: _fileTransfer,
onChanged: (value) => setState(() => _fileTransfer = value),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _filePort,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '文件服务端口',
isDense: true,
),
),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: TextField(
controller: _fileToken,
decoration: const InputDecoration(
labelText: '文件服务令牌(被控端主界面显示)',
isDense: true,
),
),
),
],
),
),
const Divider(height: 32),
ListTile(
title: const Text('投屏码率'),