diff --git a/README.md b/README.md index 69183c4..5c3c0dc 100644 --- a/README.md +++ b/README.md @@ -441,9 +441,9 @@ POST /mirror/request?token= 触发一次投屏确认(便 - 与主窗口共用同一个 `FrameStore`(`Snapshot()` 返回 `shared_ptr` 保证绘制期间帧不被回收),不额外解码、不再抢 Rust 的单消费者帧队列。 - 独立窗口在播时不再驱动 Flutter 纹理,省一次 BGRA 拷贝;首页只显示串流状态(分辨率/帧数/错误)。 -- 支持拖到第二块显示器、最大化、双击/F11 全屏、ESC 退出;按真实码流宽高做 letterbox,竖屏不拉伸。 +- 窗口尺寸跟随视频宽高比:首帧到达时按视频比例自动调整并居中;拖动边框时由 `WM_SIZING` 锁定比例,没有最大化按钮、没有双击全屏。 - 还没收到画面时窗口居中显示「等待被控端画面…」,不会只给一块黑屏。 -- 「停止投屏」会同时下发 `msg_type=8 action=stop` 并关闭窗口。 +- **关闭窗口即停止投屏**:`WM_DESTROY` 通过方法通道回 `windowClosed`,Dart 侧随即下发 `msg_type=8 action=stop`,因此界面上不再需要「停止投屏」按钮。 ### 8.2 文件传输 diff --git a/flutter_sender/lib/core/bridge.dart b/flutter_sender/lib/core/bridge.dart index 48f7eb1..3b2af9a 100644 --- a/flutter_sender/lib/core/bridge.dart +++ b/flutter_sender/lib/core/bridge.dart @@ -15,7 +15,9 @@ class SenderBridge { NativeCore? nativeCore, }) : _method = method ?? const MethodChannel('ttstd/sender'), _events = events ?? const EventChannel('ttstd/sender/events'), - _native = nativeCore; + _native = nativeCore { + _video.setMethodCallHandler(_handleVideoCall); + } final MethodChannel _method; final EventChannel _events; @@ -25,6 +27,15 @@ class SenderBridge { /// 原生视频解码纹理通道(Windows runner 内嵌插件)。 static const MethodChannel _video = MethodChannel('ttstd/video'); + /// 用户关掉独立串流窗口(点关闭按钮 / 按 ESC)时触发,用于停止投屏。 + void Function()? onVideoWindowClosed; + + Future _handleVideoCall(MethodCall call) async { + if (call.method == 'windowClosed') { + onVideoWindowClosed?.call(); + } + } + NativeCore? get nativeCore => _native; bool get isLocalSignalingRunning => _localSignaling.isRunning; diff --git a/flutter_sender/lib/features/file/file_browser_page.dart b/flutter_sender/lib/features/file/file_browser_page.dart index c7e005e..06d477f 100644 --- a/flutter_sender/lib/features/file/file_browser_page.dart +++ b/flutter_sender/lib/features/file/file_browser_page.dart @@ -20,19 +20,22 @@ class FileBrowserPage extends StatefulWidget { final int initialPort; final String initialToken; - /// 用户改了端口/令牌并保存时通知主界面写回设置。 - final void Function(int port, String token)? onConfigChanged; + /// 用户改了地址/端口/令牌并保存时通知主界面写回设置。 + final void Function(String host, int port, String token)? onConfigChanged; @override State createState() => _FileBrowserPageState(); } class _FileBrowserPageState extends State { + late final TextEditingController _hostController = + TextEditingController(text: widget.host); late final TextEditingController _portController = TextEditingController(text: widget.initialPort.toString()); late final TextEditingController _tokenController = TextEditingController(text: widget.initialToken); + late String _host = widget.host; late int _port = widget.initialPort; late String _token = widget.initialToken; @@ -58,15 +61,15 @@ class _FileBrowserPageState extends State { } Future _connect() async { - if (widget.host.isEmpty) { - setState(() => _error = '还没有选中设备,请先连接被控端'); + if (_host.isEmpty || _host == '127.0.0.1') { + setState(() => _error = '还没有拿到被控端的局域网 IP,请在上方「IP」里手动填写(例如 192.168.1.23)'); return; } setState(() { _loading = true; _error = null; }); - final client = AndroidFileClient(host: widget.host, port: _port, token: _token); + final client = AndroidFileClient(host: _host, port: _port, token: _token); try { final info = await client.info(); final directory = await client.browse(''); @@ -224,13 +227,15 @@ class _FileBrowserPageState extends State { } void _saveConfig() { + final host = _hostController.text.trim(); final port = int.tryParse(_portController.text.trim()) ?? _port; final token = _tokenController.text.trim(); setState(() { + _host = host; _port = port; _token = token; }); - widget.onConfigChanged?.call(port, token); + widget.onConfigChanged?.call(host, port, token); _toast('参数已保存'); _connect(); } @@ -256,7 +261,7 @@ class _FileBrowserPageState extends State { title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(widget.host.isEmpty ? '文件传输' : '${widget.host}:$_port'), + Text(_host.isEmpty ? '文件传输' : '$_host:$_port'), if (_alias.isNotEmpty) Text(_alias, style: theme.textTheme.bodySmall), ], @@ -306,6 +311,18 @@ class _FileBrowserPageState extends State { const SizedBox(height: 8), Row( children: [ + Expanded( + flex: 2, + child: TextField( + controller: _hostController, + decoration: const InputDecoration( + labelText: 'IP', + hintText: '192.168.1.23', + isDense: true, + ), + ), + ), + const SizedBox(width: 10), Expanded( child: TextField( controller: _portController, @@ -316,9 +333,12 @@ class _FileBrowserPageState extends State { ), ), ), - const SizedBox(width: 12), + ], + ), + const SizedBox(height: 8), + Row( + children: [ Expanded( - flex: 2, child: TextField( controller: _tokenController, decoration: const InputDecoration( diff --git a/flutter_sender/lib/features/session/mirror_bar.dart b/flutter_sender/lib/features/session/mirror_bar.dart index 0ddbe2b..bc0d39b 100644 --- a/flutter_sender/lib/features/session/mirror_bar.dart +++ b/flutter_sender/lib/features/session/mirror_bar.dart @@ -2,8 +2,8 @@ import 'package:flutter/material.dart'; /// 串流控制卡片。 /// -/// 主界面不渲染投屏画面,画面统一显示在独立原生窗口里;这里只负责 -/// 「请求投屏 / 停止投屏」与窗口显隐、状态展示。 +/// 主界面不渲染投屏画面,画面统一显示在独立原生窗口里;窗口尺寸按视频比例自动适配, +/// 关闭窗口即停止投屏,所以这里只保留「请求投屏」一个动作。 class MirrorBar extends StatelessWidget { const MirrorBar({ super.key, @@ -15,8 +15,6 @@ class MirrorBar extends StatelessWidget { required this.frames, required this.error, required this.onRequest, - required this.onStop, - required this.onToggleWindow, }); final bool connected; @@ -28,13 +26,10 @@ class MirrorBar extends StatelessWidget { 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( @@ -57,17 +52,13 @@ class MirrorBar extends StatelessWidget { borderRadius: BorderRadius.circular(10), ), child: Text( - status, + _statusText(), style: theme.textTheme.labelSmall?.copyWith(color: statusColor), ), ), const Spacer(), if (windowOpen) - IconButton( - tooltip: '显示/隐藏串流窗口', - onPressed: onToggleWindow, - icon: const Icon(Icons.picture_in_picture_alt), - ), + Text('串流窗口已打开', style: theme.textTheme.labelSmall), ], ), const SizedBox(height: 4), @@ -78,24 +69,15 @@ class MirrorBar extends StatelessWidget { 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('请求投屏'), - ), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: connected && !busy && !streaming ? onRequest : null, + icon: Icon( + streaming ? Icons.cast_connected : Icons.play_circle_outline, ), - const SizedBox(width: 10), - Expanded( - child: OutlinedButton.icon( - onPressed: onStop, - icon: const Icon(Icons.stop_circle_outlined), - label: const Text('停止投屏'), - ), - ), - ], + label: Text(streaming ? '投屏中 · 关闭窗口即停止' : '请求投屏'), + ), ), ], ), @@ -124,9 +106,9 @@ class MirrorBar extends StatelessWidget { if (!connected) return '先在上方连接被控端,再请求投屏'; if (streaming) { final size = resolution.isEmpty ? '未知分辨率' : resolution; - return '$size · 已接收 $frames 帧 · 画面在独立窗口显示'; + return '$size · 已接收 $frames 帧 · 关闭独立窗口会立即停止投屏'; } if (windowOpen) return '已向被控端发送投屏请求,请在其弹窗中点击「允许」'; - return '点击「请求投屏」后会弹出独立窗口播放画面'; + return '点击「请求投屏」会按视频比例弹出独立窗口播放画面'; } } diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart index 5934f21..4873d3b 100644 --- a/flutter_sender/lib/main.dart +++ b/flutter_sender/lib/main.dart @@ -76,6 +76,8 @@ class _HomePageState extends State { _nativeError = error.toString(); } _bridge = SenderBridge(nativeCore: _nativeCore); + // 独立窗口被用户关闭 → 停止投屏。 + _bridge.onVideoWindowClosed = _handleVideoWindowClosed; _diagnosticLog.start(); _diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}'); _bridge.watchPhase().listen((phase) { @@ -196,32 +198,15 @@ class _HomePageState extends State { } } - /// 停止投屏:通知被控端结束推流,并关闭独立画面窗口。 - Future _stopMirror() async { - if (_phase.isConnected) { - _sendControl('stopMirror', const {}); - _diagnosticLog.write('mirror stop sent'); - } - await _bridge.closeVideoWindow(); + /// 用户关掉独立串流窗口(点关闭按钮 / 按 ESC)→ 直接停止投屏。 + Future _handleVideoWindowClosed() async { if (!mounted) return; setState(() => _videoWindowOpen = false); - } - - /// 独立窗口显隐(不停流)。 - Future _toggleVideoWindow() async { - if (_videoWindowOpen) { - await _bridge.closeVideoWindow(); - if (!mounted) return; - setState(() => _videoWindowOpen = false); - return; - } - final opened = await _bridge.openVideoWindow(); - if (!mounted) return; - if (!opened) { - _snack('当前平台不支持独立串流窗口'); - return; - } - setState(() => _videoWindowOpen = true); + if (!_phase.isConnected) return; + // 先通知被控端收流,再确保窗口已经关掉(用户已手动关了就无需重复动作)。 + _bridge.sendControl('stopMirror', const {}); + _diagnosticLog.write('video window closed -> stopMirror'); + _snack('串流窗口已关闭,已停止投屏'); } void _snack(String message) { @@ -248,7 +233,7 @@ class _HomePageState extends State { Text('文件传输', style: Theme.of(context).textTheme.titleMedium), const Spacer(), Text( - host.isEmpty ? '未选设备' : '$host:${_settings.filePort}', + host.isEmpty ? '未拿到被控端 IP' : '$host:${_settings.filePort}', style: Theme.of(context).textTheme.bodySmall, ), ], @@ -271,19 +256,39 @@ class _HomePageState extends State { ); } + /// 文件服务要连的被控端地址。 + /// + /// 优先用设备列表里的局域网 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 _openFileBrowser() async { - final device = _selected; - if (device == null) { + if (_selected == null) { _snack('请先选中被控端设备'); return; } + final host = _fileHost; + if (!_isUsableHost(host)) { + _snack('还没拿到被控端 IP:请先连接设备,或在文件页手动填写 IP'); + } await Navigator.of(context).push( MaterialPageRoute( builder: (_) => FileBrowserPage( - host: device.ip, + host: host, initialPort: _settings.filePort, initialToken: _settings.fileToken, - onConfigChanged: (port, token) { + onConfigChanged: (host, port, token) { final updated = _settings.copyWith(filePort: port, fileToken: token); setState(() => _settings = updated); _bridge.saveSettings(updated); @@ -674,8 +679,6 @@ class _HomePageState extends State { frames: _videoFrames, error: _videoError, onRequest: _requestMirror, - onStop: _stopMirror, - onToggleWindow: _toggleVideoWindow, ), const SizedBox(height: 12), ControlToolbar( diff --git a/flutter_sender/windows/runner/video_texture.cpp b/flutter_sender/windows/runner/video_texture.cpp index 9594f18..5f50f0a 100644 --- a/flutter_sender/windows/runner/video_texture.cpp +++ b/flutter_sender/windows/runner/video_texture.cpp @@ -832,10 +832,16 @@ class VideoTexturePlugin : public flutter::Plugin { std::unique_ptr> result) { HandleMethodCall(call, std::move(result)); }); + // 用户点窗口关闭按钮或按 ESC:通知 Flutter 停止投屏。 + video_window_.SetCloseHandler([this]() { OnVideoWindowClosed(); }); + worker_ = std::thread([this, shared_frames]() { RunWorker(shared_frames); }); } ~VideoTexturePlugin() override { + // 先摘掉回调,避免析构期间 DestroyWindow 触发 InvokeMethod。 + video_window_.SetCloseHandler(nullptr); + video_window_.Close(); stop_.store(true); if (worker_.joinable()) { worker_.join(); @@ -866,6 +872,19 @@ class VideoTexturePlugin : public flutter::Plugin { return &descriptor_; } + // 独立窗口被用户关闭:让 Dart 侧停止投屏。 + void OnVideoWindowClosed() { + if (closing_from_channel_) { + closing_from_channel_ = false; + return; + } + if (channel_ == nullptr) { + return; + } + channel_->InvokeMethod("windowClosed", + std::make_unique(true)); + } + void HandleMethodCall( const flutter::MethodCall& call, std::unique_ptr> result) { @@ -882,6 +901,9 @@ class VideoTexturePlugin : public flutter::Plugin { return; } if (call.method_name() == "closeWindow") { + // 由 Flutter 主动关闭时不回调 windowClosed,避免重复下发停止投屏。 + // 窗口本来就没开时不要置位,否则下一次用户关窗会被错误抑制。 + closing_from_channel_ = video_window_.IsOpen(); video_window_.Close(); result->Success(flutter::EncodableValue(true)); return; @@ -1029,6 +1051,8 @@ class VideoTexturePlugin : public flutter::Plugin { std::shared_ptr frames_; // 与主窗口纹理共享同一份 FrameStore 的独立串流窗口。 VideoWindow video_window_; + // 本次关闭是由 Flutter 主动发起的(不需要再回调 windowClosed)。 + bool closing_from_channel_ = false; RustVideoApi api_; VideoDecoder decoder_; std::atomic stop_{false}; diff --git a/flutter_sender/windows/runner/video_window.cpp b/flutter_sender/windows/runner/video_window.cpp index 3e498b3..4b4a3d1 100644 --- a/flutter_sender/windows/runner/video_window.cpp +++ b/flutter_sender/windows/runner/video_window.cpp @@ -1,6 +1,7 @@ #include "video_window.h" #include +#include namespace { @@ -8,6 +9,12 @@ constexpr wchar_t kWindowClass[] = L"TTSTDVideoWindowClass"; constexpr wchar_t kWindowTitle[] = L"TTSTD 串流"; // 解码线程 -> 窗口线程:有新帧,触发一次重绘。 constexpr UINT kMsgFrameReady = WM_APP + 0x51; +// 窗口线程内部:视频宽高比变化,需要按比例重设窗口大小。 +constexpr UINT kMsgApplyAspect = WM_APP + 0x52; + +// 最小客户区尺寸,避免窗口被拖成一条缝。 +constexpr int kMinClientWidth = 320; +constexpr int kMinClientHeight = 180; } // namespace @@ -28,7 +35,7 @@ bool VideoWindow::Open(FrameProvider provider) { HINSTANCE instance = GetModuleHandleW(nullptr); WNDCLASSEXW window_class = {}; window_class.cbSize = sizeof(WNDCLASSEXW); - window_class.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; + window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.lpfnWndProc = &VideoWindow::StaticWndProc; window_class.hInstance = instance; window_class.hCursor = LoadCursorW(nullptr, IDC_ARROW); @@ -41,18 +48,23 @@ bool VideoWindow::Open(FrameProvider provider) { return false; } + // 不提供最大化按钮:画面窗口只按视频比例缩放。 + const DWORD style = WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX; + RECT rect = {0, 0, 1280, 720}; - AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, FALSE); + AdjustWindowRect(&rect, style, FALSE); HWND hwnd = CreateWindowExW( - 0, kWindowClass, kWindowTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, - CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, nullptr, - nullptr, instance, this); + 0, kWindowClass, kWindowTitle, style, CW_USEDEFAULT, CW_USEDEFAULT, + rect.right - rect.left, rect.bottom - rect.top, nullptr, nullptr, instance, + this); if (hwnd == nullptr) { provider_ = nullptr; return false; } hwnd_ = hwnd; + aspect_ratio_ = 0.0; + applied_aspect_ = 0.0; open_.store(true); ShowWindow(hwnd_, SW_SHOWNORMAL); UpdateWindow(hwnd_); @@ -67,7 +79,12 @@ void VideoWindow::Close() { open_.store(false); repaint_pending_.store(false); provider_ = nullptr; - full_screen_ = false; + aspect_ratio_ = 0.0; + applied_aspect_ = 0.0; +} + +void VideoWindow::SetCloseHandler(CloseHandler handler) { + close_handler_ = std::move(handler); } void VideoWindow::OnFrameAvailable() { @@ -115,36 +132,49 @@ LRESULT VideoWindow::WndProc(HWND hwnd, UINT message, WPARAM wparam, repaint_pending_.store(false); InvalidateRect(hwnd, nullptr, FALSE); return 0; + case kMsgApplyAspect: + ApplyAspectToWindow(aspect_ratio_); + return 0; + case WM_GETMINMAXINFO: { + auto* info = reinterpret_cast(lparam); + RECT rect = {0, 0, kMinClientWidth, kMinClientHeight}; + AdjustWindowRectEx(&rect, GetWindowLongW(hwnd, GWL_STYLE), FALSE, + GetWindowLongW(hwnd, GWL_EXSTYLE)); + info->ptMinTrackSize.x = rect.right - rect.left; + info->ptMinTrackSize.y = rect.bottom - rect.top; + return 0; + } + case WM_SIZING: { + auto* rect = reinterpret_cast(lparam); + AdjustSizingRect(rect, wparam); + return TRUE; + } case WM_SIZE: InvalidateRect(hwnd, nullptr, FALSE); return 0; - case WM_LBUTTONDBLCLK: - ToggleFullScreen(); - return 0; case WM_KEYDOWN: if (wparam == VK_ESCAPE) { - if (full_screen_) { - ToggleFullScreen(); - } else { - SendMessageW(hwnd, WM_CLOSE, 0, 0); - } - return 0; - } - if (wparam == VK_F11 || wparam == 'F') { - ToggleFullScreen(); + // 关窗即停止投屏(由 close_handler_ 通知 Flutter)。 + SendMessageW(hwnd, WM_CLOSE, 0, 0); return 0; } break; case WM_CLOSE: DestroyWindow(hwnd); return 0; - case WM_DESTROY: + case WM_DESTROY: { hwnd_ = nullptr; open_.store(false); repaint_pending_.store(false); provider_ = nullptr; - full_screen_ = false; + aspect_ratio_ = 0.0; + applied_aspect_ = 0.0; + CloseHandler handler = close_handler_; + if (handler) { + handler(); + } return 0; + } default: break; } @@ -168,6 +198,14 @@ void VideoWindow::Paint() { const int client_height = client.bottom - client.top; if (frame && !frame->empty() && width > 0 && height > 0 && client_width > 0 && client_height > 0) { + const double aspect = + static_cast(width) / static_cast(height); + aspect_ratio_ = aspect; + // 首帧(或分辨率/方向变化)时把窗口调成同比例的尺寸。 + if (std::fabs(aspect - applied_aspect_) > 0.01) { + PostMessageW(hwnd_, kMsgApplyAspect, 0, 0); + } + // 保持宽高比,四周留黑边(竖屏串流不会被拉伸)。 const double scale = std::min( static_cast(client_width) / static_cast(width), @@ -196,8 +234,7 @@ void VideoWindow::Paint() { SetBkMode(hdc, TRANSPARENT); SetTextColor(hdc, RGB(170, 170, 170)); RECT text_rect = client; - DrawTextW(hdc, - L"等待被控端画面…\r\n请在手机弹窗中点击「允许」", -1, &text_rect, + DrawTextW(hdc, L"等待被控端画面…\r\n请在手机弹窗中点击「允许」", -1, &text_rect, DT_CENTER | DT_VCENTER | DT_WORDBREAK); SelectObject(hdc, previous); } @@ -205,32 +242,135 @@ void VideoWindow::Paint() { EndPaint(hwnd_, &paint); } -void VideoWindow::ToggleFullScreen() { - if (hwnd_ == nullptr) { +void VideoWindow::ApplyAspectToWindow(double aspect) { + if (hwnd_ == nullptr || aspect <= 0.0) { return; } - if (!full_screen_) { - saved_style_ = GetWindowLongW(hwnd_, GWL_STYLE); - saved_placement_.length = sizeof(saved_placement_); - GetWindowPlacement(hwnd_, &saved_placement_); - - MONITORINFO monitor = {}; - monitor.cbSize = sizeof(monitor); - GetMonitorInfoW(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST), - &monitor); - - SetWindowLongW(hwnd_, GWL_STYLE, saved_style_ & ~WS_OVERLAPPEDWINDOW); - SetWindowPos(hwnd_, nullptr, monitor.rcMonitor.left, monitor.rcMonitor.top, - monitor.rcMonitor.right - monitor.rcMonitor.left, - monitor.rcMonitor.bottom - monitor.rcMonitor.top, - SWP_NOZORDER | SWP_FRAMECHANGED); - full_screen_ = true; - } else { - SetWindowLongW(hwnd_, GWL_STYLE, saved_style_); - SetWindowPlacement(hwnd_, &saved_placement_); - SetWindowPos(hwnd_, nullptr, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); - full_screen_ = false; + MONITORINFO monitor = {}; + monitor.cbSize = sizeof(monitor); + const HMONITOR target = MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST); + if (target == nullptr || !GetMonitorInfoW(target, &monitor)) { + return; + } + applied_aspect_ = aspect; + + const RECT work = monitor.rcWork; + const int work_width = work.right - work.left; + const int work_height = work.bottom - work.top; + + int client_width = work_width * 4 / 5; + int client_height = static_cast(client_width / aspect); + const int max_client_height = work_height * 4 / 5; + if (client_height > max_client_height) { + client_height = max_client_height; + client_width = static_cast(client_height * aspect); + } + client_width = (std::max)(client_width, kMinClientWidth); + client_height = (std::max)(client_height, kMinClientHeight); + + RECT rect = {0, 0, client_width, client_height}; + AdjustWindowRectEx(&rect, GetWindowLongW(hwnd_, GWL_STYLE), FALSE, + GetWindowLongW(hwnd_, GWL_EXSTYLE)); + const int window_width = rect.right - rect.left; + const int window_height = rect.bottom - rect.top; + const int x = work.left + (work_width - window_width) / 2; + const int y = work.top + (work_height - window_height) / 2; + + SetWindowPos(hwnd_, nullptr, x, y, window_width, window_height, + SWP_NOZORDER | SWP_NOACTIVATE); +} + +void VideoWindow::AdjustSizingRect(RECT* rect, WPARAM edge) const { + if (rect == nullptr || aspect_ratio_ <= 0.0) { + return; + } + RECT window_rect = {}; + RECT client_rect = {}; + GetWindowRect(hwnd_, &window_rect); + GetClientRect(hwnd_, &client_rect); + const int frame_width = + (window_rect.right - window_rect.left) - client_rect.right; + const int frame_height = + (window_rect.bottom - window_rect.top) - client_rect.bottom; + + int client_width = (rect->right - rect->left) - frame_width; + int client_height = (rect->bottom - rect->top) - frame_height; + client_width = (std::max)(client_width, kMinClientWidth); + client_height = (std::max)(client_height, kMinClientHeight); + + switch (edge) { + case WMSZ_TOP: + case WMSZ_BOTTOM: + // 上下拖动:以高度为准算宽度,水平居中。 + client_width = static_cast(client_height * aspect_ratio_); + break; + default: + // 左右边与四角:以宽度为准算高度。 + client_height = static_cast(client_width / aspect_ratio_); + break; + } + client_height = (std::max)(client_height, kMinClientHeight); + client_width = (std::max)(client_width, kMinClientWidth); + + const int width = client_width + frame_width; + const int height = client_height + frame_height; + + switch (edge) { + case WMSZ_TOPLEFT: + // 右下角固定。 + rect->left = rect->right - width; + rect->top = rect->bottom - height; + break; + case WMSZ_TOPRIGHT: + // 左下角固定。 + rect->right = rect->left + width; + rect->top = rect->bottom - height; + break; + case WMSZ_BOTTOMLEFT: + // 右上角固定。 + rect->left = rect->right - width; + rect->bottom = rect->top + height; + break; + case WMSZ_BOTTOMRIGHT: + // 左上角固定。 + rect->right = rect->left + width; + rect->bottom = rect->top + height; + break; + case WMSZ_LEFT: + // 右边固定,垂直居中。 + rect->left = rect->right - width; + { + const int center_y = (rect->top + rect->bottom) / 2; + rect->top = center_y - height / 2; + rect->bottom = rect->top + height; + } + break; + case WMSZ_RIGHT: + // 左边固定,垂直居中。 + rect->right = rect->left + width; + { + const int center_y = (rect->top + rect->bottom) / 2; + rect->top = center_y - height / 2; + rect->bottom = rect->top + height; + } + break; + case WMSZ_TOP: + // 底边固定,水平居中。 + rect->top = rect->bottom - height; + { + const int center_x = (rect->left + rect->right) / 2; + rect->left = center_x - width / 2; + rect->right = rect->left + width; + } + break; + default: + // WMSZ_BOTTOM:顶边固定,水平居中。 + rect->bottom = rect->top + height; + { + const int center_x = (rect->left + rect->right) / 2; + rect->left = center_x - width / 2; + rect->right = rect->left + width; + } + break; } - InvalidateRect(hwnd_, nullptr, FALSE); } diff --git a/flutter_sender/windows/runner/video_window.h b/flutter_sender/windows/runner/video_window.h index 2ccba78..2164aff 100644 --- a/flutter_sender/windows/runner/video_window.h +++ b/flutter_sender/windows/runner/video_window.h @@ -12,13 +12,18 @@ // 独立串流窗口:一个原生 Win32 顶层窗口,直接用 GDI 绘制解码后的 BGRA 帧。 // // 它不依赖 Flutter 引擎(不新建引擎、不跨引擎共享纹理),因此可以随意拖动到 -// 第二块显示器、单独最大化 / 全屏,主窗口最小化也不影响画面。 +// 第二块显示器。窗口尺寸始终与视频宽高比一致: +// - 首帧到达时按视频比例自动调整窗口大小并居中; +// - 用户拖动边框时锁定比例; +// - 不提供最大化与双击全屏。 class VideoWindow { public: // 取当前帧;返回空表示暂无画面。返回的 shared_ptr 保证绘制期间帧不会被回收。 using FrameProvider = std::function>(int* width, int* height)>; + // 用户主动关闭窗口(点关闭按钮 / 按 ESC)时回调。 + using CloseHandler = std::function; VideoWindow(); ~VideoWindow(); @@ -32,6 +37,9 @@ class VideoWindow { // 解码线程收到新帧时调用,线程安全。 void OnFrameAvailable(); + // 设置/清除用户关闭回调;传 nullptr 清除。 + void SetCloseHandler(CloseHandler handler); + bool IsOpen() const { return open_.load(); } private: @@ -39,15 +47,21 @@ class VideoWindow { LPARAM lparam); LRESULT WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); void Paint(); - void ToggleFullScreen(); + // 按视频比例调整窗口大小并居中(首帧或宽高比变化时调用)。 + void ApplyAspectToWindow(double aspect); + // 把窗口矩形修正为符合当前宽高比(WM_SIZING 用)。 + void AdjustSizingRect(RECT* rect, WPARAM edge) const; HWND hwnd_ = nullptr; std::atomic open_{false}; std::atomic repaint_pending_{false}; FrameProvider provider_; - bool full_screen_ = false; - WINDOWPLACEMENT saved_placement_ = {}; - LONG saved_style_ = 0; + CloseHandler close_handler_; + + // 当前视频宽高比(宽/高),0 表示还没有画面。只在窗口线程读写。 + double aspect_ratio_ = 0.0; + // 已经应用过的宽高比,避免每帧都触发 SetWindowPos。 + double applied_aspect_ = 0.0; }; #endif // RUNNER_VIDEO_WINDOW_H_