diff --git a/README.md b/README.md index 1e2877d..69183c4 100644 --- a/README.md +++ b/README.md @@ -434,11 +434,26 @@ POST /mirror/request?token= 触发一次投屏确认(便 ### 8.1 Windows 串流独立窗口 -主界面右上角「串流独立窗口」按钮通过 `ttstd/video` 方法通道(`openWindow` / `closeWindow` / `windowOpen`)拉起一个**原生 Win32 顶层窗口**(`windows/runner/video_window.cpp`),由 GDI 直接绘制解码后的 BGRA 帧: +主界面**不渲染投屏画面**:点「串流」卡片里的「请求投屏」,通过 `ttstd/video` 方法通道 +(`openWindow` / `closeWindow` / `windowOpen`)先拉起一个**原生 Win32 顶层窗口** +(`windows/runner/video_window.cpp`),再向被控端下发 `msg_type=8 action=request`;被控端弹窗 +确认并校验权限后才推流。 - 与主窗口共用同一个 `FrameStore`(`Snapshot()` 返回 `shared_ptr` 保证绘制期间帧不被回收),不额外解码、不再抢 Rust 的单消费者帧队列。 -- 独立窗口在播时不再驱动 Flutter 纹理,省一次 BGRA 拷贝;主界面显示「画面已在独立窗口播放」占位。 +- 独立窗口在播时不再驱动 Flutter 纹理,省一次 BGRA 拷贝;首页只显示串流状态(分辨率/帧数/错误)。 - 支持拖到第二块显示器、最大化、双击/F11 全屏、ESC 退出;按真实码流宽高做 letterbox,竖屏不拉伸。 +- 还没收到画面时窗口居中显示「等待被控端画面…」,不会只给一块黑屏。 +- 「停止投屏」会同时下发 `msg_type=8 action=stop` 并关闭窗口。 + +### 8.2 文件传输 + +首页「文件传输」卡片 → 「浏览被控端文件」,走被控端内置的 LocalSend 风格 HTTP 服务 +(`lib/core/file_client.dart` + `lib/features/file/file_browser_page.dart`): + +- 目录浏览(`GET /browse`)、下载到本机 `Downloads/TTSTD`(`GET /download`)、 + 上传本地文件到当前目录(`POST /api/localsend/v2/upload`),带进度与错误提示。 +- 端口/令牌可在设置页或文件页里改并持久化;令牌由被控端主界面生成显示。 +- 该链路独立于串流控制通道,被控端只要处于待命态即可使用。 - **Wayland 主控**:Flutter 本身走 EGL 没问题,只是未来若加 Linux 被控才需要处理 PipeWire portal --- diff --git a/flutter_sender/lib/core/file_client.dart b/flutter_sender/lib/core/file_client.dart new file mode 100644 index 0000000..aed2d1c --- /dev/null +++ b/flutter_sender/lib/core/file_client.dart @@ -0,0 +1,239 @@ +import 'dart:convert'; +import 'dart:io'; + +/// 被控端目录项。 +class RemoteFileEntry { + const RemoteFileEntry({ + required this.name, + required this.path, + required this.isDir, + required this.size, + required this.modified, + }); + + final String name; + final String path; + final bool isDir; + final int size; + final int modified; + + factory RemoteFileEntry.fromJson(Map json) { + return RemoteFileEntry( + name: (json['name'] ?? '').toString(), + path: (json['path'] ?? '').toString(), + isDir: json['dir'] == true, + size: json['size'] is num ? (json['size'] as num).toInt() : 0, + modified: json['mtime'] is num ? (json['mtime'] as num).toInt() : 0, + ); + } + + String get sizeLabel { + if (isDir) return '目录'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + var value = size.toDouble(); + var index = 0; + while (value >= 1024 && index < units.length - 1) { + value /= 1024; + index++; + } + return index == 0 ? '${size} B' : '${value.toStringAsFixed(1)} ${units[index]}'; + } +} + +/// 一次目录列举的结果。 +class RemoteDirectory { + const RemoteDirectory({ + required this.path, + required this.parent, + required this.entries, + }); + + final String path; + final String parent; + final List entries; + + factory RemoteDirectory.fromJson(Map json) { + final raw = json['entries']; + final entries = raw is List + ? raw + .whereType>() + .map((item) => RemoteFileEntry.fromJson(Map.from(item))) + .toList(growable: false) + : const []; + return RemoteDirectory( + path: (json['path'] ?? '').toString(), + parent: (json['parent'] ?? '').toString(), + entries: entries, + ); + } +} + +/// 被控端文件服务客户端(LocalSend 风格 HTTP,默认 53317)。 +/// +/// 不依赖控制通道:只要被控端的待命服务在跑,就能浏览/下载/上传文件。 +class AndroidFileClient { + AndroidFileClient({ + required this.host, + required this.port, + required this.token, + this.timeout = const Duration(seconds: 15), + }); + + final String host; + final int port; + final String token; + final Duration timeout; + + String get baseUrl => 'http://$host:$port'; + + Uri _uri(String path, [Map? query]) { + return Uri( + scheme: 'http', + host: host, + port: port, + path: path, + queryParameters: { + ...?query, + if (token.isNotEmpty) 'token': token, + }, + ); + } + + HttpClient _client() => HttpClient()..connectionTimeout = timeout; + + /// 设备信息(无需令牌),同时用于连通性自检。 + Future> info() async { + final client = _client(); + try { + final request = await client.getUrl(Uri.parse('$baseUrl/api/localsend/v2/info')); + final response = await request.close().timeout(timeout); + final body = await response.transform(utf8.decoder).join(); + if (response.statusCode != 200) { + throw FileClientException('设备信息读取失败(HTTP ${response.statusCode})'); + } + return jsonDecode(body) as Map; + } on SocketException catch (error) { + throw FileClientException('无法连接 $host:$port,请确认被控端待命服务已启动(${error.message})'); + } finally { + client.close(force: true); + } + } + + /// 列举目录。 + Future browse(String path) async { + final client = _client(); + try { + final request = await client.getUrl(_uri('/browse', {'path': path})); + final response = await request.close().timeout(timeout); + final body = await response.transform(utf8.decoder).join(); + if (response.statusCode == 403) { + throw FileClientException('令牌无效,请填写被控端主界面显示的文件服务令牌'); + } + if (response.statusCode != 200) { + throw FileClientException(_errorOf(body, response.statusCode)); + } + return RemoteDirectory.fromJson(jsonDecode(body) as Map); + } on SocketException catch (error) { + throw FileClientException('无法连接 $host:$port(${error.message})'); + } finally { + client.close(force: true); + } + } + + /// 下载文件到本地路径,返回写入字节数。 + Future download( + String remotePath, + String localPath, { + void Function(int received, int total)? onProgress, + }) async { + final client = _client(); + try { + final request = await client.getUrl(_uri('/download', {'path': remotePath})); + final response = await request.close().timeout(timeout); + if (response.statusCode != 200) { + final body = await response.transform(utf8.decoder).join(); + throw FileClientException(_errorOf(body, response.statusCode)); + } + final target = File(localPath); + await target.parent.create(recursive: true); + final sink = target.openWrite(); + final total = response.contentLength; + var received = 0; + try { + await for (final chunk in response) { + sink.add(chunk); + received += chunk.length; + onProgress?.call(received, total); + } + } finally { + await sink.flush(); + await sink.close(); + } + return received; + } on SocketException catch (error) { + throw FileClientException('下载失败:${error.message}'); + } finally { + client.close(force: true); + } + } + + /// 上传本地文件到被控端目录,返回远端路径。 + Future upload( + String localPath, + String remoteDir, { + void Function(int sent, int total)? onProgress, + }) async { + final source = File(localPath); + if (!await source.exists()) { + throw FileClientException('本地文件不存在:$localPath'); + } + final total = await source.length(); + final client = _client(); + try { + final request = await client.postUrl( + _uri('/api/localsend/v2/upload', { + 'path': remoteDir, + 'name': source.uri.pathSegments.last, + }), + ); + request.headers.contentType = ContentType.binary; + request.contentLength = total; + var sent = 0; + await for (final chunk in source.openRead()) { + request.add(chunk); + sent += chunk.length; + onProgress?.call(sent, total); + } + final response = await request.close().timeout(timeout); + final body = await response.transform(utf8.decoder).join(); + if (response.statusCode != 200) { + throw FileClientException(_errorOf(body, response.statusCode)); + } + final json = jsonDecode(body) as Map; + return (json['path'] ?? '').toString(); + } on SocketException catch (error) { + throw FileClientException('上传失败:${error.message}'); + } finally { + client.close(force: true); + } + } + + String _errorOf(String body, int statusCode) { + try { + final json = jsonDecode(body); + if (json is Map && json['error'] != null) return json['error'].toString(); + } on Object catch (_) { + // 非 JSON 响应直接用原文。 + } + return 'HTTP $statusCode:${body.isEmpty ? '无响应内容' : body}'; + } +} + +class FileClientException implements Exception { + FileClientException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/flutter_sender/lib/core/models.dart b/flutter_sender/lib/core/models.dart index c892e23..c36d21e 100644 --- a/flutter_sender/lib/core/models.dart +++ b/flutter_sender/lib/core/models.dart @@ -121,6 +121,10 @@ class AppSettings { final bool clipboardSync; final bool fileTransfer; final int bitrateMbps; + /// 被控端文件服务端口(LocalSend 风格 HTTP,默认 53317)。 + final int filePort; + /// 被控端文件服务访问令牌,被控端主界面会显示。 + final String fileToken; const AppSettings({ this.signalingUrl = '', @@ -132,6 +136,8 @@ class AppSettings { this.clipboardSync = true, this.fileTransfer = true, this.bitrateMbps = 8, + this.filePort = 53317, + this.fileToken = '', }); static const defaults = AppSettings(); @@ -148,6 +154,8 @@ class AppSettings { bool? clipboardSync, bool? fileTransfer, int? bitrateMbps, + int? filePort, + String? fileToken, }) { return AppSettings( signalingUrl: signalingUrl ?? this.signalingUrl, @@ -159,6 +167,8 @@ class AppSettings { clipboardSync: clipboardSync ?? this.clipboardSync, fileTransfer: fileTransfer ?? this.fileTransfer, bitrateMbps: bitrateMbps ?? this.bitrateMbps, + filePort: filePort ?? this.filePort, + fileToken: fileToken ?? this.fileToken, ); } @@ -175,6 +185,8 @@ class AppSettings { clipboardSync: json['clipboardSync'] as bool? ?? defaults.clipboardSync, fileTransfer: json['fileTransfer'] as bool? ?? defaults.fileTransfer, bitrateMbps: (json['bitrateMbps'] is num ? json['bitrateMbps'] as num : 8).toInt(), + filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(), + fileToken: (json['fileToken'] ?? defaults.fileToken).toString(), ); } @@ -188,5 +200,7 @@ class AppSettings { 'clipboardSync': clipboardSync, 'fileTransfer': fileTransfer, 'bitrateMbps': bitrateMbps, + 'filePort': filePort, + 'fileToken': fileToken, }; } diff --git a/flutter_sender/lib/features/control/control_toolbar.dart b/flutter_sender/lib/features/control/control_toolbar.dart index eb85c44..3cb4f23 100644 --- a/flutter_sender/lib/features/control/control_toolbar.dart +++ b/flutter_sender/lib/features/control/control_toolbar.dart @@ -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 {}), - ), ], ), ], diff --git a/flutter_sender/lib/features/file/file_browser_page.dart b/flutter_sender/lib/features/file/file_browser_page.dart new file mode 100644 index 0000000..c7e005e --- /dev/null +++ b/flutter_sender/lib/features/file/file_browser_page.dart @@ -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 createState() => _FileBrowserPageState(); +} + +class _FileBrowserPageState extends State { + 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 _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 _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 _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 _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 _upload() async { + final client = _client; + final directory = _directory; + if (client == null || directory == null) return; + final controller = TextEditingController(); + final localPath = await showDialog( + 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]}'; +} diff --git a/flutter_sender/lib/features/media/video_view.dart b/flutter_sender/lib/features/media/video_view.dart deleted file mode 100644 index 3bd8423..0000000 --- a/flutter_sender/lib/features/media/video_view.dart +++ /dev/null @@ -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)), - ], - ), - ); - } -} diff --git a/flutter_sender/lib/features/session/mirror_bar.dart b/flutter_sender/lib/features/session/mirror_bar.dart new file mode 100644 index 0000000..0ddbe2b --- /dev/null +++ b/flutter_sender/lib/features/session/mirror_bar.dart @@ -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 '点击「请求投屏」后会弹出独立窗口播放画面'; + } +} diff --git a/flutter_sender/lib/features/settings/settings_page.dart b/flutter_sender/lib/features/settings/settings_page.dart index 2090788..032c518 100644 --- a/flutter_sender/lib/features/settings/settings_page.dart +++ b/flutter_sender/lib/features/settings/settings_page.dart @@ -21,6 +21,8 @@ class SettingsPage extends StatefulWidget { class _SettingsPageState extends State { 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 { 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 { void dispose() { _signalingUrl.dispose(); _localPort.dispose(); + _filePort.dispose(); + _fileToken.dispose(); super.dispose(); } @@ -204,6 +210,8 @@ class _SettingsPageState extends State { 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 { ), 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('投屏码率'), diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart index c5575da..5934f21 100644 --- a/flutter_sender/lib/main.dart +++ b/flutter_sender/lib/main.dart @@ -9,8 +9,9 @@ import 'core/native_core.dart'; import 'core/models.dart'; import 'features/control/control_toolbar.dart'; import 'features/discovery/device_list.dart'; -import 'features/media/video_view.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()); @@ -62,6 +63,8 @@ class _HomePageState extends State { int? _textureId; /// 串流画面是否已弹出到独立原生窗口。 bool _videoWindowOpen = false; + /// 正在拉起窗口并下发投屏请求。 + bool _mirrorRequesting = false; String? _nativeError; @override @@ -167,7 +170,44 @@ class _HomePageState extends State { }); } - /// 把串流画面弹出/收回独立原生窗口(Windows)。 + /// 请求投屏:先把独立串流窗口打开,再向被控端下发投屏请求。 + /// + /// 被控端会弹窗确认,确认后才开始推流;这段时间窗口显示「等待画面」。 + Future _requestMirror() async { + if (!_phase.isConnected) { + _snack('请先连接被控端'); + return; + } + setState(() => _mirrorRequesting = true); + try { + if (!_videoWindowOpen) { + final opened = await _bridge.openVideoWindow(); + if (!mounted) return; + if (!opened) { + _snack('当前平台不支持独立串流窗口'); + return; + } + setState(() => _videoWindowOpen = true); + } + _sendControl('requestMirror', const {}); + _diagnosticLog.write('mirror request sent'); + } finally { + if (mounted) setState(() => _mirrorRequesting = false); + } + } + + /// 停止投屏:通知被控端结束推流,并关闭独立画面窗口。 + Future _stopMirror() async { + if (_phase.isConnected) { + _sendControl('stopMirror', const {}); + _diagnosticLog.write('mirror stop sent'); + } + await _bridge.closeVideoWindow(); + if (!mounted) return; + setState(() => _videoWindowOpen = false); + } + + /// 独立窗口显隐(不停流)。 Future _toggleVideoWindow() async { if (_videoWindowOpen) { await _bridge.closeVideoWindow(); @@ -178,14 +218,81 @@ class _HomePageState extends State { final opened = await _bridge.openVideoWindow(); if (!mounted) return; if (!opened) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('当前平台不支持独立串流窗口')), - ); + _snack('当前平台不支持独立串流窗口'); return; } setState(() => _videoWindowOpen = true); } + 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 ? '未选设备' : '$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('浏览被控端文件'), + ), + ], + ), + ), + ); + } + + Future _openFileBrowser() async { + final device = _selected; + if (device == null) { + _snack('请先选中被控端设备'); + return; + } + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => FileBrowserPage( + host: device.ip, + initialPort: _settings.filePort, + initialToken: _settings.fileToken, + onConfigChanged: (port, token) { + final updated = _settings.copyWith(filePort: port, fileToken: token); + setState(() => _settings = updated); + _bridge.saveSettings(updated); + }, + ), + ), + ); + } + void _writeDiagnosticLog() { Map status; if (_nativeCore == null) { @@ -341,8 +448,17 @@ class _HomePageState extends State { void _sendControl(String type, Map payload) { _bridge.sendControl(type, payload); + const labels = { + 'requestMirror': '投屏请求', + 'stopMirror': '停止投屏', + 'clipboard': '剪贴板内容', + 'ping': '心跳', + }; ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('已发送 $type 控制事件'), duration: const Duration(milliseconds: 900)), + SnackBar( + content: Text('已发送${labels[type] ?? ' $type '}'), + duration: const Duration(milliseconds: 900), + ), ); } @@ -352,11 +468,6 @@ class _HomePageState extends State { appBar: AppBar( title: const Text('TTSTD Connect'), actions: [ - IconButton( - tooltip: _videoWindowOpen ? '收回串流窗口' : '串流独立窗口', - onPressed: _toggleVideoWindow, - icon: Icon(_videoWindowOpen ? Icons.close_fullscreen : Icons.open_in_new), - ), IconButton( tooltip: '扫码配对', onPressed: _showPairing, @@ -531,54 +642,49 @@ class _HomePageState extends State { return _selected?.resolution ?? ''; } - int? get _videoPts { - final decoded = _videoStats['decoded']; - final pts = _videoStats['pts']; - if (decoded is int && decoded > 0 && pts is int) return pts; - return null; - } - String get _videoError => (_videoStats['error'] as String? ?? '').trim(); - /// 按实际码流宽高算显示比例;竖屏被控端(如 1080x2400)不再被压成 16:9。 - double get _videoAspectRatio { - final width = _videoStats['width']; - final height = _videoStats['height']; - if (width is int && height is int && width > 0 && height > 0) { - return width / height; - } - return 16 / 9; + int get _videoFrames { + final decoded = _videoStats['decoded']; + return decoded is int ? decoded : 0; } + /// 是否已经在接收画面(首页不显示画面,只看状态)。 + bool get _videoStreaming => _videoFrames > 0 && _videoError.isEmpty; + Widget _buildStage() { return Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - VideoView( - // 独立窗口在播时不再占用主窗口纹理。 - textureId: _videoWindowOpen ? null : _textureId, - connected: _phase.isConnected, - resolution: _videoResolution, - pts: _videoPts, - error: _videoError, - standalone: _videoWindowOpen, - aspectRatio: _videoAspectRatio, - ), - const SizedBox(height: 16), ConnectBar( phase: _phase, device: _selected, onConnect: _connect, onDisconnect: _disconnect, ), - const SizedBox(height: 16), + const SizedBox(height: 12), + MirrorBar( + connected: _phase.isConnected, + streaming: _videoStreaming, + windowOpen: _videoWindowOpen, + busy: _mirrorRequesting, + resolution: _videoResolution, + frames: _videoFrames, + error: _videoError, + onRequest: _requestMirror, + onStop: _stopMirror, + onToggleWindow: _toggleVideoWindow, + ), + 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( diff --git a/flutter_sender/windows/runner/video_window.cpp b/flutter_sender/windows/runner/video_window.cpp index 56fa301..3e498b3 100644 --- a/flutter_sender/windows/runner/video_window.cpp +++ b/flutter_sender/windows/runner/video_window.cpp @@ -189,6 +189,17 @@ void VideoWindow::Paint() { SetStretchBltMode(hdc, COLORONCOLOR); StretchDIBits(hdc, offset_x, offset_y, draw_width, draw_height, 0, 0, width, height, frame->data(), &info, DIB_RGB_COLORS, SRCCOPY); + } else { + // 还没画面时给个提示:窗口是在点「请求投屏」后就弹出的, + // 纯黑会让人以为卡死。 + HGDIOBJ previous = SelectObject(hdc, GetStockObject(DEFAULT_GUI_FONT)); + SetBkMode(hdc, TRANSPARENT); + SetTextColor(hdc, RGB(170, 170, 170)); + RECT text_rect = client; + DrawTextW(hdc, + L"等待被控端画面…\r\n请在手机弹窗中点击「允许」", -1, &text_rect, + DT_CENTER | DT_VCENTER | DT_WORDBREAK); + SelectObject(hdc, previous); } EndPaint(hwnd_, &paint);